blob: 7f9af0e63424c3b8d57064f7348b93c90a6a5c49 [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 Żenczykowskidc886222022-09-17 06:09:22 +0000187 private static IBpfMap<S32, U32> getConfigurationMap() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000188 try {
189 return new BpfMap<>(
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000190 CONFIGURATION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U32.class);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000191 } catch (ErrnoException e) {
192 throw new IllegalStateException("Cannot open netd configuration map", e);
193 }
194 }
195
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000196 private static IBpfMap<S32, UidOwnerValue> getUidOwnerMap() {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000197 try {
198 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000199 UID_OWNER_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, UidOwnerValue.class);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000200 } catch (ErrnoException e) {
201 throw new IllegalStateException("Cannot open uid owner map", e);
202 }
203 }
204
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000205 private static IBpfMap<S32, U8> getUidPermissionMap() {
Motomu Utsumi65271202022-07-05 08:21:41 +0000206 try {
207 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000208 UID_PERMISSION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U8.class);
Motomu Utsumi65271202022-07-05 08:21:41 +0000209 } catch (ErrnoException e) {
210 throw new IllegalStateException("Cannot open uid permission map", e);
211 }
212 }
213
Motomu Utsumib9548862022-09-06 16:30:05 +0900214 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> getCookieTagMap() {
215 try {
216 return new BpfMap<>(COOKIE_TAG_MAP_PATH, BpfMap.BPF_F_RDWR,
217 CookieTagMapKey.class, CookieTagMapValue.class);
218 } catch (ErrnoException e) {
219 throw new IllegalStateException("Cannot open cookie tag map", e);
220 }
221 }
222
Ken Chen24330172023-10-20 13:02:14 +0800223 private static IBpfMap<S32, U8> getDataSaverEnabledMap() {
224 try {
225 return new BpfMap<>(
226 DATA_SAVER_ENABLED_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U8.class);
227 } catch (ErrnoException e) {
228 throw new IllegalStateException("Cannot open data saver enabled map", e);
229 }
230 }
231
Motomu Utsumi77b49992023-10-23 17:06:12 +0900232 private static IBpfMap<IngressDiscardKey, IngressDiscardValue> getIngressDiscardMap() {
233 try {
234 return new BpfMap<>(INGRESS_DISCARD_MAP_PATH, BpfMap.BPF_F_RDWR,
235 IngressDiscardKey.class, IngressDiscardValue.class);
236 } catch (ErrnoException e) {
237 throw new IllegalStateException("Cannot open ingress discard map", e);
238 }
239 }
240
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000241 private static void initBpfMaps() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000242 if (sConfigurationMap == null) {
243 sConfigurationMap = getConfigurationMap();
244 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000245 try {
246 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY,
247 new U32(UID_RULES_DEFAULT_CONFIGURATION));
248 } catch (ErrnoException e) {
249 throw new IllegalStateException("Failed to initialize uid rules configuration", e);
250 }
251 try {
252 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
253 new U32(STATS_SELECT_MAP_A));
254 } catch (ErrnoException e) {
255 throw new IllegalStateException("Failed to initialize current stats configuration", e);
256 }
257
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000258 if (sUidOwnerMap == null) {
259 sUidOwnerMap = getUidOwnerMap();
260 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000261 try {
262 sUidOwnerMap.clear();
263 } catch (ErrnoException e) {
264 throw new IllegalStateException("Failed to initialize uid owner map", e);
265 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000266
267 if (sUidPermissionMap == null) {
268 sUidPermissionMap = getUidPermissionMap();
269 }
Motomu Utsumib9548862022-09-06 16:30:05 +0900270
271 if (sCookieTagMap == null) {
272 sCookieTagMap = getCookieTagMap();
273 }
Ken Chen24330172023-10-20 13:02:14 +0800274
275 if (sDataSaverEnabledMap == null) {
276 sDataSaverEnabledMap = getDataSaverEnabledMap();
277 }
278 try {
279 sDataSaverEnabledMap.updateEntry(DATA_SAVER_ENABLED_KEY, new U8(DATA_SAVER_DISABLED));
280 } catch (ErrnoException e) {
281 throw new IllegalStateException("Failed to initialize data saver configuration", e);
282 }
Motomu Utsumi77b49992023-10-23 17:06:12 +0900283
284 if (sIngressDiscardMap == null) {
285 sIngressDiscardMap = getIngressDiscardMap();
286 }
287 try {
288 sIngressDiscardMap.clear();
289 } catch (ErrnoException e) {
290 throw new IllegalStateException("Failed to initialize ingress discard map", e);
291 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000292 }
293
Ken Chenf5f51332022-01-28 10:08:16 +0800294 /**
295 * Initializes the class if it is not already initialized. This method will open maps but not
296 * cause any other effects. This method may be called multiple times on any thread.
297 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000298 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800299 if (sInitialized) return;
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000300 initBpfMaps();
Ken Chenf5f51332022-01-28 10:08:16 +0800301 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800302 }
303
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000304 /**
305 * Dependencies of BpfNetMaps, for injection in tests.
306 */
307 @VisibleForTesting
308 public static class Dependencies {
309 /**
310 * Get interface index.
311 */
312 public int getIfIndex(final String ifName) {
313 return Os.if_nametoindex(ifName);
314 }
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000315
316 /**
Motomu Utsumi77b49992023-10-23 17:06:12 +0900317 * Get interface name
318 */
319 public String getIfName(final int ifIndex) {
320 return Os.if_indextoname(ifIndex);
321 }
322
323 /**
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000324 * Call synchronize_rcu()
325 */
326 public int synchronizeKernelRCU() {
327 return native_synchronizeKernelRCU();
328 }
Motomu Utsumi166f9662022-09-01 10:35:29 +0900329
330 /**
331 * Build Stats Event for NETWORK_BPF_MAP_INFO atom
332 */
333 public StatsEvent buildStatsEvent(final int cookieTagMapSize, final int uidOwnerMapSize,
334 final int uidPermissionMapSize) {
335 return ConnectivityStatsLog.buildStatsEvent(NETWORK_BPF_MAP_INFO, cookieTagMapSize,
336 uidOwnerMapSize, uidPermissionMapSize);
337 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000338 }
339
markchien49e944c2022-03-01 15:22:20 +0800340 /** Constructor used after T that doesn't need to use netd anymore. */
Junyu Lai626045a2023-08-28 18:49:44 +0800341 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000342 public BpfNetMaps(final Context context) {
343 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800344
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000345 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800346 }
347
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000348 public BpfNetMaps(final Context context, final INetd netd) {
349 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000350 }
351
352 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000353 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000354 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000355 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000356 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800357 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000358 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800359 }
360
Ken Chenf5f51332022-01-28 10:08:16 +0800361 private void maybeThrow(final int err, final String msg) {
362 if (err != 0) {
363 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
364 }
365 }
366
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000367 private void throwIfPreT(final String msg) {
368 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000369 throw new UnsupportedOperationException(msg);
370 }
371 }
372
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000373 private void removeRule(final int uid, final long match, final String caller) {
374 try {
375 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000376 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000377
378 if (oldMatch == null) {
379 throw new ServiceSpecificException(ENOENT,
380 "sUidOwnerMap does not have entry for uid: " + uid);
381 }
382
383 final UidOwnerValue newMatch = new UidOwnerValue(
384 (match == IIF_MATCH) ? 0 : oldMatch.iif,
385 oldMatch.rule & ~match
386 );
387
388 if (newMatch.rule == 0) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000389 sUidOwnerMap.deleteEntry(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000390 } else {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000391 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000392 }
393 }
394 } catch (ErrnoException e) {
395 throw new ServiceSpecificException(e.errno,
396 caller + " failed to remove rule: " + Os.strerror(e.errno));
397 }
398 }
399
Maciej Żenczykowski6c1c6bb2022-09-16 06:55:33 +0000400 private void addRule(final int uid, final long match, final int iif, final String caller) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000401 if (match != IIF_MATCH && iif != 0) {
402 throw new ServiceSpecificException(EINVAL,
403 "Non-interface match must have zero interface index");
404 }
405
406 try {
407 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000408 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi389278e2022-06-28 07:05:05 +0000409
410 final UidOwnerValue newMatch;
411 if (oldMatch != null) {
412 newMatch = new UidOwnerValue(
413 (match == IIF_MATCH) ? iif : oldMatch.iif,
414 oldMatch.rule | match
415 );
416 } else {
417 newMatch = new UidOwnerValue(
418 iif,
419 match
420 );
421 }
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000422 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi389278e2022-06-28 07:05:05 +0000423 }
424 } catch (ErrnoException e) {
425 throw new ServiceSpecificException(e.errno,
426 caller + " failed to add rule: " + Os.strerror(e.errno));
427 }
428 }
429
430 private void addRule(final int uid, final long match, final String caller) {
431 addRule(uid, match, 0 /* iif */, caller);
432 }
433
Ken Chenf5f51332022-01-28 10:08:16 +0800434 /**
435 * Add naughty app bandwidth rule for specific app
436 *
437 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800438 * @throws ServiceSpecificException in case of failure, with an error code indicating the
439 * cause of the failure.
440 */
Junyu Lai626045a2023-08-28 18:49:44 +0800441 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900442 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000443 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000444
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900445 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800446 }
447
Ken Chenf5f51332022-01-28 10:08:16 +0800448 /**
449 * Remove 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 removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000457 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000458
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900459 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800460 }
461
Ken Chenf5f51332022-01-28 10:08:16 +0800462 /**
463 * Add nice 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 addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000471 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000472
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900473 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800474 }
475
Ken Chenf5f51332022-01-28 10:08:16 +0800476 /**
477 * Remove 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 removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000485 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000486
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900487 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800488 }
489
Ken Chenf5f51332022-01-28 10:08:16 +0800490 /**
491 * Set target firewall child chain
492 *
493 * @param childChain target chain to enable
494 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000495 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800496 * @throws ServiceSpecificException in case of failure, with an error code indicating the
497 * cause of the failure.
498 */
Junyu Lai626045a2023-08-28 18:49:44 +0800499 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900500 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000501 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000502
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900503 final long match = getMatchByFirewallChain(childChain);
504 try {
505 synchronized (sUidRulesConfigBpfMapLock) {
506 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
507 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
508 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000509 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900510 } catch (ErrnoException e) {
511 throw new ServiceSpecificException(e.errno,
512 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000513 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800514 }
515
516 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000517 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000518 *
519 * @param childChain target chain
520 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
521 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000522 * @throws ServiceSpecificException in case of failure, with an error code indicating the
523 * cause of the failure.
Junyu Lai626045a2023-08-28 18:49:44 +0800524 *
525 * @deprecated Use {@link BpfNetMapsReader#isChainEnabled} instead.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000526 */
Junyu Lai626045a2023-08-28 18:49:44 +0800527 // TODO: Migrate the callers to use {@link BpfNetMapsReader#isChainEnabled} instead.
528 @Deprecated
529 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000530 public boolean isChainEnabled(final int childChain) {
Junyu Lai626045a2023-08-28 18:49:44 +0800531 return BpfNetMapsReader.isChainEnabled(sConfigurationMap, childChain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000532 }
533
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900534 private Set<Integer> asSet(final int[] uids) {
535 final Set<Integer> uidSet = new ArraySet<>();
Motomu Utsumi77b49992023-10-23 17:06:12 +0900536 for (final int uid : uids) {
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900537 uidSet.add(uid);
538 }
539 return uidSet;
540 }
541
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000542 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800543 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000544 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800545 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000546 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800547 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000548 * @throws UnsupportedOperationException if called on pre-T devices.
549 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800550 */
Junyu Lai626045a2023-08-28 18:49:44 +0800551 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000552 public void replaceUidChain(final int chain, final int[] uids) {
553 throwIfPreT("replaceUidChain is not available on pre-T devices");
554
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900555 final long match;
556 try {
557 match = getMatchByFirewallChain(chain);
558 } catch (ServiceSpecificException e) {
559 // Throws IllegalArgumentException to keep the behavior of
560 // ConnectivityManager#replaceFirewallChain API
561 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
562 }
563 final Set<Integer> uidSet = asSet(uids);
564 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
565 try {
566 synchronized (sUidOwnerMap) {
567 sUidOwnerMap.forEach((uid, config) -> {
568 // config could be null if there is a concurrent entry deletion.
569 // http://b/220084230. But sUidOwnerMap update must be done while holding a
570 // lock, so this should not happen.
571 if (config == null) {
572 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
573 } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
574 uidSetToRemoveRule.add((int) uid.val);
575 }
576 });
Motomu Utsumic7c16852022-08-03 06:51:41 +0000577
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900578 for (final int uid : uidSetToRemoveRule) {
579 removeRule(uid, match, "replaceUidChain");
Motomu Utsumic7c16852022-08-03 06:51:41 +0000580 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900581 for (final int uid : uids) {
582 addRule(uid, match, "replaceUidChain");
583 }
Motomu Utsumic7c16852022-08-03 06:51:41 +0000584 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900585 } catch (ErrnoException | ServiceSpecificException e) {
586 Log.e(TAG, "replaceUidChain failed: " + e);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800587 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800588 }
589
Ken Chenf5f51332022-01-28 10:08:16 +0800590 /**
591 * Set firewall rule for uid
592 *
593 * @param childChain target chain
594 * @param uid uid to allow/deny
595 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800596 * @throws ServiceSpecificException in case of failure, with an error code indicating the
597 * cause of the failure.
598 */
Junyu Lai626045a2023-08-28 18:49:44 +0800599 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900600 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000601 throwIfPreT("setUidRule is not available on pre-T devices");
602
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900603 final long match = getMatchByFirewallChain(childChain);
604 final boolean isAllowList = isFirewallAllowList(childChain);
605 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
606 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000607
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900608 if (add) {
609 addRule(uid, match, "setUidRule");
Motomu Utsumi40230be2022-07-05 03:27:35 +0000610 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900611 removeRule(uid, match, "setUidRule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000612 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800613 }
614
615 /**
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900616 * Get firewall rule of specified firewall chain on specified uid.
617 *
618 * @param childChain target chain
619 * @param uid target uid
620 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
621 * @throws UnsupportedOperationException if called on pre-T devices.
622 * @throws ServiceSpecificException in case of failure, with an error code indicating the
623 * cause of the failure.
Junyu Lai626045a2023-08-28 18:49:44 +0800624 *
625 * @deprecated use {@link BpfNetMapsReader#getUidRule} instead.
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900626 */
Junyu Lai626045a2023-08-28 18:49:44 +0800627 // TODO: Migrate the callers to use {@link BpfNetMapsReader#getUidRule} instead.
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900628 public int getUidRule(final int childChain, final int uid) {
Junyu Lai626045a2023-08-28 18:49:44 +0800629 return BpfNetMapsReader.getUidRule(sUidOwnerMap, childChain, uid);
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900630 }
631
Motomu Utsumid44a33a2023-03-28 18:08:12 +0900632 private Set<Integer> getUidsMatchEnabled(final int childChain) throws ErrnoException {
633 final long match = getMatchByFirewallChain(childChain);
634 Set<Integer> uids = new ArraySet<>();
635 synchronized (sUidOwnerMap) {
636 sUidOwnerMap.forEach((uid, val) -> {
637 if (val == null) {
638 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
639 } else {
640 if ((val.rule & match) != 0) {
641 uids.add(uid.val);
642 }
643 }
644 });
645 }
646 return uids;
647 }
648
649 /**
650 * Get uids that has FIREWALL_RULE_ALLOW on allowlist chain.
651 * Allowlist means the firewall denies all by default, uids must be explicitly allowed.
652 *
653 * Note that uids that has FIREWALL_RULE_DENY on allowlist chain can not be computed from the
654 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_ALLOW rule in bpf map
655 * are determined to have FIREWALL_RULE_DENY.
656 *
657 * @param childChain target chain
658 * @return Set of uids
659 */
660 public Set<Integer> getUidsWithAllowRuleOnAllowListChain(final int childChain)
661 throws ErrnoException {
662 if (!isFirewallAllowList(childChain)) {
663 throw new IllegalArgumentException("getUidsWithAllowRuleOnAllowListChain is called with"
664 + " denylist chain:" + childChain);
665 }
666 // Corresponding match is enabled for uids that has FIREWALL_RULE_ALLOW on allowlist chain.
667 return getUidsMatchEnabled(childChain);
668 }
669
670 /**
671 * Get uids that has FIREWALL_RULE_DENY on denylist chain.
672 * Denylist means the firewall allows all by default, uids must be explicitly denyed
673 *
674 * Note that uids that has FIREWALL_RULE_ALLOW on denylist chain can not be computed from the
675 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_DENY rule in bpf map
676 * are determined to have the FIREWALL_RULE_ALLOW.
677 *
678 * @param childChain target chain
679 * @return Set of uids
680 */
681 public Set<Integer> getUidsWithDenyRuleOnDenyListChain(final int childChain)
682 throws ErrnoException {
683 if (isFirewallAllowList(childChain)) {
684 throw new IllegalArgumentException("getUidsWithDenyRuleOnDenyListChain is called with"
685 + " allowlist chain:" + childChain);
686 }
687 // Corresponding match is enabled for uids that has FIREWALL_RULE_DENY on denylist chain.
688 return getUidsMatchEnabled(childChain);
689 }
690
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900691 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800692 * Add ingress interface filtering rules to a list of UIDs
693 *
694 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
695 * allowed interface and loopback to be sent to the list of UIDs.
696 *
697 * Calling this method on one or more UIDs with an existing filtering rule but a different
698 * interface name will result in the filtering rule being updated to allow the new interface
699 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
700 *
701 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800702 * be received.
703 * @param uids an array of UIDs which the filtering rules will be set
704 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800705 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800706 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800707 */
Ken Chenf5f51332022-01-28 10:08:16 +0800708 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000709 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800710 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800711 return;
712 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000713
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900714 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
715 // ifIndex is set to 0.
716 final int ifIndex;
717 if (ifName == null) {
718 ifIndex = 0;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000719 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900720 ifIndex = mDeps.getIfIndex(ifName);
721 if (ifIndex == 0) {
722 throw new ServiceSpecificException(ENODEV,
723 "Failed to get index of interface " + ifName);
724 }
725 }
726 for (final int uid : uids) {
727 try {
728 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
729 } catch (ServiceSpecificException e) {
730 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
731 }
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000732 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800733 }
734
735 /**
736 * Remove ingress interface filtering rules from a list of UIDs
737 *
738 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
739 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
740 *
741 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800742 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800743 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800744 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800745 */
Ken Chenf5f51332022-01-28 10:08:16 +0800746 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000747 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800748 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800749 return;
750 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000751
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900752 for (final int uid : uids) {
753 try {
754 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
755 } catch (ServiceSpecificException e) {
756 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000757 }
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000758 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800759 }
760
Ken Chenf5f51332022-01-28 10:08:16 +0800761 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000762 * Update lockdown rule for uid
763 *
764 * @param uid target uid to add/remove the rule
765 * @param add {@code true} to add the rule, {@code false} to remove the rule.
766 * @throws ServiceSpecificException in case of failure, with an error code indicating the
767 * cause of the failure.
768 */
Junyu Lai626045a2023-08-28 18:49:44 +0800769 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000770 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000771 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000772
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900773 if (add) {
774 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
Motomu Utsumi697b2992022-06-30 02:25:29 +0000775 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900776 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000777 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000778 }
779
780 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800781 * Request netd to change the current active network stats map.
782 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000783 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800784 * @throws ServiceSpecificException in case of failure, with an error code indicating the
785 * cause of the failure.
786 */
Junyu Lai626045a2023-08-28 18:49:44 +0800787 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien49e944c2022-03-01 15:22:20 +0800788 public void swapActiveStatsMap() {
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000789 throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
790
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900791 try {
792 synchronized (sCurrentStatsMapConfigLock) {
793 final long config = sConfigurationMap.getValue(
794 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
795 final long newConfig = (config == STATS_SELECT_MAP_A)
796 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
797 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
798 new U32(newConfig));
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000799 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900800 } catch (ErrnoException e) {
801 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000802 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900803
804 // After changing the config, it's needed to make sure all the current running eBPF
805 // programs are finished and all the CPUs are aware of this config change before the old
806 // map is modified. So special hack is needed here to wait for the kernel to do a
807 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
808 // be available to all cores and the next eBPF programs triggered inside the kernel will
809 // use the new map configuration. So once this function returns it is safe to modify the
810 // old stats map without concerning about race between the kernel and userspace.
811 final int err = mDeps.synchronizeKernelRCU();
812 maybeThrow(err, "synchronizeKernelRCU failed");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800813 }
814
Ken Chenf5f51332022-01-28 10:08:16 +0800815 /**
816 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
817 * specified. Or remove all permissions from the uids.
818 *
819 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
820 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
821 * revoke all permissions for the uids.
822 * @param uids uid of users to grant permission
823 * @throws RemoteException when netd has crashed.
824 */
825 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000826 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800827 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800828 return;
829 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000830
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900831 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
832 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000833 for (final int uid : uids) {
834 try {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900835 sUidPermissionMap.deleteEntry(new S32(uid));
Motomu Utsumi65271202022-07-05 08:21:41 +0000836 } catch (ErrnoException e) {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900837 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
Motomu Utsumi65271202022-07-05 08:21:41 +0000838 }
839 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900840 return;
841 }
842
843 for (final int uid : uids) {
844 try {
845 sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
846 } catch (ErrnoException e) {
847 Log.e(TAG, "Failed to set permission "
848 + permissions + " to uid " + uid + ": " + e);
849 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000850 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800851 }
852
Ken Chen24330172023-10-20 13:02:14 +0800853 /**
854 * Set Data Saver enabled or disabled
855 *
856 * @param enable whether Data Saver is enabled or disabled.
857 * @throws UnsupportedOperationException if called on pre-T devices.
858 * @throws ServiceSpecificException in case of failure, with an error code indicating the
859 * cause of the failure.
860 */
861 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
862 public void setDataSaverEnabled(boolean enable) {
863 throwIfPreT("setDataSaverEnabled is not available on pre-T devices");
864
865 try {
866 final short config = enable ? DATA_SAVER_ENABLED : DATA_SAVER_DISABLED;
867 sDataSaverEnabledMap.updateEntry(DATA_SAVER_ENABLED_KEY, new U8(config));
868 } catch (ErrnoException e) {
869 throw new ServiceSpecificException(e.errno, "Unable to set data saver: "
870 + Os.strerror(e.errno));
871 }
872 }
873
Motomu Utsumi77b49992023-10-23 17:06:12 +0900874 /**
875 * Set ingress discard rule
876 *
877 * @param address target address to set the ingress discard rule
878 * @param iface allowed interface
879 */
880 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
881 public void setIngressDiscardRule(final InetAddress address, final String iface) {
882 throwIfPreT("setIngressDiscardRule is not available on pre-T devices");
883 final int ifIndex = mDeps.getIfIndex(iface);
884 if (ifIndex == 0) {
885 Log.e(TAG, "Failed to get if index, skip setting ingress discard rule for " + address
886 + "(" + iface + ")");
887 return;
888 }
889 try {
890 sIngressDiscardMap.updateEntry(new IngressDiscardKey(address),
891 new IngressDiscardValue(ifIndex, ifIndex));
892 } catch (ErrnoException e) {
893 Log.e(TAG, "Failed to set ingress discard rule for " + address + "("
894 + iface + "), " + e);
895 }
896 }
897
898 /**
899 * Remove ingress discard rule
900 *
901 * @param address target address to remove the ingress discard rule
902 */
903 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
904 public void removeIngressDiscardRule(final InetAddress address) {
905 throwIfPreT("removeIngressDiscardRule is not available on pre-T devices");
906 try {
907 sIngressDiscardMap.deleteEntry(new IngressDiscardKey(address));
908 } catch (ErrnoException e) {
909 Log.e(TAG, "Failed to remove ingress discard rule for " + address + ", " + e);
910 }
911 }
912
Motomu Utsumi166f9662022-09-01 10:35:29 +0900913 /** Register callback for statsd to pull atom. */
Junyu Lai626045a2023-08-28 18:49:44 +0800914 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi166f9662022-09-01 10:35:29 +0900915 public void setPullAtomCallback(final Context context) {
916 throwIfPreT("setPullAtomCallback is not available on pre-T devices");
917
918 final StatsManager statsManager = context.getSystemService(StatsManager.class);
919 statsManager.setPullAtomCallback(NETWORK_BPF_MAP_INFO, null /* metadata */,
920 BackgroundThread.getExecutor(), this::pullBpfMapInfoAtom);
921 }
922
923 private <K extends Struct, V extends Struct> int getMapSize(IBpfMap<K, V> map)
924 throws ErrnoException {
925 // forEach could restart iteration from the beginning if there is a concurrent entry
926 // deletion. netd and skDestroyListener could delete CookieTagMap entry concurrently.
927 // So using Set to count the number of entry in the map.
928 Set<K> keySet = new ArraySet<>();
929 map.forEach((k, v) -> keySet.add(k));
930 return keySet.size();
931 }
932
933 /** Callback for StatsManager#setPullAtomCallback */
934 @VisibleForTesting
935 public int pullBpfMapInfoAtom(final int atomTag, final List<StatsEvent> data) {
936 if (atomTag != NETWORK_BPF_MAP_INFO) {
937 Log.e(TAG, "Unexpected atom tag: " + atomTag);
938 return StatsManager.PULL_SKIP;
939 }
940
941 try {
942 data.add(mDeps.buildStatsEvent(getMapSize(sCookieTagMap), getMapSize(sUidOwnerMap),
943 getMapSize(sUidPermissionMap)));
944 } catch (ErrnoException e) {
945 Log.e(TAG, "Failed to pull NETWORK_BPF_MAP_INFO atom: " + e);
946 return StatsManager.PULL_SKIP;
947 }
948 return StatsManager.PULL_SUCCESS;
949 }
950
Motomu Utsumi310850f2022-09-02 12:48:20 +0900951 private String permissionToString(int permissionMask) {
952 if (permissionMask == PERMISSION_NONE) {
953 return "PERMISSION_NONE";
954 }
955 if (permissionMask == PERMISSION_UNINSTALLED) {
956 // PERMISSION_UNINSTALLED should never appear in the map
957 return "PERMISSION_UNINSTALLED error!";
958 }
959
960 final StringJoiner sj = new StringJoiner(" ");
961 for (Pair<Integer, String> permission: PERMISSION_LIST) {
962 final int permissionFlag = permission.first;
963 final String permissionName = permission.second;
964 if ((permissionMask & permissionFlag) != 0) {
965 sj.add(permissionName);
966 permissionMask &= ~permissionFlag;
967 }
968 }
969 if (permissionMask != 0) {
970 sj.add("PERMISSION_UNKNOWN(" + permissionMask + ")");
971 }
972 return sj.toString();
973 }
974
Motomu Utsumi372c9b42022-09-02 19:02:56 +0900975 private void dumpOwnerMatchConfig(final IndentingPrintWriter pw) {
976 try {
977 final long match = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY).val;
978 pw.println("current ownerMatch configuration: " + match + " " + matchToString(match));
979 } catch (ErrnoException e) {
980 pw.println("Failed to read ownerMatch configuration: " + e);
981 }
982 }
983
Motomu Utsumic675d6f2022-09-02 18:15:25 +0900984 private void dumpCurrentStatsMapConfig(final IndentingPrintWriter pw) {
985 try {
986 final long config = sConfigurationMap.getValue(CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
987 final String currentStatsMap =
988 (config == STATS_SELECT_MAP_A) ? "SELECT_MAP_A" : "SELECT_MAP_B";
989 pw.println("current statsMap configuration: " + config + " " + currentStatsMap);
990 } catch (ErrnoException e) {
991 pw.println("Falied to read current statsMap configuration: " + e);
992 }
993 }
994
Ken Chen24330172023-10-20 13:02:14 +0800995 private void dumpDataSaverConfig(final IndentingPrintWriter pw) {
996 try {
997 final short config = sDataSaverEnabledMap.getValue(DATA_SAVER_ENABLED_KEY).val;
998 // Any non-zero value converted from short to boolean is true by convention.
999 pw.println("sDataSaverEnabledMap: " + (config != DATA_SAVER_DISABLED));
1000 } catch (ErrnoException e) {
1001 pw.println("Failed to read data saver configuration: " + e);
1002 }
1003 }
Ken Chene6d511f2022-01-25 11:10:42 +08001004 /**
1005 * Dump BPF maps
1006 *
Motomu Utsumi310850f2022-09-02 12:48:20 +09001007 * @param pw print writer
Ken Chene6d511f2022-01-25 11:10:42 +08001008 * @param fd file descriptor to output
Motomu Utsumi310850f2022-09-02 12:48:20 +09001009 * @param verbose verbose dump flag, if true dump the BpfMap contents
Ken Chene6d511f2022-01-25 11:10:42 +08001010 * @throws IOException when file descriptor is invalid.
1011 * @throws ServiceSpecificException when the method is called on an unsupported device.
1012 */
Junyu Lai626045a2023-08-28 18:49:44 +08001013 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi310850f2022-09-02 12:48:20 +09001014 public void dump(final IndentingPrintWriter pw, final FileDescriptor fd, boolean verbose)
Ken Chene6d511f2022-01-25 11:10:42 +08001015 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00001016 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +08001017 throw new ServiceSpecificException(
1018 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
1019 + " devices, use dumpsys netd trafficcontroller instead.");
1020 }
Maciej Żenczykowskid70a3302023-09-06 16:45:25 +00001021
1022 pw.println("TrafficController"); // required by CTS testDumpBpfNetMaps
Motomu Utsumi310850f2022-09-02 12:48:20 +09001023
Motomu Utsumi316d0572022-09-15 13:24:48 +09001024 pw.println();
Motomu Utsumi310850f2022-09-02 12:48:20 +09001025 if (verbose) {
Motomu Utsumief546a92022-10-05 16:42:29 +09001026 pw.println();
1027 pw.println("BPF map content:");
1028 pw.increaseIndent();
1029
Motomu Utsumi372c9b42022-09-02 19:02:56 +09001030 dumpOwnerMatchConfig(pw);
Motomu Utsumic675d6f2022-09-02 18:15:25 +09001031 dumpCurrentStatsMapConfig(pw);
1032 pw.println();
1033
Motomu Utsumief546a92022-10-05 16:42:29 +09001034 // TODO: Remove CookieTagMap content dump
1035 // NetworkStatsService also dumps CookieTagMap and NetworkStatsService is a right place
1036 // to dump CookieTagMap. But the TagSocketTest in CTS depends on this dump so the tests
1037 // need to be updated before remove the dump from BpfNetMaps.
1038 BpfDump.dumpMap(sCookieTagMap, pw, "sCookieTagMap",
1039 (key, value) -> "cookie=" + key.socketCookie
1040 + " tag=0x" + Long.toHexString(value.tag)
1041 + " uid=" + value.uid);
Motomu Utsumi956d86c2022-09-02 17:01:25 +09001042 BpfDump.dumpMap(sUidOwnerMap, pw, "sUidOwnerMap",
1043 (uid, match) -> {
1044 if ((match.rule & IIF_MATCH) != 0) {
1045 // TODO: convert interface index to interface name by IfaceIndexNameMap
1046 return uid.val + " " + matchToString(match.rule) + " " + match.iif;
1047 } else {
1048 return uid.val + " " + matchToString(match.rule);
1049 }
1050 });
Motomu Utsumi310850f2022-09-02 12:48:20 +09001051 BpfDump.dumpMap(sUidPermissionMap, pw, "sUidPermissionMap",
1052 (uid, permission) -> uid.val + " " + permissionToString(permission.val));
Motomu Utsumi77b49992023-10-23 17:06:12 +09001053 BpfDump.dumpMap(sIngressDiscardMap, pw, "sIngressDiscardMap",
1054 (key, value) -> "[" + key.dstAddr + "]: "
1055 + value.iif1 + "(" + mDeps.getIfName(value.iif1) + "), "
1056 + value.iif2 + "(" + mDeps.getIfName(value.iif2) + ")");
Ken Chen24330172023-10-20 13:02:14 +08001057 dumpDataSaverConfig(pw);
Motomu Utsumief546a92022-10-05 16:42:29 +09001058 pw.decreaseIndent();
Motomu Utsumi310850f2022-09-02 12:48:20 +09001059 }
Ken Chene6d511f2022-01-25 11:10:42 +08001060 }
1061
Maciej Żenczykowski70fbfa42023-07-18 20:14:38 +00001062 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi7abeaa42022-07-20 07:54:18 +00001063 private static native int native_synchronizeKernelRCU();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001064}