blob: 0015da26b1cb856a422b0b649f1ba24eee0d0096 [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
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000019import static android.net.ConnectivityManager.FIREWALL_CHAIN_DOZABLE;
20import static android.net.ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY;
21import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1;
22import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2;
23import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3;
24import static android.net.ConnectivityManager.FIREWALL_CHAIN_POWERSAVE;
25import static android.net.ConnectivityManager.FIREWALL_CHAIN_RESTRICTED;
26import static android.net.ConnectivityManager.FIREWALL_CHAIN_STANDBY;
Motomu Utsumi40230be2022-07-05 03:27:35 +000027import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
28import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Motomu Utsumi65271202022-07-05 08:21:41 +000029import static android.net.INetd.PERMISSION_INTERNET;
Motomu Utsumi310850f2022-09-02 12:48:20 +090030import static android.net.INetd.PERMISSION_NONE;
Motomu Utsumi65271202022-07-05 08:21:41 +000031import static android.net.INetd.PERMISSION_UNINSTALLED;
Motomu Utsumi310850f2022-09-02 12:48:20 +090032import static android.net.INetd.PERMISSION_UPDATE_DEVICE_STATS;
Motomu Utsumi18b287d2022-06-19 10:45:30 +000033import static android.system.OsConstants.EINVAL;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000034import static android.system.OsConstants.ENODEV;
Motomu Utsumi60ed3be2022-06-24 10:38:57 +000035import static android.system.OsConstants.ENOENT;
Ken Chene6d511f2022-01-25 11:10:42 +080036import static android.system.OsConstants.EOPNOTSUPP;
37
Motomu Utsumi166f9662022-09-01 10:35:29 +090038import static com.android.server.ConnectivityStatsLog.NETWORK_BPF_MAP_INFO;
39
40import android.app.StatsManager;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000041import android.content.Context;
Wayne Ma2fde98c2022-01-17 18:04:05 +080042import android.net.INetd;
43import android.os.RemoteException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080044import android.os.ServiceSpecificException;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000045import android.provider.DeviceConfig;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000046import android.system.ErrnoException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080047import android.system.Os;
Motomu Utsumi1a477b02022-08-23 15:14:56 +090048import android.util.ArraySet;
Motomu Utsumi310850f2022-09-02 12:48:20 +090049import android.util.IndentingPrintWriter;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080050import android.util.Log;
Motomu Utsumi310850f2022-09-02 12:48:20 +090051import android.util.Pair;
Motomu Utsumi166f9662022-09-01 10:35:29 +090052import android.util.StatsEvent;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080053
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000054import com.android.internal.annotations.VisibleForTesting;
Motomu Utsumi166f9662022-09-01 10:35:29 +090055import com.android.modules.utils.BackgroundThread;
Ken Chenf5f51332022-01-28 10:08:16 +080056import com.android.modules.utils.build.SdkLevel;
Motomu Utsumi310850f2022-09-02 12:48:20 +090057import com.android.net.module.util.BpfDump;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000058import com.android.net.module.util.BpfMap;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000059import com.android.net.module.util.DeviceConfigUtils;
Motomu Utsumi73599a52022-08-24 11:59:21 +090060import com.android.net.module.util.IBpfMap;
Motomu Utsumi166f9662022-09-01 10:35:29 +090061import com.android.net.module.util.Struct;
Maciej Żenczykowski785793f2022-09-17 02:35:20 +000062import com.android.net.module.util.Struct.S32;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000063import com.android.net.module.util.Struct.U32;
Motomu Utsumi65271202022-07-05 08:21:41 +000064import com.android.net.module.util.Struct.U8;
Motomu Utsumib9548862022-09-06 16:30:05 +090065import com.android.net.module.util.bpf.CookieTagMapKey;
66import com.android.net.module.util.bpf.CookieTagMapValue;
Ken Chenf5f51332022-01-28 10:08:16 +080067
Ken Chene6d511f2022-01-25 11:10:42 +080068import java.io.FileDescriptor;
69import java.io.IOException;
Motomu Utsumi310850f2022-09-02 12:48:20 +090070import java.util.Arrays;
Motomu Utsumi166f9662022-09-01 10:35:29 +090071import java.util.List;
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000072import java.util.Set;
Motomu Utsumi310850f2022-09-02 12:48:20 +090073import java.util.StringJoiner;
Ken Chene6d511f2022-01-25 11:10:42 +080074
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080075/**
76 * BpfNetMaps is responsible for providing traffic controller relevant functionality.
77 *
78 * {@hide}
79 */
80public class BpfNetMaps {
Motomu Utsumi305975f2022-06-27 09:24:32 +000081 private static final boolean PRE_T = !SdkLevel.isAtLeastT();
82 static {
83 if (!PRE_T) {
84 System.loadLibrary("service-connectivity");
85 }
86 }
87
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080088 private static final String TAG = "BpfNetMaps";
Wayne Ma2fde98c2022-01-17 18:04:05 +080089 private final INetd mNetd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000090 private final Dependencies mDeps;
Ken Chenf5f51332022-01-28 10:08:16 +080091 // Use legacy netd for releases before T.
Ken Chenf5f51332022-01-28 10:08:16 +080092 private static boolean sInitialized = false;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080093
Motomu Utsumif688eeb2022-07-22 03:47:35 +000094 private static Boolean sEnableJavaBpfMap = null;
95 private static final String BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP =
96 "bpf_net_maps_enable_java_bpf_map";
97
Motomu Utsumi18b287d2022-06-19 10:45:30 +000098 // Lock for sConfigurationMap entry for UID_RULES_CONFIGURATION_KEY.
99 // This entry is not accessed by others.
100 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
101 private static final Object sUidRulesConfigBpfMapLock = new Object();
102
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000103 // Lock for sConfigurationMap entry for CURRENT_STATS_MAP_CONFIGURATION_KEY.
104 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
105 // BpfNetMaps is an only writer of this entry.
106 private static final Object sCurrentStatsMapConfigLock = new Object();
107
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000108 private static final String CONFIGURATION_MAP_PATH =
109 "/sys/fs/bpf/netd_shared/map_netd_configuration_map";
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000110 private static final String UID_OWNER_MAP_PATH =
111 "/sys/fs/bpf/netd_shared/map_netd_uid_owner_map";
Motomu Utsumi65271202022-07-05 08:21:41 +0000112 private static final String UID_PERMISSION_MAP_PATH =
113 "/sys/fs/bpf/netd_shared/map_netd_uid_permission_map";
Motomu Utsumib9548862022-09-06 16:30:05 +0900114 private static final String COOKIE_TAG_MAP_PATH =
115 "/sys/fs/bpf/netd_shared/map_netd_cookie_tag_map";
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000116 private static final S32 UID_RULES_CONFIGURATION_KEY = new S32(0);
117 private static final S32 CURRENT_STATS_MAP_CONFIGURATION_KEY = new S32(1);
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000118 private static final long UID_RULES_DEFAULT_CONFIGURATION = 0;
119 private static final long STATS_SELECT_MAP_A = 0;
120 private static final long STATS_SELECT_MAP_B = 1;
121
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000122 private static IBpfMap<S32, U32> sConfigurationMap = null;
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000123 // BpfMap for UID_OWNER_MAP_PATH. This map is not accessed by others.
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000124 private static IBpfMap<S32, UidOwnerValue> sUidOwnerMap = null;
125 private static IBpfMap<S32, U8> sUidPermissionMap = null;
Motomu Utsumib9548862022-09-06 16:30:05 +0900126 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> sCookieTagMap = null;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000127
128 // LINT.IfChange(match_type)
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000129 @VisibleForTesting public static final long NO_MATCH = 0;
130 @VisibleForTesting public static final long HAPPY_BOX_MATCH = (1 << 0);
131 @VisibleForTesting public static final long PENALTY_BOX_MATCH = (1 << 1);
132 @VisibleForTesting public static final long DOZABLE_MATCH = (1 << 2);
133 @VisibleForTesting public static final long STANDBY_MATCH = (1 << 3);
134 @VisibleForTesting public static final long POWERSAVE_MATCH = (1 << 4);
135 @VisibleForTesting public static final long RESTRICTED_MATCH = (1 << 5);
136 @VisibleForTesting public static final long LOW_POWER_STANDBY_MATCH = (1 << 6);
137 @VisibleForTesting public static final long IIF_MATCH = (1 << 7);
138 @VisibleForTesting public static final long LOCKDOWN_VPN_MATCH = (1 << 8);
139 @VisibleForTesting public static final long OEM_DENY_1_MATCH = (1 << 9);
140 @VisibleForTesting public static final long OEM_DENY_2_MATCH = (1 << 10);
141 @VisibleForTesting public static final long OEM_DENY_3_MATCH = (1 << 11);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000142 // LINT.ThenChange(packages/modules/Connectivity/bpf_progs/bpf_shared.h)
143
Motomu Utsumi310850f2022-09-02 12:48:20 +0900144 private static final List<Pair<Integer, String>> PERMISSION_LIST = Arrays.asList(
145 Pair.create(PERMISSION_INTERNET, "PERMISSION_INTERNET"),
146 Pair.create(PERMISSION_UPDATE_DEVICE_STATS, "PERMISSION_UPDATE_DEVICE_STATS")
147 );
148
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000149 /**
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000150 * Set sEnableJavaBpfMap for test.
151 */
152 @VisibleForTesting
153 public static void setEnableJavaBpfMapForTest(boolean enable) {
154 sEnableJavaBpfMap = enable;
155 }
156
157 /**
Motomu Utsumi305975f2022-06-27 09:24:32 +0000158 * Set configurationMap for test.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000159 */
160 @VisibleForTesting
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000161 public static void setConfigurationMapForTest(IBpfMap<S32, U32> configurationMap) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000162 sConfigurationMap = configurationMap;
163 }
164
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000165 /**
166 * Set uidOwnerMap for test.
167 */
168 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000169 public static void setUidOwnerMapForTest(IBpfMap<S32, UidOwnerValue> uidOwnerMap) {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000170 sUidOwnerMap = uidOwnerMap;
171 }
172
Motomu Utsumi65271202022-07-05 08:21:41 +0000173 /**
174 * Set uidPermissionMap for test.
175 */
176 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000177 public static void setUidPermissionMapForTest(IBpfMap<S32, U8> uidPermissionMap) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000178 sUidPermissionMap = uidPermissionMap;
179 }
180
Motomu Utsumib9548862022-09-06 16:30:05 +0900181 /**
182 * Set cookieTagMap for test.
183 */
184 @VisibleForTesting
185 public static void setCookieTagMapForTest(
186 IBpfMap<CookieTagMapKey, CookieTagMapValue> cookieTagMap) {
187 sCookieTagMap = cookieTagMap;
188 }
189
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000190 private static IBpfMap<S32, U32> getConfigurationMap() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000191 try {
192 return new BpfMap<>(
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000193 CONFIGURATION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U32.class);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000194 } catch (ErrnoException e) {
195 throw new IllegalStateException("Cannot open netd configuration map", e);
196 }
197 }
198
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000199 private static IBpfMap<S32, UidOwnerValue> getUidOwnerMap() {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000200 try {
201 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000202 UID_OWNER_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, UidOwnerValue.class);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000203 } catch (ErrnoException e) {
204 throw new IllegalStateException("Cannot open uid owner map", e);
205 }
206 }
207
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000208 private static IBpfMap<S32, U8> getUidPermissionMap() {
Motomu Utsumi65271202022-07-05 08:21:41 +0000209 try {
210 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000211 UID_PERMISSION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U8.class);
Motomu Utsumi65271202022-07-05 08:21:41 +0000212 } catch (ErrnoException e) {
213 throw new IllegalStateException("Cannot open uid permission map", e);
214 }
215 }
216
Motomu Utsumib9548862022-09-06 16:30:05 +0900217 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> getCookieTagMap() {
218 try {
219 return new BpfMap<>(COOKIE_TAG_MAP_PATH, BpfMap.BPF_F_RDWR,
220 CookieTagMapKey.class, CookieTagMapValue.class);
221 } catch (ErrnoException e) {
222 throw new IllegalStateException("Cannot open cookie tag map", e);
223 }
224 }
225
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000226 private static void initBpfMaps() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000227 if (sConfigurationMap == null) {
228 sConfigurationMap = getConfigurationMap();
229 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000230 try {
231 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY,
232 new U32(UID_RULES_DEFAULT_CONFIGURATION));
233 } catch (ErrnoException e) {
234 throw new IllegalStateException("Failed to initialize uid rules configuration", e);
235 }
236 try {
237 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
238 new U32(STATS_SELECT_MAP_A));
239 } catch (ErrnoException e) {
240 throw new IllegalStateException("Failed to initialize current stats configuration", e);
241 }
242
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000243 if (sUidOwnerMap == null) {
244 sUidOwnerMap = getUidOwnerMap();
245 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000246 try {
247 sUidOwnerMap.clear();
248 } catch (ErrnoException e) {
249 throw new IllegalStateException("Failed to initialize uid owner map", e);
250 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000251
252 if (sUidPermissionMap == null) {
253 sUidPermissionMap = getUidPermissionMap();
254 }
Motomu Utsumib9548862022-09-06 16:30:05 +0900255
256 if (sCookieTagMap == null) {
257 sCookieTagMap = getCookieTagMap();
258 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000259 }
260
Ken Chenf5f51332022-01-28 10:08:16 +0800261 /**
262 * Initializes the class if it is not already initialized. This method will open maps but not
263 * cause any other effects. This method may be called multiple times on any thread.
264 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000265 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800266 if (sInitialized) return;
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000267 if (sEnableJavaBpfMap == null) {
268 sEnableJavaBpfMap = DeviceConfigUtils.isFeatureEnabled(context,
269 DeviceConfig.NAMESPACE_TETHERING, BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP,
270 SdkLevel.isAtLeastU() /* defaultValue */);
271 }
272 Log.d(TAG, "BpfNetMaps is initialized with sEnableJavaBpfMap=" + sEnableJavaBpfMap);
273
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000274 initBpfMaps();
Motomu Utsumid95a0da2022-09-03 00:40:30 +0900275 native_init(!sEnableJavaBpfMap /* startSkDestroyListener */);
Ken Chenf5f51332022-01-28 10:08:16 +0800276 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800277 }
278
Motomu Utsumid95a0da2022-09-03 00:40:30 +0900279 public boolean isSkDestroyListenerRunning() {
280 return !sEnableJavaBpfMap;
281 }
282
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000283 /**
284 * Dependencies of BpfNetMaps, for injection in tests.
285 */
286 @VisibleForTesting
287 public static class Dependencies {
288 /**
289 * Get interface index.
290 */
291 public int getIfIndex(final String ifName) {
292 return Os.if_nametoindex(ifName);
293 }
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000294
295 /**
296 * Call synchronize_rcu()
297 */
298 public int synchronizeKernelRCU() {
299 return native_synchronizeKernelRCU();
300 }
Motomu Utsumi166f9662022-09-01 10:35:29 +0900301
302 /**
303 * Build Stats Event for NETWORK_BPF_MAP_INFO atom
304 */
305 public StatsEvent buildStatsEvent(final int cookieTagMapSize, final int uidOwnerMapSize,
306 final int uidPermissionMapSize) {
307 return ConnectivityStatsLog.buildStatsEvent(NETWORK_BPF_MAP_INFO, cookieTagMapSize,
308 uidOwnerMapSize, uidPermissionMapSize);
309 }
Motomu Utsumidf8d2992022-09-01 17:08:27 +0900310
311 /**
312 * Call native_dump
313 */
314 public void nativeDump(final FileDescriptor fd, final boolean verbose) {
315 native_dump(fd, verbose);
316 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000317 }
318
markchien49e944c2022-03-01 15:22:20 +0800319 /** Constructor used after T that doesn't need to use netd anymore. */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000320 public BpfNetMaps(final Context context) {
321 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800322
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000323 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800324 }
325
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000326 public BpfNetMaps(final Context context, final INetd netd) {
327 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000328 }
329
330 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000331 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000332 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000333 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000334 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800335 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000336 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800337 }
338
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000339 /**
340 * Get corresponding match from firewall chain.
341 */
342 @VisibleForTesting
343 public long getMatchByFirewallChain(final int chain) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000344 switch (chain) {
345 case FIREWALL_CHAIN_DOZABLE:
346 return DOZABLE_MATCH;
347 case FIREWALL_CHAIN_STANDBY:
348 return STANDBY_MATCH;
349 case FIREWALL_CHAIN_POWERSAVE:
350 return POWERSAVE_MATCH;
351 case FIREWALL_CHAIN_RESTRICTED:
352 return RESTRICTED_MATCH;
353 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
354 return LOW_POWER_STANDBY_MATCH;
355 case FIREWALL_CHAIN_OEM_DENY_1:
356 return OEM_DENY_1_MATCH;
357 case FIREWALL_CHAIN_OEM_DENY_2:
358 return OEM_DENY_2_MATCH;
359 case FIREWALL_CHAIN_OEM_DENY_3:
360 return OEM_DENY_3_MATCH;
361 default:
362 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000363 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000364 }
365
366 /**
367 * Get if the chain is allow list or not.
368 *
369 * ALLOWLIST means the firewall denies all by default, uids must be explicitly allowed
370 * DENYLIST means the firewall allows all by default, uids must be explicitly denyed
371 */
372 @VisibleForTesting
373 public boolean isFirewallAllowList(final int chain) {
374 switch (chain) {
375 case FIREWALL_CHAIN_DOZABLE:
376 case FIREWALL_CHAIN_POWERSAVE:
377 case FIREWALL_CHAIN_RESTRICTED:
378 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
379 return true;
380 case FIREWALL_CHAIN_STANDBY:
381 case FIREWALL_CHAIN_OEM_DENY_1:
382 case FIREWALL_CHAIN_OEM_DENY_2:
383 case FIREWALL_CHAIN_OEM_DENY_3:
384 return false;
385 default:
386 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
387 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000388 }
389
Ken Chenf5f51332022-01-28 10:08:16 +0800390 private void maybeThrow(final int err, final String msg) {
391 if (err != 0) {
392 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
393 }
394 }
395
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000396 private void throwIfPreT(final String msg) {
397 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000398 throw new UnsupportedOperationException(msg);
399 }
400 }
401
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000402 private void removeRule(final int uid, final long match, final String caller) {
403 try {
404 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000405 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000406
407 if (oldMatch == null) {
408 throw new ServiceSpecificException(ENOENT,
409 "sUidOwnerMap does not have entry for uid: " + uid);
410 }
411
412 final UidOwnerValue newMatch = new UidOwnerValue(
413 (match == IIF_MATCH) ? 0 : oldMatch.iif,
414 oldMatch.rule & ~match
415 );
416
417 if (newMatch.rule == 0) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000418 sUidOwnerMap.deleteEntry(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000419 } else {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000420 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000421 }
422 }
423 } catch (ErrnoException e) {
424 throw new ServiceSpecificException(e.errno,
425 caller + " failed to remove rule: " + Os.strerror(e.errno));
426 }
427 }
428
Maciej Żenczykowski6c1c6bb2022-09-16 06:55:33 +0000429 private void addRule(final int uid, final long match, final int iif, final String caller) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000430 if (match != IIF_MATCH && iif != 0) {
431 throw new ServiceSpecificException(EINVAL,
432 "Non-interface match must have zero interface index");
433 }
434
435 try {
436 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000437 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi389278e2022-06-28 07:05:05 +0000438
439 final UidOwnerValue newMatch;
440 if (oldMatch != null) {
441 newMatch = new UidOwnerValue(
442 (match == IIF_MATCH) ? iif : oldMatch.iif,
443 oldMatch.rule | match
444 );
445 } else {
446 newMatch = new UidOwnerValue(
447 iif,
448 match
449 );
450 }
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000451 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi389278e2022-06-28 07:05:05 +0000452 }
453 } catch (ErrnoException e) {
454 throw new ServiceSpecificException(e.errno,
455 caller + " failed to add rule: " + Os.strerror(e.errno));
456 }
457 }
458
459 private void addRule(final int uid, final long match, final String caller) {
460 addRule(uid, match, 0 /* iif */, caller);
461 }
462
Ken Chenf5f51332022-01-28 10:08:16 +0800463 /**
464 * Add naughty app bandwidth rule for specific app
465 *
466 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800467 * @throws ServiceSpecificException in case of failure, with an error code indicating the
468 * cause of the failure.
469 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900470 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000471 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000472
473 if (sEnableJavaBpfMap) {
474 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
475 } else {
476 final int err = native_addNaughtyApp(uid);
477 maybeThrow(err, "Unable to add naughty app");
478 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800479 }
480
Ken Chenf5f51332022-01-28 10:08:16 +0800481 /**
482 * Remove naughty app bandwidth rule for specific app
483 *
484 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800485 * @throws ServiceSpecificException in case of failure, with an error code indicating the
486 * cause of the failure.
487 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900488 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000489 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000490
491 if (sEnableJavaBpfMap) {
492 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
493 } else {
494 final int err = native_removeNaughtyApp(uid);
495 maybeThrow(err, "Unable to remove naughty app");
496 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800497 }
498
Ken Chenf5f51332022-01-28 10:08:16 +0800499 /**
500 * Add nice app bandwidth rule for specific app
501 *
502 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800503 * @throws ServiceSpecificException in case of failure, with an error code indicating the
504 * cause of the failure.
505 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900506 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000507 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000508
509 if (sEnableJavaBpfMap) {
510 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
511 } else {
512 final int err = native_addNiceApp(uid);
513 maybeThrow(err, "Unable to add nice app");
514 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800515 }
516
Ken Chenf5f51332022-01-28 10:08:16 +0800517 /**
518 * Remove nice app bandwidth rule for specific app
519 *
520 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800521 * @throws ServiceSpecificException in case of failure, with an error code indicating the
522 * cause of the failure.
523 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900524 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000525 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000526
527 if (sEnableJavaBpfMap) {
528 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
529 } else {
530 final int err = native_removeNiceApp(uid);
531 maybeThrow(err, "Unable to remove nice app");
532 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800533 }
534
Ken Chenf5f51332022-01-28 10:08:16 +0800535 /**
536 * Set target firewall child chain
537 *
538 * @param childChain target chain to enable
539 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000540 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800541 * @throws ServiceSpecificException in case of failure, with an error code indicating the
542 * cause of the failure.
543 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900544 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000545 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000546
Motomu Utsumie057dd42022-08-03 01:23:49 +0000547 if (sEnableJavaBpfMap) {
548 final long match = getMatchByFirewallChain(childChain);
549 try {
550 synchronized (sUidRulesConfigBpfMapLock) {
551 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
552 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
553 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
554 }
555 } catch (ErrnoException e) {
556 throw new ServiceSpecificException(e.errno,
557 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000558 }
Motomu Utsumie057dd42022-08-03 01:23:49 +0000559 } else {
560 final int err = native_setChildChain(childChain, enable);
561 maybeThrow(err, "Unable to set child chain");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000562 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800563 }
564
565 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000566 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000567 *
568 * @param childChain target chain
569 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
570 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000571 * @throws ServiceSpecificException in case of failure, with an error code indicating the
572 * cause of the failure.
573 */
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000574 public boolean isChainEnabled(final int childChain) {
575 throwIfPreT("isChainEnabled is not available on pre-T devices");
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000576
577 final long match = getMatchByFirewallChain(childChain);
578 try {
579 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000580 return (config.val & match) != 0;
581 } catch (ErrnoException e) {
582 throw new ServiceSpecificException(e.errno,
583 "Unable to get firewall chain status: " + Os.strerror(e.errno));
584 }
585 }
586
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900587 private Set<Integer> asSet(final int[] uids) {
588 final Set<Integer> uidSet = new ArraySet<>();
589 for (final int uid: uids) {
590 uidSet.add(uid);
591 }
592 return uidSet;
593 }
594
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000595 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800596 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000597 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800598 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000599 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800600 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000601 * @throws UnsupportedOperationException if called on pre-T devices.
602 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800603 */
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000604 public void replaceUidChain(final int chain, final int[] uids) {
605 throwIfPreT("replaceUidChain is not available on pre-T devices");
606
Motomu Utsumic7c16852022-08-03 06:51:41 +0000607 if (sEnableJavaBpfMap) {
608 final long match;
609 try {
610 match = getMatchByFirewallChain(chain);
611 } catch (ServiceSpecificException e) {
612 // Throws IllegalArgumentException to keep the behavior of
613 // ConnectivityManager#replaceFirewallChain API
614 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000615 }
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900616 final Set<Integer> uidSet = asSet(uids);
617 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
Motomu Utsumic7c16852022-08-03 06:51:41 +0000618 try {
619 synchronized (sUidOwnerMap) {
620 sUidOwnerMap.forEach((uid, config) -> {
621 // config could be null if there is a concurrent entry deletion.
Motomu Utsumi8e420ea2022-08-24 18:03:30 +0900622 // http://b/220084230. But sUidOwnerMap update must be done while holding a
623 // lock, so this should not happen.
624 if (config == null) {
625 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
626 } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
Motomu Utsumic7c16852022-08-03 06:51:41 +0000627 uidSetToRemoveRule.add((int) uid.val);
628 }
629 });
630
631 for (final int uid : uidSetToRemoveRule) {
632 removeRule(uid, match, "replaceUidChain");
633 }
634 for (final int uid : uids) {
635 addRule(uid, match, "replaceUidChain");
636 }
637 }
638 } catch (ErrnoException | ServiceSpecificException e) {
639 Log.e(TAG, "replaceUidChain failed: " + e);
640 }
641 } else {
642 final int err;
643 switch (chain) {
644 case FIREWALL_CHAIN_DOZABLE:
645 err = native_replaceUidChain("fw_dozable", true /* isAllowList */, uids);
646 break;
647 case FIREWALL_CHAIN_STANDBY:
648 err = native_replaceUidChain("fw_standby", false /* isAllowList */, uids);
649 break;
650 case FIREWALL_CHAIN_POWERSAVE:
651 err = native_replaceUidChain("fw_powersave", true /* isAllowList */, uids);
652 break;
653 case FIREWALL_CHAIN_RESTRICTED:
654 err = native_replaceUidChain("fw_restricted", true /* isAllowList */, uids);
655 break;
656 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
657 err = native_replaceUidChain(
658 "fw_low_power_standby", true /* isAllowList */, uids);
659 break;
660 case FIREWALL_CHAIN_OEM_DENY_1:
661 err = native_replaceUidChain("fw_oem_deny_1", false /* isAllowList */, uids);
662 break;
663 case FIREWALL_CHAIN_OEM_DENY_2:
664 err = native_replaceUidChain("fw_oem_deny_2", false /* isAllowList */, uids);
665 break;
666 case FIREWALL_CHAIN_OEM_DENY_3:
667 err = native_replaceUidChain("fw_oem_deny_3", false /* isAllowList */, uids);
668 break;
669 default:
670 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
671 + chain);
672 }
673 if (err != 0) {
674 Log.e(TAG, "replaceUidChain failed: " + Os.strerror(-err));
675 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800676 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800677 }
678
Ken Chenf5f51332022-01-28 10:08:16 +0800679 /**
680 * Set firewall rule for uid
681 *
682 * @param childChain target chain
683 * @param uid uid to allow/deny
684 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800685 * @throws ServiceSpecificException in case of failure, with an error code indicating the
686 * cause of the failure.
687 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900688 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000689 throwIfPreT("setUidRule is not available on pre-T devices");
690
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000691 if (sEnableJavaBpfMap) {
692 final long match = getMatchByFirewallChain(childChain);
693 final boolean isAllowList = isFirewallAllowList(childChain);
694 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
695 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000696
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000697 if (add) {
698 addRule(uid, match, "setUidRule");
699 } else {
700 removeRule(uid, match, "setUidRule");
701 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000702 } else {
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000703 final int err = native_setUidRule(childChain, uid, firewallRule);
704 maybeThrow(err, "Unable to set uid rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000705 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800706 }
707
708 /**
709 * Add ingress interface filtering rules to a list of UIDs
710 *
711 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
712 * allowed interface and loopback to be sent to the list of UIDs.
713 *
714 * Calling this method on one or more UIDs with an existing filtering rule but a different
715 * interface name will result in the filtering rule being updated to allow the new interface
716 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
717 *
718 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800719 * be received.
720 * @param uids an array of UIDs which the filtering rules will be set
721 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800722 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800723 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800724 */
Ken Chenf5f51332022-01-28 10:08:16 +0800725 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000726 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800727 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800728 return;
729 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000730
731 if (sEnableJavaBpfMap) {
732 // 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;
737 } else {
738 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 }
750 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000751 } else {
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000752 final int err = native_addUidInterfaceRules(ifName, uids);
753 maybeThrow(err, "Unable to add uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000754 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800755 }
756
757 /**
758 * Remove ingress interface filtering rules from a list of UIDs
759 *
760 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
761 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
762 *
763 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800764 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800765 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800766 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800767 */
Ken Chenf5f51332022-01-28 10:08:16 +0800768 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000769 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800770 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800771 return;
772 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000773
774 if (sEnableJavaBpfMap) {
775 for (final int uid : uids) {
776 try {
777 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
778 } catch (ServiceSpecificException e) {
779 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
780 }
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000781 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000782 } else {
783 final int err = native_removeUidInterfaceRules(uids);
784 maybeThrow(err, "Unable to remove uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000785 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800786 }
787
Ken Chenf5f51332022-01-28 10:08:16 +0800788 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000789 * Update lockdown rule for uid
790 *
791 * @param uid target uid to add/remove the rule
792 * @param add {@code true} to add the rule, {@code false} to remove the rule.
793 * @throws ServiceSpecificException in case of failure, with an error code indicating the
794 * cause of the failure.
795 */
796 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000797 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000798
799 if (sEnableJavaBpfMap) {
800 if (add) {
801 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
802 } else {
803 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
804 }
Motomu Utsumi697b2992022-06-30 02:25:29 +0000805 } else {
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000806 final int err = native_updateUidLockdownRule(uid, add);
807 maybeThrow(err, "Unable to update lockdown rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000808 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000809 }
810
811 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800812 * Request netd to change the current active network stats map.
813 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000814 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800815 * @throws ServiceSpecificException in case of failure, with an error code indicating the
816 * cause of the failure.
817 */
markchien49e944c2022-03-01 15:22:20 +0800818 public void swapActiveStatsMap() {
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000819 throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
820
821 if (sEnableJavaBpfMap) {
822 try {
823 synchronized (sCurrentStatsMapConfigLock) {
824 final long config = sConfigurationMap.getValue(
825 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
826 final long newConfig = (config == STATS_SELECT_MAP_A)
827 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
828 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
829 new U32(newConfig));
830 }
831 } catch (ErrnoException e) {
832 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
833 }
834
835 // After changing the config, it's needed to make sure all the current running eBPF
836 // programs are finished and all the CPUs are aware of this config change before the old
837 // map is modified. So special hack is needed here to wait for the kernel to do a
838 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
839 // be available to all cores and the next eBPF programs triggered inside the kernel will
840 // use the new map configuration. So once this function returns it is safe to modify the
841 // old stats map without concerning about race between the kernel and userspace.
842 final int err = mDeps.synchronizeKernelRCU();
843 maybeThrow(err, "synchronizeKernelRCU failed");
844 } else {
845 final int err = native_swapActiveStatsMap();
846 maybeThrow(err, "Unable to swap active stats map");
847 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800848 }
849
Ken Chenf5f51332022-01-28 10:08:16 +0800850 /**
851 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
852 * specified. Or remove all permissions from the uids.
853 *
854 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
855 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
856 * revoke all permissions for the uids.
857 * @param uids uid of users to grant permission
858 * @throws RemoteException when netd has crashed.
859 */
860 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000861 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800862 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800863 return;
864 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000865
866 if (sEnableJavaBpfMap) {
867 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
868 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
869 for (final int uid : uids) {
870 try {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000871 sUidPermissionMap.deleteEntry(new S32(uid));
Motomu Utsumi65271202022-07-05 08:21:41 +0000872 } catch (ErrnoException e) {
873 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
874 }
875 }
876 return;
877 }
878
879 for (final int uid : uids) {
880 try {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000881 sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
Motomu Utsumi65271202022-07-05 08:21:41 +0000882 } catch (ErrnoException e) {
883 Log.e(TAG, "Failed to set permission "
884 + permissions + " to uid " + uid + ": " + e);
885 }
886 }
887 } else {
888 native_setPermissionForUids(permissions, uids);
889 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800890 }
891
Motomu Utsumi166f9662022-09-01 10:35:29 +0900892 /** Register callback for statsd to pull atom. */
893 public void setPullAtomCallback(final Context context) {
894 throwIfPreT("setPullAtomCallback is not available on pre-T devices");
895
896 final StatsManager statsManager = context.getSystemService(StatsManager.class);
897 statsManager.setPullAtomCallback(NETWORK_BPF_MAP_INFO, null /* metadata */,
898 BackgroundThread.getExecutor(), this::pullBpfMapInfoAtom);
899 }
900
901 private <K extends Struct, V extends Struct> int getMapSize(IBpfMap<K, V> map)
902 throws ErrnoException {
903 // forEach could restart iteration from the beginning if there is a concurrent entry
904 // deletion. netd and skDestroyListener could delete CookieTagMap entry concurrently.
905 // So using Set to count the number of entry in the map.
906 Set<K> keySet = new ArraySet<>();
907 map.forEach((k, v) -> keySet.add(k));
908 return keySet.size();
909 }
910
911 /** Callback for StatsManager#setPullAtomCallback */
912 @VisibleForTesting
913 public int pullBpfMapInfoAtom(final int atomTag, final List<StatsEvent> data) {
914 if (atomTag != NETWORK_BPF_MAP_INFO) {
915 Log.e(TAG, "Unexpected atom tag: " + atomTag);
916 return StatsManager.PULL_SKIP;
917 }
918
919 try {
920 data.add(mDeps.buildStatsEvent(getMapSize(sCookieTagMap), getMapSize(sUidOwnerMap),
921 getMapSize(sUidPermissionMap)));
922 } catch (ErrnoException e) {
923 Log.e(TAG, "Failed to pull NETWORK_BPF_MAP_INFO atom: " + e);
924 return StatsManager.PULL_SKIP;
925 }
926 return StatsManager.PULL_SUCCESS;
927 }
928
Motomu Utsumi310850f2022-09-02 12:48:20 +0900929 private String permissionToString(int permissionMask) {
930 if (permissionMask == PERMISSION_NONE) {
931 return "PERMISSION_NONE";
932 }
933 if (permissionMask == PERMISSION_UNINSTALLED) {
934 // PERMISSION_UNINSTALLED should never appear in the map
935 return "PERMISSION_UNINSTALLED error!";
936 }
937
938 final StringJoiner sj = new StringJoiner(" ");
939 for (Pair<Integer, String> permission: PERMISSION_LIST) {
940 final int permissionFlag = permission.first;
941 final String permissionName = permission.second;
942 if ((permissionMask & permissionFlag) != 0) {
943 sj.add(permissionName);
944 permissionMask &= ~permissionFlag;
945 }
946 }
947 if (permissionMask != 0) {
948 sj.add("PERMISSION_UNKNOWN(" + permissionMask + ")");
949 }
950 return sj.toString();
951 }
952
Ken Chene6d511f2022-01-25 11:10:42 +0800953 /**
954 * Dump BPF maps
955 *
Motomu Utsumi310850f2022-09-02 12:48:20 +0900956 * @param pw print writer
Ken Chene6d511f2022-01-25 11:10:42 +0800957 * @param fd file descriptor to output
Motomu Utsumi310850f2022-09-02 12:48:20 +0900958 * @param verbose verbose dump flag, if true dump the BpfMap contents
Ken Chene6d511f2022-01-25 11:10:42 +0800959 * @throws IOException when file descriptor is invalid.
960 * @throws ServiceSpecificException when the method is called on an unsupported device.
961 */
Motomu Utsumi310850f2022-09-02 12:48:20 +0900962 public void dump(final IndentingPrintWriter pw, final FileDescriptor fd, boolean verbose)
Ken Chene6d511f2022-01-25 11:10:42 +0800963 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000964 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +0800965 throw new ServiceSpecificException(
966 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
967 + " devices, use dumpsys netd trafficcontroller instead.");
968 }
Motomu Utsumidf8d2992022-09-01 17:08:27 +0900969 mDeps.nativeDump(fd, verbose);
Motomu Utsumi310850f2022-09-02 12:48:20 +0900970
971 if (verbose) {
972 BpfDump.dumpMap(sUidPermissionMap, pw, "sUidPermissionMap",
973 (uid, permission) -> uid.val + " " + permissionToString(permission.val));
974 }
Ken Chene6d511f2022-01-25 11:10:42 +0800975 }
976
Motomu Utsumi3af8f0e2022-09-02 23:42:13 +0900977 private static native void native_init(boolean startSkDestroyListener);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800978 private native int native_addNaughtyApp(int uid);
979 private native int native_removeNaughtyApp(int uid);
980 private native int native_addNiceApp(int uid);
981 private native int native_removeNiceApp(int uid);
Motomu Utsumi114cd9c2022-08-01 02:08:35 +0000982 private native int native_setChildChain(int childChain, boolean enable);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800983 private native int native_replaceUidChain(String name, boolean isAllowlist, int[] uids);
984 private native int native_setUidRule(int childChain, int uid, int firewallRule);
985 private native int native_addUidInterfaceRules(String ifName, int[] uids);
986 private native int native_removeUidInterfaceRules(int[] uids);
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000987 private native int native_updateUidLockdownRule(int uid, boolean add);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800988 private native int native_swapActiveStatsMap();
Wayne Ma2fde98c2022-01-17 18:04:05 +0800989 private native void native_setPermissionForUids(int permissions, int[] uids);
Motomu Utsumidf8d2992022-09-01 17:08:27 +0900990 private static native void native_dump(FileDescriptor fd, boolean verbose);
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000991 private static native int native_synchronizeKernelRCU();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800992}