blob: 086d276c00e69bf67051dda25dbbc0d9fea99feb [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 Utsumi18b287d2022-06-19 10:45:30 +0000111 // Lock for sConfigurationMap entry for UID_RULES_CONFIGURATION_KEY.
112 // This entry is not accessed by others.
113 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
114 private static final Object sUidRulesConfigBpfMapLock = new Object();
115
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000116 // Lock for sConfigurationMap entry for CURRENT_STATS_MAP_CONFIGURATION_KEY.
117 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
118 // BpfNetMaps is an only writer of this entry.
119 private static final Object sCurrentStatsMapConfigLock = new Object();
120
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000121 private static final long UID_RULES_DEFAULT_CONFIGURATION = 0;
122 private static final long STATS_SELECT_MAP_A = 0;
123 private static final long STATS_SELECT_MAP_B = 1;
124
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000125 private static IBpfMap<S32, U32> sConfigurationMap = null;
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000126 // BpfMap for UID_OWNER_MAP_PATH. This map is not accessed by others.
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000127 private static IBpfMap<S32, UidOwnerValue> sUidOwnerMap = null;
128 private static IBpfMap<S32, U8> sUidPermissionMap = null;
Motomu Utsumib9548862022-09-06 16:30:05 +0900129 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> sCookieTagMap = null;
Ken Chen24330172023-10-20 13:02:14 +0800130 // TODO: Add BOOL class and replace U8?
131 private static IBpfMap<S32, U8> sDataSaverEnabledMap = null;
Motomu Utsumi77b49992023-10-23 17:06:12 +0900132 private static IBpfMap<IngressDiscardKey, IngressDiscardValue> sIngressDiscardMap = null;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000133
Motomu Utsumi310850f2022-09-02 12:48:20 +0900134 private static final List<Pair<Integer, String>> PERMISSION_LIST = Arrays.asList(
135 Pair.create(PERMISSION_INTERNET, "PERMISSION_INTERNET"),
136 Pair.create(PERMISSION_UPDATE_DEVICE_STATS, "PERMISSION_UPDATE_DEVICE_STATS")
137 );
138
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000139 /**
Motomu Utsumi305975f2022-06-27 09:24:32 +0000140 * Set configurationMap for test.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000141 */
142 @VisibleForTesting
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000143 public static void setConfigurationMapForTest(IBpfMap<S32, U32> configurationMap) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000144 sConfigurationMap = configurationMap;
145 }
146
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000147 /**
148 * Set uidOwnerMap for test.
149 */
150 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000151 public static void setUidOwnerMapForTest(IBpfMap<S32, UidOwnerValue> uidOwnerMap) {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000152 sUidOwnerMap = uidOwnerMap;
153 }
154
Motomu Utsumi65271202022-07-05 08:21:41 +0000155 /**
156 * Set uidPermissionMap for test.
157 */
158 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000159 public static void setUidPermissionMapForTest(IBpfMap<S32, U8> uidPermissionMap) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000160 sUidPermissionMap = uidPermissionMap;
161 }
162
Motomu Utsumib9548862022-09-06 16:30:05 +0900163 /**
164 * Set cookieTagMap for test.
165 */
166 @VisibleForTesting
167 public static void setCookieTagMapForTest(
168 IBpfMap<CookieTagMapKey, CookieTagMapValue> cookieTagMap) {
169 sCookieTagMap = cookieTagMap;
170 }
171
Ken Chen24330172023-10-20 13:02:14 +0800172 /**
173 * Set dataSaverEnabledMap for test.
174 */
175 @VisibleForTesting
176 public static void setDataSaverEnabledMapForTest(IBpfMap<S32, U8> dataSaverEnabledMap) {
177 sDataSaverEnabledMap = dataSaverEnabledMap;
178 }
179
Motomu Utsumi77b49992023-10-23 17:06:12 +0900180 /**
181 * Set ingressDiscardMap for test.
182 */
183 @VisibleForTesting
184 public static void setIngressDiscardMapForTest(
185 IBpfMap<IngressDiscardKey, IngressDiscardValue> ingressDiscardMap) {
186 sIngressDiscardMap = ingressDiscardMap;
187 }
188
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000189 private static IBpfMap<S32, U32> getConfigurationMap() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000190 try {
191 return new BpfMap<>(
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000192 CONFIGURATION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U32.class);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000193 } catch (ErrnoException e) {
194 throw new IllegalStateException("Cannot open netd configuration map", e);
195 }
196 }
197
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000198 private static IBpfMap<S32, UidOwnerValue> getUidOwnerMap() {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000199 try {
200 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000201 UID_OWNER_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, UidOwnerValue.class);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000202 } catch (ErrnoException e) {
203 throw new IllegalStateException("Cannot open uid owner map", e);
204 }
205 }
206
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000207 private static IBpfMap<S32, U8> getUidPermissionMap() {
Motomu Utsumi65271202022-07-05 08:21:41 +0000208 try {
209 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000210 UID_PERMISSION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U8.class);
Motomu Utsumi65271202022-07-05 08:21:41 +0000211 } catch (ErrnoException e) {
212 throw new IllegalStateException("Cannot open uid permission map", e);
213 }
214 }
215
Motomu Utsumib9548862022-09-06 16:30:05 +0900216 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> getCookieTagMap() {
217 try {
218 return new BpfMap<>(COOKIE_TAG_MAP_PATH, BpfMap.BPF_F_RDWR,
219 CookieTagMapKey.class, CookieTagMapValue.class);
220 } catch (ErrnoException e) {
221 throw new IllegalStateException("Cannot open cookie tag map", e);
222 }
223 }
224
Ken Chen24330172023-10-20 13:02:14 +0800225 private static IBpfMap<S32, U8> getDataSaverEnabledMap() {
226 try {
227 return new BpfMap<>(
228 DATA_SAVER_ENABLED_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U8.class);
229 } catch (ErrnoException e) {
230 throw new IllegalStateException("Cannot open data saver enabled map", e);
231 }
232 }
233
Motomu Utsumi77b49992023-10-23 17:06:12 +0900234 private static IBpfMap<IngressDiscardKey, IngressDiscardValue> getIngressDiscardMap() {
235 try {
236 return new BpfMap<>(INGRESS_DISCARD_MAP_PATH, BpfMap.BPF_F_RDWR,
237 IngressDiscardKey.class, IngressDiscardValue.class);
238 } catch (ErrnoException e) {
239 throw new IllegalStateException("Cannot open ingress discard map", e);
240 }
241 }
242
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000243 private static void initBpfMaps() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000244 if (sConfigurationMap == null) {
245 sConfigurationMap = getConfigurationMap();
246 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000247 try {
248 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY,
249 new U32(UID_RULES_DEFAULT_CONFIGURATION));
250 } catch (ErrnoException e) {
251 throw new IllegalStateException("Failed to initialize uid rules configuration", e);
252 }
253 try {
254 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
255 new U32(STATS_SELECT_MAP_A));
256 } catch (ErrnoException e) {
257 throw new IllegalStateException("Failed to initialize current stats configuration", e);
258 }
259
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000260 if (sUidOwnerMap == null) {
261 sUidOwnerMap = getUidOwnerMap();
262 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000263 try {
264 sUidOwnerMap.clear();
265 } catch (ErrnoException e) {
266 throw new IllegalStateException("Failed to initialize uid owner map", e);
267 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000268
269 if (sUidPermissionMap == null) {
270 sUidPermissionMap = getUidPermissionMap();
271 }
Motomu Utsumib9548862022-09-06 16:30:05 +0900272
273 if (sCookieTagMap == null) {
274 sCookieTagMap = getCookieTagMap();
275 }
Ken Chen24330172023-10-20 13:02:14 +0800276
277 if (sDataSaverEnabledMap == null) {
278 sDataSaverEnabledMap = getDataSaverEnabledMap();
279 }
280 try {
281 sDataSaverEnabledMap.updateEntry(DATA_SAVER_ENABLED_KEY, new U8(DATA_SAVER_DISABLED));
282 } catch (ErrnoException e) {
283 throw new IllegalStateException("Failed to initialize data saver configuration", e);
284 }
Motomu Utsumi77b49992023-10-23 17:06:12 +0900285
286 if (sIngressDiscardMap == null) {
287 sIngressDiscardMap = getIngressDiscardMap();
288 }
289 try {
290 sIngressDiscardMap.clear();
291 } catch (ErrnoException e) {
292 throw new IllegalStateException("Failed to initialize ingress discard map", e);
293 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000294 }
295
Ken Chenf5f51332022-01-28 10:08:16 +0800296 /**
297 * Initializes the class if it is not already initialized. This method will open maps but not
298 * cause any other effects. This method may be called multiple times on any thread.
299 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000300 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800301 if (sInitialized) return;
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000302 initBpfMaps();
Ken Chenf5f51332022-01-28 10:08:16 +0800303 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800304 }
305
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000306 /**
307 * Dependencies of BpfNetMaps, for injection in tests.
308 */
309 @VisibleForTesting
310 public static class Dependencies {
311 /**
312 * Get interface index.
313 */
314 public int getIfIndex(final String ifName) {
315 return Os.if_nametoindex(ifName);
316 }
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000317
318 /**
Motomu Utsumi77b49992023-10-23 17:06:12 +0900319 * Get interface name
320 */
321 public String getIfName(final int ifIndex) {
322 return Os.if_indextoname(ifIndex);
323 }
324
325 /**
Maciej Żenczykowski7b8f4752023-11-07 17:04:15 -0800326 * Synchronously call in to kernel to synchronize_rcu()
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000327 */
Maciej Żenczykowski7b8f4752023-11-07 17:04:15 -0800328 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000329 public int synchronizeKernelRCU() {
Maciej Żenczykowski7b8f4752023-11-07 17:04:15 -0800330 // See p/m/C's staticlibs/native/bpf_headers/include/bpf/BpfUtils.h
331 // for equivalent C implementation of this function.
332 try {
333 // When closing socket, kernel calls synchronize_rcu()
334 // from pf_key's sock_release().
335 // Constants from //bionic/libc/include/sys/socket.h: AF_KEY=15
336 // and kernel's include/uapi/linux/pfkeyv2.h: PF_KEY_V2=2
337 Os.close(Os.socket(15 /*PF_KEY*/, SOCK_RAW | SOCK_CLOEXEC, 2));
338 } catch (ErrnoException e) {
339 // socket() can only fail due to lack of privs (selinux) or OOM,
340 // close() always succeeds, but may return a pending error,
341 // however on a freshly opened socket that cannot happen.
342 // As such this failing is basically a build configuration error.
343 return -e.errno;
344 }
345 return 0;
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000346 }
Motomu Utsumi166f9662022-09-01 10:35:29 +0900347
348 /**
349 * Build Stats Event for NETWORK_BPF_MAP_INFO atom
350 */
351 public StatsEvent buildStatsEvent(final int cookieTagMapSize, final int uidOwnerMapSize,
352 final int uidPermissionMapSize) {
353 return ConnectivityStatsLog.buildStatsEvent(NETWORK_BPF_MAP_INFO, cookieTagMapSize,
354 uidOwnerMapSize, uidPermissionMapSize);
355 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000356 }
357
markchien49e944c2022-03-01 15:22:20 +0800358 /** Constructor used after T that doesn't need to use netd anymore. */
Junyu Lai626045a2023-08-28 18:49:44 +0800359 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000360 public BpfNetMaps(final Context context) {
361 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800362
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000363 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800364 }
365
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000366 public BpfNetMaps(final Context context, final INetd netd) {
367 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000368 }
369
370 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000371 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000372 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000373 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000374 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800375 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000376 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800377 }
378
Ken Chenf5f51332022-01-28 10:08:16 +0800379 private void maybeThrow(final int err, final String msg) {
380 if (err != 0) {
381 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
382 }
383 }
384
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000385 private void throwIfPreT(final String msg) {
386 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000387 throw new UnsupportedOperationException(msg);
388 }
389 }
390
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000391 private void removeRule(final int uid, final long match, final String caller) {
392 try {
393 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000394 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000395
396 if (oldMatch == null) {
397 throw new ServiceSpecificException(ENOENT,
398 "sUidOwnerMap does not have entry for uid: " + uid);
399 }
400
401 final UidOwnerValue newMatch = new UidOwnerValue(
402 (match == IIF_MATCH) ? 0 : oldMatch.iif,
403 oldMatch.rule & ~match
404 );
405
406 if (newMatch.rule == 0) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000407 sUidOwnerMap.deleteEntry(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000408 } else {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000409 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000410 }
411 }
412 } catch (ErrnoException e) {
413 throw new ServiceSpecificException(e.errno,
414 caller + " failed to remove rule: " + Os.strerror(e.errno));
415 }
416 }
417
Maciej Żenczykowski6c1c6bb2022-09-16 06:55:33 +0000418 private void addRule(final int uid, final long match, final int iif, final String caller) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000419 if (match != IIF_MATCH && iif != 0) {
420 throw new ServiceSpecificException(EINVAL,
421 "Non-interface match must have zero interface index");
422 }
423
424 try {
425 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000426 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi389278e2022-06-28 07:05:05 +0000427
428 final UidOwnerValue newMatch;
429 if (oldMatch != null) {
430 newMatch = new UidOwnerValue(
431 (match == IIF_MATCH) ? iif : oldMatch.iif,
432 oldMatch.rule | match
433 );
434 } else {
435 newMatch = new UidOwnerValue(
436 iif,
437 match
438 );
439 }
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000440 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi389278e2022-06-28 07:05:05 +0000441 }
442 } catch (ErrnoException e) {
443 throw new ServiceSpecificException(e.errno,
444 caller + " failed to add rule: " + Os.strerror(e.errno));
445 }
446 }
447
448 private void addRule(final int uid, final long match, final String caller) {
449 addRule(uid, match, 0 /* iif */, caller);
450 }
451
Ken Chenf5f51332022-01-28 10:08:16 +0800452 /**
453 * Add naughty app bandwidth rule for specific app
454 *
455 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800456 * @throws ServiceSpecificException in case of failure, with an error code indicating the
457 * cause of the failure.
458 */
Junyu Lai626045a2023-08-28 18:49:44 +0800459 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900460 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000461 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000462
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900463 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800464 }
465
Ken Chenf5f51332022-01-28 10:08:16 +0800466 /**
467 * Remove naughty app bandwidth rule for specific app
468 *
469 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800470 * @throws ServiceSpecificException in case of failure, with an error code indicating the
471 * cause of the failure.
472 */
Junyu Lai626045a2023-08-28 18:49:44 +0800473 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900474 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000475 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000476
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900477 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800478 }
479
Ken Chenf5f51332022-01-28 10:08:16 +0800480 /**
481 * Add nice app bandwidth rule for specific app
482 *
483 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800484 * @throws ServiceSpecificException in case of failure, with an error code indicating the
485 * cause of the failure.
486 */
Junyu Lai626045a2023-08-28 18:49:44 +0800487 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900488 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000489 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000490
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900491 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800492 }
493
Ken Chenf5f51332022-01-28 10:08:16 +0800494 /**
495 * Remove nice app bandwidth rule for specific app
496 *
497 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800498 * @throws ServiceSpecificException in case of failure, with an error code indicating the
499 * cause of the failure.
500 */
Junyu Lai626045a2023-08-28 18:49:44 +0800501 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900502 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000503 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000504
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900505 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800506 }
507
Ken Chenf5f51332022-01-28 10:08:16 +0800508 /**
509 * Set target firewall child chain
510 *
511 * @param childChain target chain to enable
512 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000513 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800514 * @throws ServiceSpecificException in case of failure, with an error code indicating the
515 * cause of the failure.
516 */
Junyu Lai626045a2023-08-28 18:49:44 +0800517 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900518 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000519 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000520
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900521 final long match = getMatchByFirewallChain(childChain);
522 try {
523 synchronized (sUidRulesConfigBpfMapLock) {
524 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
525 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
526 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000527 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900528 } catch (ErrnoException e) {
529 throw new ServiceSpecificException(e.errno,
530 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000531 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800532 }
533
534 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000535 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000536 *
537 * @param childChain target chain
538 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
539 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000540 * @throws ServiceSpecificException in case of failure, with an error code indicating the
541 * cause of the failure.
Junyu Lai626045a2023-08-28 18:49:44 +0800542 *
543 * @deprecated Use {@link BpfNetMapsReader#isChainEnabled} instead.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000544 */
Junyu Lai626045a2023-08-28 18:49:44 +0800545 // TODO: Migrate the callers to use {@link BpfNetMapsReader#isChainEnabled} instead.
546 @Deprecated
547 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000548 public boolean isChainEnabled(final int childChain) {
Junyu Lai626045a2023-08-28 18:49:44 +0800549 return BpfNetMapsReader.isChainEnabled(sConfigurationMap, childChain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000550 }
551
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900552 private Set<Integer> asSet(final int[] uids) {
553 final Set<Integer> uidSet = new ArraySet<>();
Motomu Utsumi77b49992023-10-23 17:06:12 +0900554 for (final int uid : uids) {
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900555 uidSet.add(uid);
556 }
557 return uidSet;
558 }
559
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000560 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800561 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000562 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800563 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000564 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800565 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000566 * @throws UnsupportedOperationException if called on pre-T devices.
567 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800568 */
Junyu Lai626045a2023-08-28 18:49:44 +0800569 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000570 public void replaceUidChain(final int chain, final int[] uids) {
571 throwIfPreT("replaceUidChain is not available on pre-T devices");
572
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900573 final long match;
574 try {
575 match = getMatchByFirewallChain(chain);
576 } catch (ServiceSpecificException e) {
577 // Throws IllegalArgumentException to keep the behavior of
578 // ConnectivityManager#replaceFirewallChain API
579 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
580 }
581 final Set<Integer> uidSet = asSet(uids);
582 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
583 try {
584 synchronized (sUidOwnerMap) {
585 sUidOwnerMap.forEach((uid, config) -> {
586 // config could be null if there is a concurrent entry deletion.
587 // http://b/220084230. But sUidOwnerMap update must be done while holding a
588 // lock, so this should not happen.
589 if (config == null) {
590 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
591 } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
592 uidSetToRemoveRule.add((int) uid.val);
593 }
594 });
Motomu Utsumic7c16852022-08-03 06:51:41 +0000595
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900596 for (final int uid : uidSetToRemoveRule) {
597 removeRule(uid, match, "replaceUidChain");
Motomu Utsumic7c16852022-08-03 06:51:41 +0000598 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900599 for (final int uid : uids) {
600 addRule(uid, match, "replaceUidChain");
601 }
Motomu Utsumic7c16852022-08-03 06:51:41 +0000602 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900603 } catch (ErrnoException | ServiceSpecificException e) {
604 Log.e(TAG, "replaceUidChain failed: " + e);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800605 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800606 }
607
Ken Chenf5f51332022-01-28 10:08:16 +0800608 /**
609 * Set firewall rule for uid
610 *
611 * @param childChain target chain
612 * @param uid uid to allow/deny
613 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800614 * @throws ServiceSpecificException in case of failure, with an error code indicating the
615 * cause of the failure.
616 */
Junyu Lai626045a2023-08-28 18:49:44 +0800617 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900618 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000619 throwIfPreT("setUidRule is not available on pre-T devices");
620
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900621 final long match = getMatchByFirewallChain(childChain);
622 final boolean isAllowList = isFirewallAllowList(childChain);
623 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
624 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000625
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900626 if (add) {
627 addRule(uid, match, "setUidRule");
Motomu Utsumi40230be2022-07-05 03:27:35 +0000628 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900629 removeRule(uid, match, "setUidRule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000630 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800631 }
632
633 /**
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900634 * Get firewall rule of specified firewall chain on specified uid.
635 *
636 * @param childChain target chain
637 * @param uid target uid
638 * @return either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
639 * @throws UnsupportedOperationException if called on pre-T devices.
640 * @throws ServiceSpecificException in case of failure, with an error code indicating the
641 * cause of the failure.
Junyu Lai626045a2023-08-28 18:49:44 +0800642 *
643 * @deprecated use {@link BpfNetMapsReader#getUidRule} instead.
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900644 */
Junyu Lai626045a2023-08-28 18:49:44 +0800645 // TODO: Migrate the callers to use {@link BpfNetMapsReader#getUidRule} instead.
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900646 public int getUidRule(final int childChain, final int uid) {
Junyu Lai626045a2023-08-28 18:49:44 +0800647 return BpfNetMapsReader.getUidRule(sUidOwnerMap, childChain, uid);
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900648 }
649
Motomu Utsumid44a33a2023-03-28 18:08:12 +0900650 private Set<Integer> getUidsMatchEnabled(final int childChain) throws ErrnoException {
651 final long match = getMatchByFirewallChain(childChain);
652 Set<Integer> uids = new ArraySet<>();
653 synchronized (sUidOwnerMap) {
654 sUidOwnerMap.forEach((uid, val) -> {
655 if (val == null) {
656 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
657 } else {
658 if ((val.rule & match) != 0) {
659 uids.add(uid.val);
660 }
661 }
662 });
663 }
664 return uids;
665 }
666
667 /**
668 * Get uids that has FIREWALL_RULE_ALLOW on allowlist chain.
669 * Allowlist means the firewall denies all by default, uids must be explicitly allowed.
670 *
671 * Note that uids that has FIREWALL_RULE_DENY on allowlist chain can not be computed from the
672 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_ALLOW rule in bpf map
673 * are determined to have FIREWALL_RULE_DENY.
674 *
675 * @param childChain target chain
676 * @return Set of uids
677 */
678 public Set<Integer> getUidsWithAllowRuleOnAllowListChain(final int childChain)
679 throws ErrnoException {
680 if (!isFirewallAllowList(childChain)) {
681 throw new IllegalArgumentException("getUidsWithAllowRuleOnAllowListChain is called with"
682 + " denylist chain:" + childChain);
683 }
684 // Corresponding match is enabled for uids that has FIREWALL_RULE_ALLOW on allowlist chain.
685 return getUidsMatchEnabled(childChain);
686 }
687
688 /**
689 * Get uids that has FIREWALL_RULE_DENY on denylist chain.
690 * Denylist means the firewall allows all by default, uids must be explicitly denyed
691 *
692 * Note that uids that has FIREWALL_RULE_ALLOW on denylist chain can not be computed from the
693 * bpf map, since all the uids that does not have explicit FIREWALL_RULE_DENY rule in bpf map
694 * are determined to have the FIREWALL_RULE_ALLOW.
695 *
696 * @param childChain target chain
697 * @return Set of uids
698 */
699 public Set<Integer> getUidsWithDenyRuleOnDenyListChain(final int childChain)
700 throws ErrnoException {
701 if (isFirewallAllowList(childChain)) {
702 throw new IllegalArgumentException("getUidsWithDenyRuleOnDenyListChain is called with"
703 + " allowlist chain:" + childChain);
704 }
705 // Corresponding match is enabled for uids that has FIREWALL_RULE_DENY on denylist chain.
706 return getUidsMatchEnabled(childChain);
707 }
708
Motomu Utsumi56c412a2023-01-19 15:58:39 +0900709 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800710 * Add ingress interface filtering rules to a list of UIDs
711 *
712 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
713 * allowed interface and loopback to be sent to the list of UIDs.
714 *
715 * Calling this method on one or more UIDs with an existing filtering rule but a different
716 * interface name will result in the filtering rule being updated to allow the new interface
717 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
718 *
719 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800720 * be received.
721 * @param uids an array of UIDs which the filtering rules will be set
722 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800723 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800724 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800725 */
Ken Chenf5f51332022-01-28 10:08:16 +0800726 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000727 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800728 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800729 return;
730 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000731
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900732 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
733 // ifIndex is set to 0.
734 final int ifIndex;
735 if (ifName == null) {
736 ifIndex = 0;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000737 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900738 ifIndex = mDeps.getIfIndex(ifName);
739 if (ifIndex == 0) {
740 throw new ServiceSpecificException(ENODEV,
741 "Failed to get index of interface " + ifName);
742 }
743 }
744 for (final int uid : uids) {
745 try {
746 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
747 } catch (ServiceSpecificException e) {
748 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
749 }
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000750 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800751 }
752
753 /**
754 * Remove ingress interface filtering rules from a list of UIDs
755 *
756 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
757 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
758 *
759 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800760 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800761 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800762 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800763 */
Ken Chenf5f51332022-01-28 10:08:16 +0800764 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000765 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800766 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800767 return;
768 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000769
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900770 for (final int uid : uids) {
771 try {
772 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
773 } catch (ServiceSpecificException e) {
774 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000775 }
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000776 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800777 }
778
Ken Chenf5f51332022-01-28 10:08:16 +0800779 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000780 * Update lockdown rule for uid
781 *
782 * @param uid target uid to add/remove the rule
783 * @param add {@code true} to add the rule, {@code false} to remove the rule.
784 * @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)
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000788 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000789 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000790
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900791 if (add) {
792 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
Motomu Utsumi697b2992022-06-30 02:25:29 +0000793 } else {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900794 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000795 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000796 }
797
798 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800799 * Request netd to change the current active network stats map.
800 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000801 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800802 * @throws ServiceSpecificException in case of failure, with an error code indicating the
803 * cause of the failure.
804 */
Junyu Lai626045a2023-08-28 18:49:44 +0800805 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien49e944c2022-03-01 15:22:20 +0800806 public void swapActiveStatsMap() {
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000807 throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
808
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900809 try {
810 synchronized (sCurrentStatsMapConfigLock) {
811 final long config = sConfigurationMap.getValue(
812 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
813 final long newConfig = (config == STATS_SELECT_MAP_A)
814 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
815 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
816 new U32(newConfig));
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000817 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900818 } catch (ErrnoException e) {
819 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000820 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900821
822 // After changing the config, it's needed to make sure all the current running eBPF
823 // programs are finished and all the CPUs are aware of this config change before the old
824 // map is modified. So special hack is needed here to wait for the kernel to do a
825 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
826 // be available to all cores and the next eBPF programs triggered inside the kernel will
827 // use the new map configuration. So once this function returns it is safe to modify the
828 // old stats map without concerning about race between the kernel and userspace.
829 final int err = mDeps.synchronizeKernelRCU();
830 maybeThrow(err, "synchronizeKernelRCU failed");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800831 }
832
Ken Chenf5f51332022-01-28 10:08:16 +0800833 /**
834 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
835 * specified. Or remove all permissions from the uids.
836 *
837 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
838 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
839 * revoke all permissions for the uids.
840 * @param uids uid of users to grant permission
841 * @throws RemoteException when netd has crashed.
842 */
843 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000844 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800845 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800846 return;
847 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000848
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900849 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
850 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000851 for (final int uid : uids) {
852 try {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900853 sUidPermissionMap.deleteEntry(new S32(uid));
Motomu Utsumi65271202022-07-05 08:21:41 +0000854 } catch (ErrnoException e) {
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900855 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
Motomu Utsumi65271202022-07-05 08:21:41 +0000856 }
857 }
Motomu Utsumi96b6c392023-11-07 15:45:54 +0900858 return;
859 }
860
861 for (final int uid : uids) {
862 try {
863 sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
864 } catch (ErrnoException e) {
865 Log.e(TAG, "Failed to set permission "
866 + permissions + " to uid " + uid + ": " + e);
867 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000868 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800869 }
870
Ken Chen24330172023-10-20 13:02:14 +0800871 /**
872 * Set Data Saver enabled or disabled
873 *
874 * @param enable whether Data Saver is enabled or disabled.
875 * @throws UnsupportedOperationException if called on pre-T devices.
876 * @throws ServiceSpecificException in case of failure, with an error code indicating the
877 * cause of the failure.
878 */
879 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
880 public void setDataSaverEnabled(boolean enable) {
881 throwIfPreT("setDataSaverEnabled is not available on pre-T devices");
882
883 try {
884 final short config = enable ? DATA_SAVER_ENABLED : DATA_SAVER_DISABLED;
885 sDataSaverEnabledMap.updateEntry(DATA_SAVER_ENABLED_KEY, new U8(config));
886 } catch (ErrnoException e) {
887 throw new ServiceSpecificException(e.errno, "Unable to set data saver: "
888 + Os.strerror(e.errno));
889 }
890 }
891
Motomu Utsumi77b49992023-10-23 17:06:12 +0900892 /**
893 * Set ingress discard rule
894 *
895 * @param address target address to set the ingress discard rule
896 * @param iface allowed interface
897 */
898 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
899 public void setIngressDiscardRule(final InetAddress address, final String iface) {
900 throwIfPreT("setIngressDiscardRule is not available on pre-T devices");
901 final int ifIndex = mDeps.getIfIndex(iface);
902 if (ifIndex == 0) {
903 Log.e(TAG, "Failed to get if index, skip setting ingress discard rule for " + address
904 + "(" + iface + ")");
905 return;
906 }
907 try {
908 sIngressDiscardMap.updateEntry(new IngressDiscardKey(address),
909 new IngressDiscardValue(ifIndex, ifIndex));
910 } catch (ErrnoException e) {
911 Log.e(TAG, "Failed to set ingress discard rule for " + address + "("
912 + iface + "), " + e);
913 }
914 }
915
916 /**
917 * Remove ingress discard rule
918 *
919 * @param address target address to remove the ingress discard rule
920 */
921 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
922 public void removeIngressDiscardRule(final InetAddress address) {
923 throwIfPreT("removeIngressDiscardRule is not available on pre-T devices");
924 try {
925 sIngressDiscardMap.deleteEntry(new IngressDiscardKey(address));
926 } catch (ErrnoException e) {
927 Log.e(TAG, "Failed to remove ingress discard rule for " + address + ", " + e);
928 }
929 }
930
Motomu Utsumi166f9662022-09-01 10:35:29 +0900931 /** Register callback for statsd to pull atom. */
Junyu Lai626045a2023-08-28 18:49:44 +0800932 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi166f9662022-09-01 10:35:29 +0900933 public void setPullAtomCallback(final Context context) {
934 throwIfPreT("setPullAtomCallback is not available on pre-T devices");
935
936 final StatsManager statsManager = context.getSystemService(StatsManager.class);
937 statsManager.setPullAtomCallback(NETWORK_BPF_MAP_INFO, null /* metadata */,
938 BackgroundThread.getExecutor(), this::pullBpfMapInfoAtom);
939 }
940
941 private <K extends Struct, V extends Struct> int getMapSize(IBpfMap<K, V> map)
942 throws ErrnoException {
943 // forEach could restart iteration from the beginning if there is a concurrent entry
944 // deletion. netd and skDestroyListener could delete CookieTagMap entry concurrently.
945 // So using Set to count the number of entry in the map.
946 Set<K> keySet = new ArraySet<>();
947 map.forEach((k, v) -> keySet.add(k));
948 return keySet.size();
949 }
950
951 /** Callback for StatsManager#setPullAtomCallback */
952 @VisibleForTesting
953 public int pullBpfMapInfoAtom(final int atomTag, final List<StatsEvent> data) {
954 if (atomTag != NETWORK_BPF_MAP_INFO) {
955 Log.e(TAG, "Unexpected atom tag: " + atomTag);
956 return StatsManager.PULL_SKIP;
957 }
958
959 try {
960 data.add(mDeps.buildStatsEvent(getMapSize(sCookieTagMap), getMapSize(sUidOwnerMap),
961 getMapSize(sUidPermissionMap)));
962 } catch (ErrnoException e) {
963 Log.e(TAG, "Failed to pull NETWORK_BPF_MAP_INFO atom: " + e);
964 return StatsManager.PULL_SKIP;
965 }
966 return StatsManager.PULL_SUCCESS;
967 }
968
Motomu Utsumi310850f2022-09-02 12:48:20 +0900969 private String permissionToString(int permissionMask) {
970 if (permissionMask == PERMISSION_NONE) {
971 return "PERMISSION_NONE";
972 }
973 if (permissionMask == PERMISSION_UNINSTALLED) {
974 // PERMISSION_UNINSTALLED should never appear in the map
975 return "PERMISSION_UNINSTALLED error!";
976 }
977
978 final StringJoiner sj = new StringJoiner(" ");
979 for (Pair<Integer, String> permission: PERMISSION_LIST) {
980 final int permissionFlag = permission.first;
981 final String permissionName = permission.second;
982 if ((permissionMask & permissionFlag) != 0) {
983 sj.add(permissionName);
984 permissionMask &= ~permissionFlag;
985 }
986 }
987 if (permissionMask != 0) {
988 sj.add("PERMISSION_UNKNOWN(" + permissionMask + ")");
989 }
990 return sj.toString();
991 }
992
Motomu Utsumi372c9b42022-09-02 19:02:56 +0900993 private void dumpOwnerMatchConfig(final IndentingPrintWriter pw) {
994 try {
995 final long match = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY).val;
996 pw.println("current ownerMatch configuration: " + match + " " + matchToString(match));
997 } catch (ErrnoException e) {
998 pw.println("Failed to read ownerMatch configuration: " + e);
999 }
1000 }
1001
Motomu Utsumic675d6f2022-09-02 18:15:25 +09001002 private void dumpCurrentStatsMapConfig(final IndentingPrintWriter pw) {
1003 try {
1004 final long config = sConfigurationMap.getValue(CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
1005 final String currentStatsMap =
1006 (config == STATS_SELECT_MAP_A) ? "SELECT_MAP_A" : "SELECT_MAP_B";
1007 pw.println("current statsMap configuration: " + config + " " + currentStatsMap);
1008 } catch (ErrnoException e) {
1009 pw.println("Falied to read current statsMap configuration: " + e);
1010 }
1011 }
1012
Ken Chen24330172023-10-20 13:02:14 +08001013 private void dumpDataSaverConfig(final IndentingPrintWriter pw) {
1014 try {
1015 final short config = sDataSaverEnabledMap.getValue(DATA_SAVER_ENABLED_KEY).val;
1016 // Any non-zero value converted from short to boolean is true by convention.
1017 pw.println("sDataSaverEnabledMap: " + (config != DATA_SAVER_DISABLED));
1018 } catch (ErrnoException e) {
1019 pw.println("Failed to read data saver configuration: " + e);
1020 }
1021 }
Ken Chene6d511f2022-01-25 11:10:42 +08001022 /**
1023 * Dump BPF maps
1024 *
Motomu Utsumi310850f2022-09-02 12:48:20 +09001025 * @param pw print writer
Ken Chene6d511f2022-01-25 11:10:42 +08001026 * @param fd file descriptor to output
Motomu Utsumi310850f2022-09-02 12:48:20 +09001027 * @param verbose verbose dump flag, if true dump the BpfMap contents
Ken Chene6d511f2022-01-25 11:10:42 +08001028 * @throws IOException when file descriptor is invalid.
1029 * @throws ServiceSpecificException when the method is called on an unsupported device.
1030 */
Junyu Lai626045a2023-08-28 18:49:44 +08001031 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Motomu Utsumi310850f2022-09-02 12:48:20 +09001032 public void dump(final IndentingPrintWriter pw, final FileDescriptor fd, boolean verbose)
Ken Chene6d511f2022-01-25 11:10:42 +08001033 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +00001034 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +08001035 throw new ServiceSpecificException(
1036 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
1037 + " devices, use dumpsys netd trafficcontroller instead.");
1038 }
Maciej Żenczykowskid70a3302023-09-06 16:45:25 +00001039
1040 pw.println("TrafficController"); // required by CTS testDumpBpfNetMaps
Motomu Utsumi310850f2022-09-02 12:48:20 +09001041
Motomu Utsumi316d0572022-09-15 13:24:48 +09001042 pw.println();
Motomu Utsumi310850f2022-09-02 12:48:20 +09001043 if (verbose) {
Motomu Utsumief546a92022-10-05 16:42:29 +09001044 pw.println();
1045 pw.println("BPF map content:");
1046 pw.increaseIndent();
1047
Motomu Utsumi372c9b42022-09-02 19:02:56 +09001048 dumpOwnerMatchConfig(pw);
Motomu Utsumic675d6f2022-09-02 18:15:25 +09001049 dumpCurrentStatsMapConfig(pw);
1050 pw.println();
1051
Motomu Utsumief546a92022-10-05 16:42:29 +09001052 // TODO: Remove CookieTagMap content dump
1053 // NetworkStatsService also dumps CookieTagMap and NetworkStatsService is a right place
1054 // to dump CookieTagMap. But the TagSocketTest in CTS depends on this dump so the tests
1055 // need to be updated before remove the dump from BpfNetMaps.
1056 BpfDump.dumpMap(sCookieTagMap, pw, "sCookieTagMap",
1057 (key, value) -> "cookie=" + key.socketCookie
1058 + " tag=0x" + Long.toHexString(value.tag)
1059 + " uid=" + value.uid);
Motomu Utsumi956d86c2022-09-02 17:01:25 +09001060 BpfDump.dumpMap(sUidOwnerMap, pw, "sUidOwnerMap",
1061 (uid, match) -> {
1062 if ((match.rule & IIF_MATCH) != 0) {
1063 // TODO: convert interface index to interface name by IfaceIndexNameMap
1064 return uid.val + " " + matchToString(match.rule) + " " + match.iif;
1065 } else {
1066 return uid.val + " " + matchToString(match.rule);
1067 }
1068 });
Motomu Utsumi310850f2022-09-02 12:48:20 +09001069 BpfDump.dumpMap(sUidPermissionMap, pw, "sUidPermissionMap",
1070 (uid, permission) -> uid.val + " " + permissionToString(permission.val));
Motomu Utsumi77b49992023-10-23 17:06:12 +09001071 BpfDump.dumpMap(sIngressDiscardMap, pw, "sIngressDiscardMap",
1072 (key, value) -> "[" + key.dstAddr + "]: "
1073 + value.iif1 + "(" + mDeps.getIfName(value.iif1) + "), "
1074 + value.iif2 + "(" + mDeps.getIfName(value.iif2) + ")");
Ken Chen24330172023-10-20 13:02:14 +08001075 dumpDataSaverConfig(pw);
Motomu Utsumief546a92022-10-05 16:42:29 +09001076 pw.decreaseIndent();
Motomu Utsumi310850f2022-09-02 12:48:20 +09001077 }
Ken Chene6d511f2022-01-25 11:10:42 +08001078 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +08001079}