blob: 93a2602a6bb930a2dcab050e3278c09e7d66a79d [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;
Maciej Żenczykowski7b8f4752023-11-07 17:04:15 -080048import static android.system.OsConstants.SOCK_RAW;
49import static android.system.OsConstants.SOCK_CLOEXEC;
Ken Chene6d511f2022-01-25 11:10:42 +080050
Motomu Utsumi166f9662022-09-01 10:35:29 +090051import static com.android.server.ConnectivityStatsLog.NETWORK_BPF_MAP_INFO;
52
53import android.app.StatsManager;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000054import android.content.Context;
Junyu Lai626045a2023-08-28 18:49:44 +080055import android.net.BpfNetMapsReader;
Wayne Ma2fde98c2022-01-17 18:04:05 +080056import android.net.INetd;
Junyu Lai626045a2023-08-28 18:49:44 +080057import android.net.UidOwnerValue;
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +000058import android.os.Build;
Wayne Ma2fde98c2022-01-17 18:04:05 +080059import android.os.RemoteException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080060import android.os.ServiceSpecificException;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000061import android.system.ErrnoException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080062import android.system.Os;
Motomu Utsumi1a477b02022-08-23 15:14:56 +090063import android.util.ArraySet;
Motomu Utsumi310850f2022-09-02 12:48:20 +090064import android.util.IndentingPrintWriter;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080065import android.util.Log;
Motomu Utsumi310850f2022-09-02 12:48:20 +090066import android.util.Pair;
Motomu Utsumi166f9662022-09-01 10:35:29 +090067import android.util.StatsEvent;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080068
Maciej Żenczykowskie7da6fd2023-07-18 14:19:19 +000069import androidx.annotation.RequiresApi;
70
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000071import com.android.internal.annotations.VisibleForTesting;
Motomu Utsumi166f9662022-09-01 10:35:29 +090072import com.android.modules.utils.BackgroundThread;
Motomu Utsumi310850f2022-09-02 12:48:20 +090073import com.android.net.module.util.BpfDump;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000074import com.android.net.module.util.BpfMap;
Motomu Utsumi73599a52022-08-24 11:59:21 +090075import com.android.net.module.util.IBpfMap;
Motomu Utsumi166f9662022-09-01 10:35:29 +090076import com.android.net.module.util.Struct;
Maciej Żenczykowski785793f2022-09-17 02:35:20 +000077import com.android.net.module.util.Struct.S32;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000078import com.android.net.module.util.Struct.U32;
Motomu Utsumi65271202022-07-05 08:21:41 +000079import com.android.net.module.util.Struct.U8;
Motomu Utsumib9548862022-09-06 16:30:05 +090080import com.android.net.module.util.bpf.CookieTagMapKey;
81import com.android.net.module.util.bpf.CookieTagMapValue;
Motomu Utsumi77b49992023-10-23 17:06:12 +090082import com.android.net.module.util.bpf.IngressDiscardKey;
83import com.android.net.module.util.bpf.IngressDiscardValue;
Ken Chenf5f51332022-01-28 10:08:16 +080084
Ken Chene6d511f2022-01-25 11:10:42 +080085import java.io.FileDescriptor;
86import java.io.IOException;
Motomu Utsumi77b49992023-10-23 17:06:12 +090087import java.net.InetAddress;
Motomu Utsumi310850f2022-09-02 12:48:20 +090088import java.util.Arrays;
Motomu Utsumi166f9662022-09-01 10:35:29 +090089import java.util.List;
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000090import java.util.Set;
Motomu Utsumi310850f2022-09-02 12:48:20 +090091import java.util.StringJoiner;
Ken Chene6d511f2022-01-25 11:10:42 +080092
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080093/**
94 * BpfNetMaps is responsible for providing traffic controller relevant functionality.
95 *
96 * {@hide}
97 */
98public class BpfNetMaps {
Motomu Utsumi305975f2022-06-27 09:24:32 +000099 static {
100 if (!PRE_T) {
101 System.loadLibrary("service-connectivity");
102 }
103 }
104
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800105 private static final String TAG = "BpfNetMaps";
Wayne Ma2fde98c2022-01-17 18:04:05 +0800106 private final INetd mNetd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000107 private final Dependencies mDeps;
Ken Chenf5f51332022-01-28 10:08:16 +0800108 // Use legacy netd for releases before T.
Ken Chenf5f51332022-01-28 10:08:16 +0800109 private static boolean sInitialized = false;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800110
Motomu Utsumi7628ea32023-08-14 11:09:02 +0900111 private static final String BPF_NET_MAPS_FORCE_DISABLE_JAVA_BPF_MAP =
112 "bpf_net_maps_force_disable_java_bpf_map";
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000113
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000114 // Lock for sConfigurationMap entry for UID_RULES_CONFIGURATION_KEY.
115 // This entry is not accessed by others.
116 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
117 private static final Object sUidRulesConfigBpfMapLock = new Object();
118
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000119 // Lock for sConfigurationMap entry for CURRENT_STATS_MAP_CONFIGURATION_KEY.
120 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
121 // BpfNetMaps is an only writer of this entry.
122 private static final Object sCurrentStatsMapConfigLock = new Object();
123
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000124 private static final long UID_RULES_DEFAULT_CONFIGURATION = 0;
125 private static final long STATS_SELECT_MAP_A = 0;
126 private static final long STATS_SELECT_MAP_B = 1;
127
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000128 private static IBpfMap<S32, U32> sConfigurationMap = null;
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000129 // BpfMap for UID_OWNER_MAP_PATH. This map is not accessed by others.
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000130 private static IBpfMap<S32, UidOwnerValue> sUidOwnerMap = null;
131 private static IBpfMap<S32, U8> sUidPermissionMap = null;
Motomu Utsumib9548862022-09-06 16:30:05 +0900132 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> sCookieTagMap = null;
Ken Chen24330172023-10-20 13:02:14 +0800133 // TODO: Add BOOL class and replace U8?
134 private static IBpfMap<S32, U8> sDataSaverEnabledMap = null;
Motomu Utsumi77b49992023-10-23 17:06:12 +0900135 private static IBpfMap<IngressDiscardKey, IngressDiscardValue> sIngressDiscardMap = null;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000136
Motomu Utsumi310850f2022-09-02 12:48:20 +0900137 private static final List<Pair<Integer, String>> PERMISSION_LIST = Arrays.asList(
138 Pair.create(PERMISSION_INTERNET, "PERMISSION_INTERNET"),
139 Pair.create(PERMISSION_UPDATE_DEVICE_STATS, "PERMISSION_UPDATE_DEVICE_STATS")
140 );
141
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000142 /**
Motomu Utsumi305975f2022-06-27 09:24:32 +0000143 * Set configurationMap for test.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000144 */
145 @VisibleForTesting
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000146 public static void setConfigurationMapForTest(IBpfMap<S32, U32> configurationMap) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000147 sConfigurationMap = configurationMap;
148 }
149
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000150 /**
151 * Set uidOwnerMap for test.
152 */
153 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000154 public static void setUidOwnerMapForTest(IBpfMap<S32, UidOwnerValue> uidOwnerMap) {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000155 sUidOwnerMap = uidOwnerMap;
156 }
157
Motomu Utsumi65271202022-07-05 08:21:41 +0000158 /**
159 * Set uidPermissionMap for test.
160 */
161 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000162 public static void setUidPermissionMapForTest(IBpfMap<S32, U8> uidPermissionMap) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000163 sUidPermissionMap = uidPermissionMap;
164 }
165
Motomu Utsumib9548862022-09-06 16:30:05 +0900166 /**
167 * Set cookieTagMap for test.
168 */
169 @VisibleForTesting
170 public static void setCookieTagMapForTest(
171 IBpfMap<CookieTagMapKey, CookieTagMapValue> cookieTagMap) {
172 sCookieTagMap = cookieTagMap;
173 }
174
Ken Chen24330172023-10-20 13:02:14 +0800175 /**
176 * Set dataSaverEnabledMap for test.
177 */
178 @VisibleForTesting
179 public static void setDataSaverEnabledMapForTest(IBpfMap<S32, U8> dataSaverEnabledMap) {
180 sDataSaverEnabledMap = dataSaverEnabledMap;
181 }
182
Motomu Utsumi77b49992023-10-23 17:06:12 +0900183 /**
184 * Set ingressDiscardMap for test.
185 */
186 @VisibleForTesting
187 public static void setIngressDiscardMapForTest(
188 IBpfMap<IngressDiscardKey, IngressDiscardValue> ingressDiscardMap) {
189 sIngressDiscardMap = ingressDiscardMap;
190 }
191
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000192 private static IBpfMap<S32, U32> getConfigurationMap() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000193 try {
194 return new BpfMap<>(
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000195 CONFIGURATION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U32.class);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000196 } catch (ErrnoException e) {
197 throw new IllegalStateException("Cannot open netd configuration map", e);
198 }
199 }
200
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000201 private static IBpfMap<S32, UidOwnerValue> getUidOwnerMap() {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000202 try {
203 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000204 UID_OWNER_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, UidOwnerValue.class);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000205 } catch (ErrnoException e) {
206 throw new IllegalStateException("Cannot open uid owner map", e);
207 }
208 }
209
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000210 private static IBpfMap<S32, U8> getUidPermissionMap() {
Motomu Utsumi65271202022-07-05 08:21:41 +0000211 try {
212 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000213 UID_PERMISSION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U8.class);
Motomu Utsumi65271202022-07-05 08:21:41 +0000214 } catch (ErrnoException e) {
215 throw new IllegalStateException("Cannot open uid permission map", e);
216 }
217 }
218
Motomu Utsumib9548862022-09-06 16:30:05 +0900219 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> getCookieTagMap() {
220 try {
221 return new BpfMap<>(COOKIE_TAG_MAP_PATH, BpfMap.BPF_F_RDWR,
222 CookieTagMapKey.class, CookieTagMapValue.class);
223 } catch (ErrnoException e) {
224 throw new IllegalStateException("Cannot open cookie tag map", e);
225 }
226 }
227
Ken Chen24330172023-10-20 13:02:14 +0800228 private static IBpfMap<S32, U8> getDataSaverEnabledMap() {
229 try {
230 return new BpfMap<>(
231 DATA_SAVER_ENABLED_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U8.class);
232 } catch (ErrnoException e) {
233 throw new IllegalStateException("Cannot open data saver enabled map", e);
234 }
235 }
236
Motomu Utsumi77b49992023-10-23 17:06:12 +0900237 private static IBpfMap<IngressDiscardKey, IngressDiscardValue> getIngressDiscardMap() {
238 try {
239 return new BpfMap<>(INGRESS_DISCARD_MAP_PATH, BpfMap.BPF_F_RDWR,
240 IngressDiscardKey.class, IngressDiscardValue.class);
241 } catch (ErrnoException e) {
242 throw new IllegalStateException("Cannot open ingress discard map", e);
243 }
244 }
245
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000246 private static void initBpfMaps() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000247 if (sConfigurationMap == null) {
248 sConfigurationMap = getConfigurationMap();
249 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000250 try {
251 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY,
252 new U32(UID_RULES_DEFAULT_CONFIGURATION));
253 } catch (ErrnoException e) {
254 throw new IllegalStateException("Failed to initialize uid rules configuration", e);
255 }
256 try {
257 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
258 new U32(STATS_SELECT_MAP_A));
259 } catch (ErrnoException e) {
260 throw new IllegalStateException("Failed to initialize current stats configuration", e);
261 }
262
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000263 if (sUidOwnerMap == null) {
264 sUidOwnerMap = getUidOwnerMap();
265 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000266 try {
267 sUidOwnerMap.clear();
268 } catch (ErrnoException e) {
269 throw new IllegalStateException("Failed to initialize uid owner map", e);
270 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000271
272 if (sUidPermissionMap == null) {
273 sUidPermissionMap = getUidPermissionMap();
274 }
Motomu Utsumib9548862022-09-06 16:30:05 +0900275
276 if (sCookieTagMap == null) {
277 sCookieTagMap = getCookieTagMap();
278 }
Ken Chen24330172023-10-20 13:02:14 +0800279
280 if (sDataSaverEnabledMap == null) {
281 sDataSaverEnabledMap = getDataSaverEnabledMap();
282 }
283 try {
284 sDataSaverEnabledMap.updateEntry(DATA_SAVER_ENABLED_KEY, new U8(DATA_SAVER_DISABLED));
285 } catch (ErrnoException e) {
286 throw new IllegalStateException("Failed to initialize data saver configuration", e);
287 }
Motomu Utsumi77b49992023-10-23 17:06:12 +0900288
289 if (sIngressDiscardMap == null) {
290 sIngressDiscardMap = getIngressDiscardMap();
291 }
292 try {
293 sIngressDiscardMap.clear();
294 } catch (ErrnoException e) {
295 throw new IllegalStateException("Failed to initialize ingress discard map", e);
296 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000297 }
298
Ken Chenf5f51332022-01-28 10:08:16 +0800299 /**
300 * Initializes the class if it is not already initialized. This method will open maps but not
301 * cause any other effects. This method may be called multiple times on any thread.
302 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000303 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800304 if (sInitialized) return;
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000305 initBpfMaps();
Ken Chenf5f51332022-01-28 10:08:16 +0800306 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800307 }
308
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000309 /**
310 * Dependencies of BpfNetMaps, for injection in tests.
311 */
312 @VisibleForTesting
313 public static class Dependencies {
314 /**
315 * Get interface index.
316 */
317 public int getIfIndex(final String ifName) {
318 return Os.if_nametoindex(ifName);
319 }
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000320
321 /**
Motomu Utsumi77b49992023-10-23 17:06:12 +0900322 * Get interface name
323 */
324 public String getIfName(final int ifIndex) {
325 return Os.if_indextoname(ifIndex);
326 }
327
328 /**
Maciej Żenczykowski7b8f4752023-11-07 17:04:15 -0800329 * Synchronously call in to kernel to synchronize_rcu()
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000330 */
Maciej Żenczykowski7b8f4752023-11-07 17:04:15 -0800331 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000332 public int synchronizeKernelRCU() {
Maciej Żenczykowski7b8f4752023-11-07 17:04:15 -0800333 // See p/m/C's staticlibs/native/bpf_headers/include/bpf/BpfUtils.h
334 // for equivalent C implementation of this function.
335 try {
336 // When closing socket, kernel calls synchronize_rcu()
337 // from pf_key's sock_release().
338 // Constants from //bionic/libc/include/sys/socket.h: AF_KEY=15
339 // and kernel's include/uapi/linux/pfkeyv2.h: PF_KEY_V2=2
340 Os.close(Os.socket(15 /*PF_KEY*/, SOCK_RAW | SOCK_CLOEXEC, 2));
341 } catch (ErrnoException e) {
342 // socket() can only fail due to lack of privs (selinux) or OOM,
343 // close() always succeeds, but may return a pending error,
344 // however on a freshly opened socket that cannot happen.
345 // As such this failing is basically a build configuration error.
346 return -e.errno;
347 }
348 return 0;
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000349 }
Motomu Utsumi166f9662022-09-01 10:35:29 +0900350
351 /**
352 * Build Stats Event for NETWORK_BPF_MAP_INFO atom
353 */
354 public StatsEvent buildStatsEvent(final int cookieTagMapSize, final int uidOwnerMapSize,
355 final int uidPermissionMapSize) {
356 return ConnectivityStatsLog.buildStatsEvent(NETWORK_BPF_MAP_INFO, cookieTagMapSize,
357 uidOwnerMapSize, uidPermissionMapSize);
358 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000359 }
360
markchien49e944c2022-03-01 15:22:20 +0800361 /** Constructor used after T that doesn't need to use netd anymore. */
Junyu Lai626045a2023-08-28 18:49:44 +0800362 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000363 public BpfNetMaps(final Context context) {
364 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800365
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000366 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800367 }
368
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000369 public BpfNetMaps(final Context context, final INetd netd) {
370 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000371 }
372
373 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000374 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000375 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000376 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000377 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800378 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000379 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800380 }
381
Ken Chenf5f51332022-01-28 10:08:16 +0800382 private void maybeThrow(final int err, final String msg) {
383 if (err != 0) {
384 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
385 }
386 }
387
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000388 private void throwIfPreT(final String msg) {
389 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000390 throw new UnsupportedOperationException(msg);
391 }
392 }
393
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000394 private void removeRule(final int uid, final long match, final String caller) {
395 try {
396 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000397 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000398
399 if (oldMatch == null) {
400 throw new ServiceSpecificException(ENOENT,
401 "sUidOwnerMap does not have entry for uid: " + uid);
402 }
403
404 final UidOwnerValue newMatch = new UidOwnerValue(
405 (match == IIF_MATCH) ? 0 : oldMatch.iif,
406 oldMatch.rule & ~match
407 );
408
409 if (newMatch.rule == 0) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000410 sUidOwnerMap.deleteEntry(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000411 } else {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000412 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000413 }
414 }
415 } catch (ErrnoException e) {
416 throw new ServiceSpecificException(e.errno,
417 caller + " failed to remove rule: " + Os.strerror(e.errno));
418 }
419 }
420
Maciej Żenczykowski6c1c6bb2022-09-16 06:55:33 +0000421 private void addRule(final int uid, final long match, final int iif, final String caller) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000422 if (match != IIF_MATCH && iif != 0) {
423 throw new ServiceSpecificException(EINVAL,
424 "Non-interface match must have zero interface index");
425 }
426
427 try {
428 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000429 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi389278e2022-06-28 07:05:05 +0000430
431 final UidOwnerValue newMatch;
432 if (oldMatch != null) {
433 newMatch = new UidOwnerValue(
434 (match == IIF_MATCH) ? iif : oldMatch.iif,
435 oldMatch.rule | match
436 );
437 } else {
438 newMatch = new UidOwnerValue(
439 iif,
440 match
441 );
442 }
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000443 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi389278e2022-06-28 07:05:05 +0000444 }
445 } catch (ErrnoException e) {
446 throw new ServiceSpecificException(e.errno,
447 caller + " failed to add rule: " + Os.strerror(e.errno));
448 }
449 }
450
451 private void addRule(final int uid, final long match, final String caller) {
452 addRule(uid, match, 0 /* iif */, caller);
453 }
454
Ken Chenf5f51332022-01-28 10:08:16 +0800455 /**
456 * Add naughty app bandwidth rule for specific app
457 *
458 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800459 * @throws ServiceSpecificException in case of failure, with an error code indicating the
460 * cause of the failure.
461 */
Junyu Lai626045a2023-08-28 18:49:44 +0800462 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900463 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000464 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000465
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900466 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800467 }
468
Ken Chenf5f51332022-01-28 10:08:16 +0800469 /**
470 * Remove naughty app bandwidth rule for specific app
471 *
472 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800473 * @throws ServiceSpecificException in case of failure, with an error code indicating the
474 * cause of the failure.
475 */
Junyu Lai626045a2023-08-28 18:49:44 +0800476 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900477 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000478 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000479
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900480 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800481 }
482
Ken Chenf5f51332022-01-28 10:08:16 +0800483 /**
484 * Add nice app bandwidth rule for specific app
485 *
486 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800487 * @throws ServiceSpecificException in case of failure, with an error code indicating the
488 * cause of the failure.
489 */
Junyu Lai626045a2023-08-28 18:49:44 +0800490 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900491 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000492 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000493
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900494 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800495 }
496
Ken Chenf5f51332022-01-28 10:08:16 +0800497 /**
498 * Remove nice app bandwidth rule for specific app
499 *
500 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800501 * @throws ServiceSpecificException in case of failure, with an error code indicating the
502 * cause of the failure.
503 */
Junyu Lai626045a2023-08-28 18:49:44 +0800504 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900505 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000506 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000507
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900508 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800509 }
510
Ken Chenf5f51332022-01-28 10:08:16 +0800511 /**
512 * Set target firewall child chain
513 *
514 * @param childChain target chain to enable
515 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000516 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800517 * @throws ServiceSpecificException in case of failure, with an error code indicating the
518 * cause of the failure.
519 */
Junyu Lai626045a2023-08-28 18:49:44 +0800520 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900521 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000522 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000523
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900524 final long match = getMatchByFirewallChain(childChain);
525 try {
526 synchronized (sUidRulesConfigBpfMapLock) {
527 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
528 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
529 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000530 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900531 } catch (ErrnoException e) {
532 throw new ServiceSpecificException(e.errno,
533 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000534 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800535 }
536
537 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000538 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000539 *
540 * @param childChain target chain
541 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
542 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000543 * @throws ServiceSpecificException in case of failure, with an error code indicating the
544 * cause of the failure.
Junyu Lai626045a2023-08-28 18:49:44 +0800545 *
546 * @deprecated Use {@link BpfNetMapsReader#isChainEnabled} instead.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000547 */
Junyu Lai626045a2023-08-28 18:49:44 +0800548 // TODO: Migrate the callers to use {@link BpfNetMapsReader#isChainEnabled} instead.
549 @Deprecated
550 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000551 public boolean isChainEnabled(final int childChain) {
Junyu Lai626045a2023-08-28 18:49:44 +0800552 return BpfNetMapsReader.isChainEnabled(sConfigurationMap, childChain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000553 }
554
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900555 private Set<Integer> asSet(final int[] uids) {
556 final Set<Integer> uidSet = new ArraySet<>();
Motomu Utsumi77b49992023-10-23 17:06:12 +0900557 for (final int uid : uids) {
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900558 uidSet.add(uid);
559 }
560 return uidSet;
561 }
562
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000563 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800564 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000565 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800566 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000567 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800568 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000569 * @throws UnsupportedOperationException if called on pre-T devices.
570 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800571 */
Junyu Lai626045a2023-08-28 18:49:44 +0800572 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000573 public void replaceUidChain(final int chain, final int[] uids) {
574 throwIfPreT("replaceUidChain is not available on pre-T devices");
575
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900576 final long match;
577 try {
578 match = getMatchByFirewallChain(chain);
579 } catch (ServiceSpecificException e) {
580 // Throws IllegalArgumentException to keep the behavior of
581 // ConnectivityManager#replaceFirewallChain API
582 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
583 }
584 final Set<Integer> uidSet = asSet(uids);
585 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
586 try {
587 synchronized (sUidOwnerMap) {
588 sUidOwnerMap.forEach((uid, config) -> {
589 // config could be null if there is a concurrent entry deletion.
590 // http://b/220084230. But sUidOwnerMap update must be done while holding a
591 // lock, so this should not happen.
592 if (config == null) {
593 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
594 } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
595 uidSetToRemoveRule.add((int) uid.val);
596 }
597 });
Motomu Utsumic7c16852022-08-03 06:51:41 +0000598
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900599 for (final int uid : uidSetToRemoveRule) {
600 removeRule(uid, match, "replaceUidChain");
Motomu Utsumic7c16852022-08-03 06:51:41 +0000601 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900602 for (final int uid : uids) {
603 addRule(uid, match, "replaceUidChain");
604 }
Motomu Utsumic7c16852022-08-03 06:51:41 +0000605 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900606 } catch (ErrnoException | ServiceSpecificException e) {
607 Log.e(TAG, "replaceUidChain failed: " + e);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800608 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800609 }
610
Ken Chenf5f51332022-01-28 10:08:16 +0800611 /**
612 * Set firewall rule for uid
613 *
614 * @param childChain target chain
615 * @param uid uid to allow/deny
616 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800617 * @throws ServiceSpecificException in case of failure, with an error code indicating the
618 * cause of the failure.
619 */
Junyu Lai626045a2023-08-28 18:49:44 +0800620 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900621 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000622 throwIfPreT("setUidRule is not available on pre-T devices");
623
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900624 final long match = getMatchByFirewallChain(childChain);
625 final boolean isAllowList = isFirewallAllowList(childChain);
626 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
627 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000628
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900629 if (add) {
630 addRule(uid, match, "setUidRule");
Motomu Utsumi40230be2022-07-05 03:27:35 +0000631 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900632 removeRule(uid, match, "setUidRule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000633 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800634 }
635
636 /**
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900637 * Get firewall rule of specified firewall chain on specified uid.
638 *
639 * @param childChain target chain
640 * @param uid target uid
641 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
642 * @throws UnsupportedOperationException if called on pre-T devices.
643 * @throws ServiceSpecificException in case of failure, with an error code indicating the
644 * cause of the failure.
Junyu Lai626045a2023-08-28 18:49:44 +0800645 *
646 * @deprecated use {@link BpfNetMapsReader#getUidRule} instead.
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900647 */
Junyu Lai626045a2023-08-28 18:49:44 +0800648 // TODO: Migrate the callers to use {@link BpfNetMapsReader#getUidRule} instead.
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900649 public int getUidRule(final int childChain, final int uid) {
Junyu Lai626045a2023-08-28 18:49:44 +0800650 return BpfNetMapsReader.getUidRule(sUidOwnerMap, childChain, uid);
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900651 }
652
Motomu Utsumid44a33a2023-03-28 18:08:12 +0900653 private Set<Integer> getUidsMatchEnabled(final int childChain) throws ErrnoException {
654 final long match = getMatchByFirewallChain(childChain);
655 Set<Integer> uids = new ArraySet<>();
656 synchronized (sUidOwnerMap) {
657 sUidOwnerMap.forEach((uid, val) -> {
658 if (val == null) {
659 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
660 } else {
661 if ((val.rule & match) != 0) {
662 uids.add(uid.val);
663 }
664 }
665 });
666 }
667 return uids;
668 }
669
670 /**
671 * Get uids that has FIREWALL_RULE_ALLOW on allowlist chain.
672 * Allowlist means the firewall denies all by default, uids must be explicitly allowed.
673 *
674 * Note that uids that has FIREWALL_RULE_DENY on allowlist chain can not be computed from the
675 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_ALLOW rule in bpf map
676 * are determined to have FIREWALL_RULE_DENY.
677 *
678 * @param childChain target chain
679 * @return Set of uids
680 */
681 public Set<Integer> getUidsWithAllowRuleOnAllowListChain(final int childChain)
682 throws ErrnoException {
683 if (!isFirewallAllowList(childChain)) {
684 throw new IllegalArgumentException("getUidsWithAllowRuleOnAllowListChain is called with"
685 + " denylist chain:" + childChain);
686 }
687 // Corresponding match is enabled for uids that has FIREWALL_RULE_ALLOW on allowlist chain.
688 return getUidsMatchEnabled(childChain);
689 }
690
691 /**
692 * Get uids that has FIREWALL_RULE_DENY on denylist chain.
693 * Denylist means the firewall allows all by default, uids must be explicitly denyed
694 *
695 * Note that uids that has FIREWALL_RULE_ALLOW on denylist chain can not be computed from the
696 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_DENY rule in bpf map
697 * are determined to have the FIREWALL_RULE_ALLOW.
698 *
699 * @param childChain target chain
700 * @return Set of uids
701 */
702 public Set<Integer> getUidsWithDenyRuleOnDenyListChain(final int childChain)
703 throws ErrnoException {
704 if (isFirewallAllowList(childChain)) {
705 throw new IllegalArgumentException("getUidsWithDenyRuleOnDenyListChain is called with"
706 + " allowlist chain:" + childChain);
707 }
708 // Corresponding match is enabled for uids that has FIREWALL_RULE_DENY on denylist chain.
709 return getUidsMatchEnabled(childChain);
710 }
711
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900712 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800713 * Add ingress interface filtering rules to a list of UIDs
714 *
715 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
716 * allowed interface and loopback to be sent to the list of UIDs.
717 *
718 * Calling this method on one or more UIDs with an existing filtering rule but a different
719 * interface name will result in the filtering rule being updated to allow the new interface
720 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
721 *
722 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800723 * be received.
724 * @param uids an array of UIDs which the filtering rules will be set
725 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800726 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800727 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800728 */
Ken Chenf5f51332022-01-28 10:08:16 +0800729 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000730 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800731 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800732 return;
733 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000734
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900735 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
736 // ifIndex is set to 0.
737 final int ifIndex;
738 if (ifName == null) {
739 ifIndex = 0;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000740 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900741 ifIndex = mDeps.getIfIndex(ifName);
742 if (ifIndex == 0) {
743 throw new ServiceSpecificException(ENODEV,
744 "Failed to get index of interface " + ifName);
745 }
746 }
747 for (final int uid : uids) {
748 try {
749 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
750 } catch (ServiceSpecificException e) {
751 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
752 }
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000753 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800754 }
755
756 /**
757 * Remove ingress interface filtering rules from a list of UIDs
758 *
759 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
760 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
761 *
762 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800763 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800764 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800765 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800766 */
Ken Chenf5f51332022-01-28 10:08:16 +0800767 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000768 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800769 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800770 return;
771 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000772
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900773 for (final int uid : uids) {
774 try {
775 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
776 } catch (ServiceSpecificException e) {
777 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000778 }
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000779 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800780 }
781
Ken Chenf5f51332022-01-28 10:08:16 +0800782 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000783 * Update lockdown rule for uid
784 *
785 * @param uid target uid to add/remove the rule
786 * @param add {@code true} to add the rule, {@code false} to remove the rule.
787 * @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)
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000791 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000792 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000793
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900794 if (add) {
795 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
Motomu Utsumi697b2992022-06-30 02:25:29 +0000796 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900797 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000798 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000799 }
800
801 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800802 * Request netd to change the current active network stats map.
803 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000804 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800805 * @throws ServiceSpecificException in case of failure, with an error code indicating the
806 * cause of the failure.
807 */
Junyu Lai626045a2023-08-28 18:49:44 +0800808 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien49e944c2022-03-01 15:22:20 +0800809 public void swapActiveStatsMap() {
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000810 throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
811
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900812 try {
813 synchronized (sCurrentStatsMapConfigLock) {
814 final long config = sConfigurationMap.getValue(
815 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
816 final long newConfig = (config == STATS_SELECT_MAP_A)
817 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
818 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
819 new U32(newConfig));
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000820 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900821 } catch (ErrnoException e) {
822 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000823 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900824
825 // After changing the config, it's needed to make sure all the current running eBPF
826 // programs are finished and all the CPUs are aware of this config change before the old
827 // map is modified. So special hack is needed here to wait for the kernel to do a
828 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
829 // be available to all cores and the next eBPF programs triggered inside the kernel will
830 // use the new map configuration. So once this function returns it is safe to modify the
831 // old stats map without concerning about race between the kernel and userspace.
832 final int err = mDeps.synchronizeKernelRCU();
833 maybeThrow(err, "synchronizeKernelRCU failed");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800834 }
835
Ken Chenf5f51332022-01-28 10:08:16 +0800836 /**
837 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
838 * specified. Or remove all permissions from the uids.
839 *
840 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
841 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
842 * revoke all permissions for the uids.
843 * @param uids uid of users to grant permission
844 * @throws RemoteException when netd has crashed.
845 */
846 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000847 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800848 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800849 return;
850 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000851
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900852 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
853 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000854 for (final int uid : uids) {
855 try {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900856 sUidPermissionMap.deleteEntry(new S32(uid));
Motomu Utsumi65271202022-07-05 08:21:41 +0000857 } catch (ErrnoException e) {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900858 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
Motomu Utsumi65271202022-07-05 08:21:41 +0000859 }
860 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900861 return;
862 }
863
864 for (final int uid : uids) {
865 try {
866 sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
867 } catch (ErrnoException e) {
868 Log.e(TAG, "Failed to set permission "
869 + permissions + " to uid " + uid + ": " + e);
870 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000871 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800872 }
873
Ken Chen24330172023-10-20 13:02:14 +0800874 /**
875 * Set Data Saver enabled or disabled
876 *
877 * @param enable whether Data Saver is enabled or disabled.
878 * @throws UnsupportedOperationException if called on pre-T devices.
879 * @throws ServiceSpecificException in case of failure, with an error code indicating the
880 * cause of the failure.
881 */
882 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
883 public void setDataSaverEnabled(boolean enable) {
884 throwIfPreT("setDataSaverEnabled is not available on pre-T devices");
885
886 try {
887 final short config = enable ? DATA_SAVER_ENABLED : DATA_SAVER_DISABLED;
888 sDataSaverEnabledMap.updateEntry(DATA_SAVER_ENABLED_KEY, new U8(config));
889 } catch (ErrnoException e) {
890 throw new ServiceSpecificException(e.errno, "Unable to set data saver: "
891 + Os.strerror(e.errno));
892 }
893 }
894
Motomu Utsumi77b49992023-10-23 17:06:12 +0900895 /**
896 * Set ingress discard rule
897 *
898 * @param address target address to set the ingress discard rule
899 * @param iface allowed interface
900 */
901 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
902 public void setIngressDiscardRule(final InetAddress address, final String iface) {
903 throwIfPreT("setIngressDiscardRule is not available on pre-T devices");
904 final int ifIndex = mDeps.getIfIndex(iface);
905 if (ifIndex == 0) {
906 Log.e(TAG, "Failed to get if index, skip setting ingress discard rule for " + address
907 + "(" + iface + ")");
908 return;
909 }
910 try {
911 sIngressDiscardMap.updateEntry(new IngressDiscardKey(address),
912 new IngressDiscardValue(ifIndex, ifIndex));
913 } catch (ErrnoException e) {
914 Log.e(TAG, "Failed to set ingress discard rule for " + address + "("
915 + iface + "), " + e);
916 }
917 }
918
919 /**
920 * Remove ingress discard rule
921 *
922 * @param address target address to remove the ingress discard rule
923 */
924 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
925 public void removeIngressDiscardRule(final InetAddress address) {
926 throwIfPreT("removeIngressDiscardRule is not available on pre-T devices");
927 try {
928 sIngressDiscardMap.deleteEntry(new IngressDiscardKey(address));
929 } catch (ErrnoException e) {
930 Log.e(TAG, "Failed to remove ingress discard rule for " + address + ", " + e);
931 }
932 }
933
Motomu Utsumi166f9662022-09-01 10:35:29 +0900934 /** Register callback for statsd to pull atom. */
Junyu Lai626045a2023-08-28 18:49:44 +0800935 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi166f9662022-09-01 10:35:29 +0900936 public void setPullAtomCallback(final Context context) {
937 throwIfPreT("setPullAtomCallback is not available on pre-T devices");
938
939 final StatsManager statsManager = context.getSystemService(StatsManager.class);
940 statsManager.setPullAtomCallback(NETWORK_BPF_MAP_INFO, null /* metadata */,
941 BackgroundThread.getExecutor(), this::pullBpfMapInfoAtom);
942 }
943
944 private <K extends Struct, V extends Struct> int getMapSize(IBpfMap<K, V> map)
945 throws ErrnoException {
946 // forEach could restart iteration from the beginning if there is a concurrent entry
947 // deletion. netd and skDestroyListener could delete CookieTagMap entry concurrently.
948 // So using Set to count the number of entry in the map.
949 Set<K> keySet = new ArraySet<>();
950 map.forEach((k, v) -> keySet.add(k));
951 return keySet.size();
952 }
953
954 /** Callback for StatsManager#setPullAtomCallback */
955 @VisibleForTesting
956 public int pullBpfMapInfoAtom(final int atomTag, final List<StatsEvent> data) {
957 if (atomTag != NETWORK_BPF_MAP_INFO) {
958 Log.e(TAG, "Unexpected atom tag: " + atomTag);
959 return StatsManager.PULL_SKIP;
960 }
961
962 try {
963 data.add(mDeps.buildStatsEvent(getMapSize(sCookieTagMap), getMapSize(sUidOwnerMap),
964 getMapSize(sUidPermissionMap)));
965 } catch (ErrnoException e) {
966 Log.e(TAG, "Failed to pull NETWORK_BPF_MAP_INFO atom: " + e);
967 return StatsManager.PULL_SKIP;
968 }
969 return StatsManager.PULL_SUCCESS;
970 }
971
Motomu Utsumi310850f2022-09-02 12:48:20 +0900972 private String permissionToString(int permissionMask) {
973 if (permissionMask == PERMISSION_NONE) {
974 return "PERMISSION_NONE";
975 }
976 if (permissionMask == PERMISSION_UNINSTALLED) {
977 // PERMISSION_UNINSTALLED should never appear in the map
978 return "PERMISSION_UNINSTALLED error!";
979 }
980
981 final StringJoiner sj = new StringJoiner(" ");
982 for (Pair<Integer, String> permission: PERMISSION_LIST) {
983 final int permissionFlag = permission.first;
984 final String permissionName = permission.second;
985 if ((permissionMask & permissionFlag) != 0) {
986 sj.add(permissionName);
987 permissionMask &= ~permissionFlag;
988 }
989 }
990 if (permissionMask != 0) {
991 sj.add("PERMISSION_UNKNOWN(" + permissionMask + ")");
992 }
993 return sj.toString();
994 }
995
Motomu Utsumi372c9b42022-09-02 19:02:56 +0900996 private void dumpOwnerMatchConfig(final IndentingPrintWriter pw) {
997 try {
998 final long match = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY).val;
999 pw.println("current ownerMatch configuration: " + match + " " + matchToString(match));
1000 } catch (ErrnoException e) {
1001 pw.println("Failed to read ownerMatch configuration: " + e);
1002 }
1003 }
1004
Motomu Utsumic675d6f2022-09-02 18:15:25 +09001005 private void dumpCurrentStatsMapConfig(final IndentingPrintWriter pw) {
1006 try {
1007 final long config = sConfigurationMap.getValue(CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
1008 final String currentStatsMap =
1009 (config == STATS_SELECT_MAP_A) ? "SELECT_MAP_A" : "SELECT_MAP_B";
1010 pw.println("current statsMap configuration: " + config + " " + currentStatsMap);
1011 } catch (ErrnoException e) {
1012 pw.println("Falied to read current statsMap configuration: " + e);
1013 }
1014 }
1015
Ken Chen24330172023-10-20 13:02:14 +08001016 private void dumpDataSaverConfig(final IndentingPrintWriter pw) {
1017 try {
1018 final short config = sDataSaverEnabledMap.getValue(DATA_SAVER_ENABLED_KEY).val;
1019 // Any non-zero value converted from short to boolean is true by convention.
1020 pw.println("sDataSaverEnabledMap: " + (config != DATA_SAVER_DISABLED));
1021 } catch (ErrnoException e) {
1022 pw.println("Failed to read data saver configuration: " + e);
1023 }
1024 }
Ken Chene6d511f2022-01-25 11:10:42 +08001025 /**
1026 * Dump BPF maps
1027 *
Motomu Utsumi310850f2022-09-02 12:48:20 +09001028 * @param pw print writer
Ken Chene6d511f2022-01-25 11:10:42 +08001029 * @param fd file descriptor to output
Motomu Utsumi310850f2022-09-02 12:48:20 +09001030 * @param verbose verbose dump flag, if true dump the BpfMap contents
Ken Chene6d511f2022-01-25 11:10:42 +08001031 * @throws IOException when file descriptor is invalid.
1032 * @throws ServiceSpecificException when the method is called on an unsupported device.
1033 */
Junyu Lai626045a2023-08-28 18:49:44 +08001034 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi310850f2022-09-02 12:48:20 +09001035 public void dump(final IndentingPrintWriter pw, final FileDescriptor fd, boolean verbose)
Ken Chene6d511f2022-01-25 11:10:42 +08001036 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00001037 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +08001038 throw new ServiceSpecificException(
1039 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
1040 + " devices, use dumpsys netd trafficcontroller instead.");
1041 }
Maciej Żenczykowskid70a3302023-09-06 16:45:25 +00001042
1043 pw.println("TrafficController"); // required by CTS testDumpBpfNetMaps
Motomu Utsumi310850f2022-09-02 12:48:20 +09001044
Motomu Utsumi316d0572022-09-15 13:24:48 +09001045 pw.println();
Motomu Utsumi310850f2022-09-02 12:48:20 +09001046 if (verbose) {
Motomu Utsumief546a92022-10-05 16:42:29 +09001047 pw.println();
1048 pw.println("BPF map content:");
1049 pw.increaseIndent();
1050
Motomu Utsumi372c9b42022-09-02 19:02:56 +09001051 dumpOwnerMatchConfig(pw);
Motomu Utsumic675d6f2022-09-02 18:15:25 +09001052 dumpCurrentStatsMapConfig(pw);
1053 pw.println();
1054
Motomu Utsumief546a92022-10-05 16:42:29 +09001055 // TODO: Remove CookieTagMap content dump
1056 // NetworkStatsService also dumps CookieTagMap and NetworkStatsService is a right place
1057 // to dump CookieTagMap. But the TagSocketTest in CTS depends on this dump so the tests
1058 // need to be updated before remove the dump from BpfNetMaps.
1059 BpfDump.dumpMap(sCookieTagMap, pw, "sCookieTagMap",
1060 (key, value) -> "cookie=" + key.socketCookie
1061 + " tag=0x" + Long.toHexString(value.tag)
1062 + " uid=" + value.uid);
Motomu Utsumi956d86c2022-09-02 17:01:25 +09001063 BpfDump.dumpMap(sUidOwnerMap, pw, "sUidOwnerMap",
1064 (uid, match) -> {
1065 if ((match.rule & IIF_MATCH) != 0) {
1066 // TODO: convert interface index to interface name by IfaceIndexNameMap
1067 return uid.val + " " + matchToString(match.rule) + " " + match.iif;
1068 } else {
1069 return uid.val + " " + matchToString(match.rule);
1070 }
1071 });
Motomu Utsumi310850f2022-09-02 12:48:20 +09001072 BpfDump.dumpMap(sUidPermissionMap, pw, "sUidPermissionMap",
1073 (uid, permission) -> uid.val + " " + permissionToString(permission.val));
Motomu Utsumi77b49992023-10-23 17:06:12 +09001074 BpfDump.dumpMap(sIngressDiscardMap, pw, "sIngressDiscardMap",
1075 (key, value) -> "[" + key.dstAddr + "]: "
1076 + value.iif1 + "(" + mDeps.getIfName(value.iif1) + "), "
1077 + value.iif2 + "(" + mDeps.getIfName(value.iif2) + ")");
Ken Chen24330172023-10-20 13:02:14 +08001078 dumpDataSaverConfig(pw);
Motomu Utsumief546a92022-10-05 16:42:29 +09001079 pw.decreaseIndent();
Motomu Utsumi310850f2022-09-02 12:48:20 +09001080 }
Ken Chene6d511f2022-01-25 11:10:42 +08001081 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001082}