blob: dbfc383b72c0a6b8ffd44a216a75ce2e02a1bad9 [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;
30import static android.net.INetd.PERMISSION_UNINSTALLED;
Motomu Utsumi18b287d2022-06-19 10:45:30 +000031import static android.system.OsConstants.EINVAL;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000032import static android.system.OsConstants.ENODEV;
Motomu Utsumi60ed3be2022-06-24 10:38:57 +000033import static android.system.OsConstants.ENOENT;
Ken Chene6d511f2022-01-25 11:10:42 +080034import static android.system.OsConstants.EOPNOTSUPP;
35
Motomu Utsumi166f9662022-09-01 10:35:29 +090036import static com.android.server.ConnectivityStatsLog.NETWORK_BPF_MAP_INFO;
37
38import android.app.StatsManager;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000039import android.content.Context;
Wayne Ma2fde98c2022-01-17 18:04:05 +080040import android.net.INetd;
41import android.os.RemoteException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080042import android.os.ServiceSpecificException;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000043import android.provider.DeviceConfig;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000044import android.system.ErrnoException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080045import android.system.Os;
Motomu Utsumi1a477b02022-08-23 15:14:56 +090046import android.util.ArraySet;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080047import android.util.Log;
Motomu Utsumi166f9662022-09-01 10:35:29 +090048import android.util.StatsEvent;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080049
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000050import com.android.internal.annotations.VisibleForTesting;
Motomu Utsumi166f9662022-09-01 10:35:29 +090051import com.android.modules.utils.BackgroundThread;
Ken Chenf5f51332022-01-28 10:08:16 +080052import com.android.modules.utils.build.SdkLevel;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000053import com.android.net.module.util.BpfMap;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000054import com.android.net.module.util.DeviceConfigUtils;
Motomu Utsumi73599a52022-08-24 11:59:21 +090055import com.android.net.module.util.IBpfMap;
Motomu Utsumi166f9662022-09-01 10:35:29 +090056import com.android.net.module.util.Struct;
Maciej Żenczykowski785793f2022-09-17 02:35:20 +000057import com.android.net.module.util.Struct.S32;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000058import com.android.net.module.util.Struct.U32;
Motomu Utsumi65271202022-07-05 08:21:41 +000059import com.android.net.module.util.Struct.U8;
Motomu Utsumib9548862022-09-06 16:30:05 +090060import com.android.net.module.util.bpf.CookieTagMapKey;
61import com.android.net.module.util.bpf.CookieTagMapValue;
Ken Chenf5f51332022-01-28 10:08:16 +080062
Ken Chene6d511f2022-01-25 11:10:42 +080063import java.io.FileDescriptor;
64import java.io.IOException;
Motomu Utsumi166f9662022-09-01 10:35:29 +090065import java.util.List;
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000066import java.util.Set;
Ken Chene6d511f2022-01-25 11:10:42 +080067
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080068/**
69 * BpfNetMaps is responsible for providing traffic controller relevant functionality.
70 *
71 * {@hide}
72 */
73public class BpfNetMaps {
Motomu Utsumi305975f2022-06-27 09:24:32 +000074 private static final boolean PRE_T = !SdkLevel.isAtLeastT();
75 static {
76 if (!PRE_T) {
77 System.loadLibrary("service-connectivity");
78 }
79 }
80
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080081 private static final String TAG = "BpfNetMaps";
Wayne Ma2fde98c2022-01-17 18:04:05 +080082 private final INetd mNetd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000083 private final Dependencies mDeps;
Ken Chenf5f51332022-01-28 10:08:16 +080084 // Use legacy netd for releases before T.
Ken Chenf5f51332022-01-28 10:08:16 +080085 private static boolean sInitialized = false;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080086
Motomu Utsumif688eeb2022-07-22 03:47:35 +000087 private static Boolean sEnableJavaBpfMap = null;
88 private static final String BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP =
89 "bpf_net_maps_enable_java_bpf_map";
90
Motomu Utsumi18b287d2022-06-19 10:45:30 +000091 // Lock for sConfigurationMap entry for UID_RULES_CONFIGURATION_KEY.
92 // This entry is not accessed by others.
93 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
94 private static final Object sUidRulesConfigBpfMapLock = new Object();
95
Motomu Utsumi7abeaa42022-07-20 07:54:18 +000096 // Lock for sConfigurationMap entry for CURRENT_STATS_MAP_CONFIGURATION_KEY.
97 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
98 // BpfNetMaps is an only writer of this entry.
99 private static final Object sCurrentStatsMapConfigLock = new Object();
100
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000101 private static final String CONFIGURATION_MAP_PATH =
102 "/sys/fs/bpf/netd_shared/map_netd_configuration_map";
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000103 private static final String UID_OWNER_MAP_PATH =
104 "/sys/fs/bpf/netd_shared/map_netd_uid_owner_map";
Motomu Utsumi65271202022-07-05 08:21:41 +0000105 private static final String UID_PERMISSION_MAP_PATH =
106 "/sys/fs/bpf/netd_shared/map_netd_uid_permission_map";
Motomu Utsumib9548862022-09-06 16:30:05 +0900107 private static final String COOKIE_TAG_MAP_PATH =
108 "/sys/fs/bpf/netd_shared/map_netd_cookie_tag_map";
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000109 private static final S32 UID_RULES_CONFIGURATION_KEY = new S32(0);
110 private static final S32 CURRENT_STATS_MAP_CONFIGURATION_KEY = new S32(1);
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000111 private static final long UID_RULES_DEFAULT_CONFIGURATION = 0;
112 private static final long STATS_SELECT_MAP_A = 0;
113 private static final long STATS_SELECT_MAP_B = 1;
114
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000115 private static IBpfMap<S32, U32> sConfigurationMap = null;
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000116 // BpfMap for UID_OWNER_MAP_PATH. This map is not accessed by others.
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000117 private static IBpfMap<S32, UidOwnerValue> sUidOwnerMap = null;
118 private static IBpfMap<S32, U8> sUidPermissionMap = null;
Motomu Utsumib9548862022-09-06 16:30:05 +0900119 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> sCookieTagMap = null;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000120
121 // LINT.IfChange(match_type)
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000122 @VisibleForTesting public static final long NO_MATCH = 0;
123 @VisibleForTesting public static final long HAPPY_BOX_MATCH = (1 << 0);
124 @VisibleForTesting public static final long PENALTY_BOX_MATCH = (1 << 1);
125 @VisibleForTesting public static final long DOZABLE_MATCH = (1 << 2);
126 @VisibleForTesting public static final long STANDBY_MATCH = (1 << 3);
127 @VisibleForTesting public static final long POWERSAVE_MATCH = (1 << 4);
128 @VisibleForTesting public static final long RESTRICTED_MATCH = (1 << 5);
129 @VisibleForTesting public static final long LOW_POWER_STANDBY_MATCH = (1 << 6);
130 @VisibleForTesting public static final long IIF_MATCH = (1 << 7);
131 @VisibleForTesting public static final long LOCKDOWN_VPN_MATCH = (1 << 8);
132 @VisibleForTesting public static final long OEM_DENY_1_MATCH = (1 << 9);
133 @VisibleForTesting public static final long OEM_DENY_2_MATCH = (1 << 10);
134 @VisibleForTesting public static final long OEM_DENY_3_MATCH = (1 << 11);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000135 // LINT.ThenChange(packages/modules/Connectivity/bpf_progs/bpf_shared.h)
136
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000137 /**
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000138 * Set sEnableJavaBpfMap for test.
139 */
140 @VisibleForTesting
141 public static void setEnableJavaBpfMapForTest(boolean enable) {
142 sEnableJavaBpfMap = enable;
143 }
144
145 /**
Motomu Utsumi305975f2022-06-27 09:24:32 +0000146 * Set configurationMap for test.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000147 */
148 @VisibleForTesting
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000149 public static void setConfigurationMapForTest(IBpfMap<S32, U32> configurationMap) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000150 sConfigurationMap = configurationMap;
151 }
152
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000153 /**
154 * Set uidOwnerMap for test.
155 */
156 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000157 public static void setUidOwnerMapForTest(IBpfMap<S32, UidOwnerValue> uidOwnerMap) {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000158 sUidOwnerMap = uidOwnerMap;
159 }
160
Motomu Utsumi65271202022-07-05 08:21:41 +0000161 /**
162 * Set uidPermissionMap for test.
163 */
164 @VisibleForTesting
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000165 public static void setUidPermissionMapForTest(IBpfMap<S32, U8> uidPermissionMap) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000166 sUidPermissionMap = uidPermissionMap;
167 }
168
Motomu Utsumib9548862022-09-06 16:30:05 +0900169 /**
170 * Set cookieTagMap for test.
171 */
172 @VisibleForTesting
173 public static void setCookieTagMapForTest(
174 IBpfMap<CookieTagMapKey, CookieTagMapValue> cookieTagMap) {
175 sCookieTagMap = cookieTagMap;
176 }
177
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000178 private static IBpfMap<S32, U32> getConfigurationMap() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000179 try {
180 return new BpfMap<>(
Maciej Żenczykowskidc886222022-09-17 06:09:22 +0000181 CONFIGURATION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U32.class);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000182 } catch (ErrnoException e) {
183 throw new IllegalStateException("Cannot open netd configuration map", e);
184 }
185 }
186
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000187 private static IBpfMap<S32, UidOwnerValue> getUidOwnerMap() {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000188 try {
189 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000190 UID_OWNER_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, UidOwnerValue.class);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000191 } catch (ErrnoException e) {
192 throw new IllegalStateException("Cannot open uid owner map", e);
193 }
194 }
195
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000196 private static IBpfMap<S32, U8> getUidPermissionMap() {
Motomu Utsumi65271202022-07-05 08:21:41 +0000197 try {
198 return new BpfMap<>(
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000199 UID_PERMISSION_MAP_PATH, BpfMap.BPF_F_RDWR, S32.class, U8.class);
Motomu Utsumi65271202022-07-05 08:21:41 +0000200 } catch (ErrnoException e) {
201 throw new IllegalStateException("Cannot open uid permission map", e);
202 }
203 }
204
Motomu Utsumib9548862022-09-06 16:30:05 +0900205 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> getCookieTagMap() {
206 try {
207 return new BpfMap<>(COOKIE_TAG_MAP_PATH, BpfMap.BPF_F_RDWR,
208 CookieTagMapKey.class, CookieTagMapValue.class);
209 } catch (ErrnoException e) {
210 throw new IllegalStateException("Cannot open cookie tag map", e);
211 }
212 }
213
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000214 private static void initBpfMaps() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000215 if (sConfigurationMap == null) {
216 sConfigurationMap = getConfigurationMap();
217 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000218 try {
219 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY,
220 new U32(UID_RULES_DEFAULT_CONFIGURATION));
221 } catch (ErrnoException e) {
222 throw new IllegalStateException("Failed to initialize uid rules configuration", e);
223 }
224 try {
225 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
226 new U32(STATS_SELECT_MAP_A));
227 } catch (ErrnoException e) {
228 throw new IllegalStateException("Failed to initialize current stats configuration", e);
229 }
230
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000231 if (sUidOwnerMap == null) {
232 sUidOwnerMap = getUidOwnerMap();
233 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000234 try {
235 sUidOwnerMap.clear();
236 } catch (ErrnoException e) {
237 throw new IllegalStateException("Failed to initialize uid owner map", e);
238 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000239
240 if (sUidPermissionMap == null) {
241 sUidPermissionMap = getUidPermissionMap();
242 }
Motomu Utsumib9548862022-09-06 16:30:05 +0900243
244 if (sCookieTagMap == null) {
245 sCookieTagMap = getCookieTagMap();
246 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000247 }
248
Ken Chenf5f51332022-01-28 10:08:16 +0800249 /**
250 * Initializes the class if it is not already initialized. This method will open maps but not
251 * cause any other effects. This method may be called multiple times on any thread.
252 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000253 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800254 if (sInitialized) return;
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000255 if (sEnableJavaBpfMap == null) {
256 sEnableJavaBpfMap = DeviceConfigUtils.isFeatureEnabled(context,
257 DeviceConfig.NAMESPACE_TETHERING, BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP,
258 SdkLevel.isAtLeastU() /* defaultValue */);
259 }
260 Log.d(TAG, "BpfNetMaps is initialized with sEnableJavaBpfMap=" + sEnableJavaBpfMap);
261
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000262 initBpfMaps();
Motomu Utsumid95a0da2022-09-03 00:40:30 +0900263 native_init(!sEnableJavaBpfMap /* startSkDestroyListener */);
Ken Chenf5f51332022-01-28 10:08:16 +0800264 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800265 }
266
Motomu Utsumid95a0da2022-09-03 00:40:30 +0900267 public boolean isSkDestroyListenerRunning() {
268 return !sEnableJavaBpfMap;
269 }
270
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000271 /**
272 * Dependencies of BpfNetMaps, for injection in tests.
273 */
274 @VisibleForTesting
275 public static class Dependencies {
276 /**
277 * Get interface index.
278 */
279 public int getIfIndex(final String ifName) {
280 return Os.if_nametoindex(ifName);
281 }
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000282
283 /**
284 * Call synchronize_rcu()
285 */
286 public int synchronizeKernelRCU() {
287 return native_synchronizeKernelRCU();
288 }
Motomu Utsumi166f9662022-09-01 10:35:29 +0900289
290 /**
291 * Build Stats Event for NETWORK_BPF_MAP_INFO atom
292 */
293 public StatsEvent buildStatsEvent(final int cookieTagMapSize, final int uidOwnerMapSize,
294 final int uidPermissionMapSize) {
295 return ConnectivityStatsLog.buildStatsEvent(NETWORK_BPF_MAP_INFO, cookieTagMapSize,
296 uidOwnerMapSize, uidPermissionMapSize);
297 }
Motomu Utsumidf8d2992022-09-01 17:08:27 +0900298
299 /**
300 * Call native_dump
301 */
302 public void nativeDump(final FileDescriptor fd, final boolean verbose) {
303 native_dump(fd, verbose);
304 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000305 }
306
markchien49e944c2022-03-01 15:22:20 +0800307 /** Constructor used after T that doesn't need to use netd anymore. */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000308 public BpfNetMaps(final Context context) {
309 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800310
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000311 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800312 }
313
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000314 public BpfNetMaps(final Context context, final INetd netd) {
315 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000316 }
317
318 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000319 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000320 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000321 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000322 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800323 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000324 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800325 }
326
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000327 /**
328 * Get corresponding match from firewall chain.
329 */
330 @VisibleForTesting
331 public long getMatchByFirewallChain(final int chain) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000332 switch (chain) {
333 case FIREWALL_CHAIN_DOZABLE:
334 return DOZABLE_MATCH;
335 case FIREWALL_CHAIN_STANDBY:
336 return STANDBY_MATCH;
337 case FIREWALL_CHAIN_POWERSAVE:
338 return POWERSAVE_MATCH;
339 case FIREWALL_CHAIN_RESTRICTED:
340 return RESTRICTED_MATCH;
341 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
342 return LOW_POWER_STANDBY_MATCH;
343 case FIREWALL_CHAIN_OEM_DENY_1:
344 return OEM_DENY_1_MATCH;
345 case FIREWALL_CHAIN_OEM_DENY_2:
346 return OEM_DENY_2_MATCH;
347 case FIREWALL_CHAIN_OEM_DENY_3:
348 return OEM_DENY_3_MATCH;
349 default:
350 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000351 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000352 }
353
354 /**
355 * Get if the chain is allow list or not.
356 *
357 * ALLOWLIST means the firewall denies all by default, uids must be explicitly allowed
358 * DENYLIST means the firewall allows all by default, uids must be explicitly denyed
359 */
360 @VisibleForTesting
361 public boolean isFirewallAllowList(final int chain) {
362 switch (chain) {
363 case FIREWALL_CHAIN_DOZABLE:
364 case FIREWALL_CHAIN_POWERSAVE:
365 case FIREWALL_CHAIN_RESTRICTED:
366 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
367 return true;
368 case FIREWALL_CHAIN_STANDBY:
369 case FIREWALL_CHAIN_OEM_DENY_1:
370 case FIREWALL_CHAIN_OEM_DENY_2:
371 case FIREWALL_CHAIN_OEM_DENY_3:
372 return false;
373 default:
374 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
375 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000376 }
377
Ken Chenf5f51332022-01-28 10:08:16 +0800378 private void maybeThrow(final int err, final String msg) {
379 if (err != 0) {
380 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
381 }
382 }
383
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000384 private void throwIfPreT(final String msg) {
385 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000386 throw new UnsupportedOperationException(msg);
387 }
388 }
389
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000390 private void removeRule(final int uid, final long match, final String caller) {
391 try {
392 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000393 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000394
395 if (oldMatch == null) {
396 throw new ServiceSpecificException(ENOENT,
397 "sUidOwnerMap does not have entry for uid: " + uid);
398 }
399
400 final UidOwnerValue newMatch = new UidOwnerValue(
401 (match == IIF_MATCH) ? 0 : oldMatch.iif,
402 oldMatch.rule & ~match
403 );
404
405 if (newMatch.rule == 0) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000406 sUidOwnerMap.deleteEntry(new S32(uid));
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000407 } else {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000408 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000409 }
410 }
411 } catch (ErrnoException e) {
412 throw new ServiceSpecificException(e.errno,
413 caller + " failed to remove rule: " + Os.strerror(e.errno));
414 }
415 }
416
Maciej Żenczykowski6c1c6bb2022-09-16 06:55:33 +0000417 private void addRule(final int uid, final long match, final int iif, final String caller) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000418 if (match != IIF_MATCH && iif != 0) {
419 throw new ServiceSpecificException(EINVAL,
420 "Non-interface match must have zero interface index");
421 }
422
423 try {
424 synchronized (sUidOwnerMap) {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000425 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new S32(uid));
Motomu Utsumi389278e2022-06-28 07:05:05 +0000426
427 final UidOwnerValue newMatch;
428 if (oldMatch != null) {
429 newMatch = new UidOwnerValue(
430 (match == IIF_MATCH) ? iif : oldMatch.iif,
431 oldMatch.rule | match
432 );
433 } else {
434 newMatch = new UidOwnerValue(
435 iif,
436 match
437 );
438 }
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000439 sUidOwnerMap.updateEntry(new S32(uid), newMatch);
Motomu Utsumi389278e2022-06-28 07:05:05 +0000440 }
441 } catch (ErrnoException e) {
442 throw new ServiceSpecificException(e.errno,
443 caller + " failed to add rule: " + Os.strerror(e.errno));
444 }
445 }
446
447 private void addRule(final int uid, final long match, final String caller) {
448 addRule(uid, match, 0 /* iif */, caller);
449 }
450
Ken Chenf5f51332022-01-28 10:08:16 +0800451 /**
452 * Add naughty app bandwidth rule for specific app
453 *
454 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800455 * @throws ServiceSpecificException in case of failure, with an error code indicating the
456 * cause of the failure.
457 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900458 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000459 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000460
461 if (sEnableJavaBpfMap) {
462 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
463 } else {
464 final int err = native_addNaughtyApp(uid);
465 maybeThrow(err, "Unable to add naughty app");
466 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800467 }
468
Ken Chenf5f51332022-01-28 10:08:16 +0800469 /**
470 * Remove naughty app bandwidth rule for specific app
471 *
472 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800473 * @throws ServiceSpecificException in case of failure, with an error code indicating the
474 * cause of the failure.
475 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900476 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000477 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000478
479 if (sEnableJavaBpfMap) {
480 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
481 } else {
482 final int err = native_removeNaughtyApp(uid);
483 maybeThrow(err, "Unable to remove naughty app");
484 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800485 }
486
Ken Chenf5f51332022-01-28 10:08:16 +0800487 /**
488 * Add nice app bandwidth rule for specific app
489 *
490 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800491 * @throws ServiceSpecificException in case of failure, with an error code indicating the
492 * cause of the failure.
493 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900494 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000495 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000496
497 if (sEnableJavaBpfMap) {
498 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
499 } else {
500 final int err = native_addNiceApp(uid);
501 maybeThrow(err, "Unable to add nice app");
502 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800503 }
504
Ken Chenf5f51332022-01-28 10:08:16 +0800505 /**
506 * Remove nice app bandwidth rule for specific app
507 *
508 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800509 * @throws ServiceSpecificException in case of failure, with an error code indicating the
510 * cause of the failure.
511 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900512 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000513 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000514
515 if (sEnableJavaBpfMap) {
516 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
517 } else {
518 final int err = native_removeNiceApp(uid);
519 maybeThrow(err, "Unable to remove nice app");
520 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800521 }
522
Ken Chenf5f51332022-01-28 10:08:16 +0800523 /**
524 * Set target firewall child chain
525 *
526 * @param childChain target chain to enable
527 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000528 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800529 * @throws ServiceSpecificException in case of failure, with an error code indicating the
530 * cause of the failure.
531 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900532 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000533 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000534
Motomu Utsumie057dd42022-08-03 01:23:49 +0000535 if (sEnableJavaBpfMap) {
536 final long match = getMatchByFirewallChain(childChain);
537 try {
538 synchronized (sUidRulesConfigBpfMapLock) {
539 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
540 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
541 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
542 }
543 } catch (ErrnoException e) {
544 throw new ServiceSpecificException(e.errno,
545 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000546 }
Motomu Utsumie057dd42022-08-03 01:23:49 +0000547 } else {
548 final int err = native_setChildChain(childChain, enable);
549 maybeThrow(err, "Unable to set child chain");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000550 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800551 }
552
553 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000554 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000555 *
556 * @param childChain target chain
557 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
558 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000559 * @throws ServiceSpecificException in case of failure, with an error code indicating the
560 * cause of the failure.
561 */
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000562 public boolean isChainEnabled(final int childChain) {
563 throwIfPreT("isChainEnabled is not available on pre-T devices");
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000564
565 final long match = getMatchByFirewallChain(childChain);
566 try {
567 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000568 return (config.val & match) != 0;
569 } catch (ErrnoException e) {
570 throw new ServiceSpecificException(e.errno,
571 "Unable to get firewall chain status: " + Os.strerror(e.errno));
572 }
573 }
574
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900575 private Set<Integer> asSet(final int[] uids) {
576 final Set<Integer> uidSet = new ArraySet<>();
577 for (final int uid: uids) {
578 uidSet.add(uid);
579 }
580 return uidSet;
581 }
582
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000583 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800584 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000585 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800586 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000587 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800588 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000589 * @throws UnsupportedOperationException if called on pre-T devices.
590 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800591 */
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000592 public void replaceUidChain(final int chain, final int[] uids) {
593 throwIfPreT("replaceUidChain is not available on pre-T devices");
594
Motomu Utsumic7c16852022-08-03 06:51:41 +0000595 if (sEnableJavaBpfMap) {
596 final long match;
597 try {
598 match = getMatchByFirewallChain(chain);
599 } catch (ServiceSpecificException e) {
600 // Throws IllegalArgumentException to keep the behavior of
601 // ConnectivityManager#replaceFirewallChain API
602 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000603 }
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900604 final Set<Integer> uidSet = asSet(uids);
605 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
Motomu Utsumic7c16852022-08-03 06:51:41 +0000606 try {
607 synchronized (sUidOwnerMap) {
608 sUidOwnerMap.forEach((uid, config) -> {
609 // config could be null if there is a concurrent entry deletion.
Motomu Utsumi8e420ea2022-08-24 18:03:30 +0900610 // http://b/220084230. But sUidOwnerMap update must be done while holding a
611 // lock, so this should not happen.
612 if (config == null) {
613 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
614 } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
Motomu Utsumic7c16852022-08-03 06:51:41 +0000615 uidSetToRemoveRule.add((int) uid.val);
616 }
617 });
618
619 for (final int uid : uidSetToRemoveRule) {
620 removeRule(uid, match, "replaceUidChain");
621 }
622 for (final int uid : uids) {
623 addRule(uid, match, "replaceUidChain");
624 }
625 }
626 } catch (ErrnoException | ServiceSpecificException e) {
627 Log.e(TAG, "replaceUidChain failed: " + e);
628 }
629 } else {
630 final int err;
631 switch (chain) {
632 case FIREWALL_CHAIN_DOZABLE:
633 err = native_replaceUidChain("fw_dozable", true /* isAllowList */, uids);
634 break;
635 case FIREWALL_CHAIN_STANDBY:
636 err = native_replaceUidChain("fw_standby", false /* isAllowList */, uids);
637 break;
638 case FIREWALL_CHAIN_POWERSAVE:
639 err = native_replaceUidChain("fw_powersave", true /* isAllowList */, uids);
640 break;
641 case FIREWALL_CHAIN_RESTRICTED:
642 err = native_replaceUidChain("fw_restricted", true /* isAllowList */, uids);
643 break;
644 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
645 err = native_replaceUidChain(
646 "fw_low_power_standby", true /* isAllowList */, uids);
647 break;
648 case FIREWALL_CHAIN_OEM_DENY_1:
649 err = native_replaceUidChain("fw_oem_deny_1", false /* isAllowList */, uids);
650 break;
651 case FIREWALL_CHAIN_OEM_DENY_2:
652 err = native_replaceUidChain("fw_oem_deny_2", false /* isAllowList */, uids);
653 break;
654 case FIREWALL_CHAIN_OEM_DENY_3:
655 err = native_replaceUidChain("fw_oem_deny_3", false /* isAllowList */, uids);
656 break;
657 default:
658 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
659 + chain);
660 }
661 if (err != 0) {
662 Log.e(TAG, "replaceUidChain failed: " + Os.strerror(-err));
663 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800664 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800665 }
666
Ken Chenf5f51332022-01-28 10:08:16 +0800667 /**
668 * Set firewall rule for uid
669 *
670 * @param childChain target chain
671 * @param uid uid to allow/deny
672 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800673 * @throws ServiceSpecificException in case of failure, with an error code indicating the
674 * cause of the failure.
675 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900676 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000677 throwIfPreT("setUidRule is not available on pre-T devices");
678
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000679 if (sEnableJavaBpfMap) {
680 final long match = getMatchByFirewallChain(childChain);
681 final boolean isAllowList = isFirewallAllowList(childChain);
682 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
683 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000684
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000685 if (add) {
686 addRule(uid, match, "setUidRule");
687 } else {
688 removeRule(uid, match, "setUidRule");
689 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000690 } else {
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000691 final int err = native_setUidRule(childChain, uid, firewallRule);
692 maybeThrow(err, "Unable to set uid rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000693 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800694 }
695
696 /**
697 * Add ingress interface filtering rules to a list of UIDs
698 *
699 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
700 * allowed interface and loopback to be sent to the list of UIDs.
701 *
702 * Calling this method on one or more UIDs with an existing filtering rule but a different
703 * interface name will result in the filtering rule being updated to allow the new interface
704 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
705 *
706 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800707 * be received.
708 * @param uids an array of UIDs which the filtering rules will be set
709 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800710 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800711 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800712 */
Ken Chenf5f51332022-01-28 10:08:16 +0800713 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000714 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800715 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800716 return;
717 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000718
719 if (sEnableJavaBpfMap) {
720 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
721 // ifIndex is set to 0.
722 final int ifIndex;
723 if (ifName == null) {
724 ifIndex = 0;
725 } else {
726 ifIndex = mDeps.getIfIndex(ifName);
727 if (ifIndex == 0) {
728 throw new ServiceSpecificException(ENODEV,
729 "Failed to get index of interface " + ifName);
730 }
731 }
732 for (final int uid : uids) {
733 try {
734 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
735 } catch (ServiceSpecificException e) {
736 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
737 }
738 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000739 } else {
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000740 final int err = native_addUidInterfaceRules(ifName, uids);
741 maybeThrow(err, "Unable to add uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000742 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800743 }
744
745 /**
746 * Remove ingress interface filtering rules from a list of UIDs
747 *
748 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
749 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
750 *
751 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800752 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800753 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800754 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800755 */
Ken Chenf5f51332022-01-28 10:08:16 +0800756 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000757 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800758 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800759 return;
760 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000761
762 if (sEnableJavaBpfMap) {
763 for (final int uid : uids) {
764 try {
765 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
766 } catch (ServiceSpecificException e) {
767 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
768 }
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000769 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000770 } else {
771 final int err = native_removeUidInterfaceRules(uids);
772 maybeThrow(err, "Unable to remove uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000773 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800774 }
775
Ken Chenf5f51332022-01-28 10:08:16 +0800776 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000777 * Update lockdown rule for uid
778 *
779 * @param uid target uid to add/remove the rule
780 * @param add {@code true} to add the rule, {@code false} to remove the rule.
781 * @throws ServiceSpecificException in case of failure, with an error code indicating the
782 * cause of the failure.
783 */
784 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000785 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000786
787 if (sEnableJavaBpfMap) {
788 if (add) {
789 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
790 } else {
791 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
792 }
Motomu Utsumi697b2992022-06-30 02:25:29 +0000793 } else {
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000794 final int err = native_updateUidLockdownRule(uid, add);
795 maybeThrow(err, "Unable to update lockdown rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000796 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000797 }
798
799 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800800 * Request netd to change the current active network stats map.
801 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000802 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800803 * @throws ServiceSpecificException in case of failure, with an error code indicating the
804 * cause of the failure.
805 */
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
809 if (sEnableJavaBpfMap) {
810 try {
811 synchronized (sCurrentStatsMapConfigLock) {
812 final long config = sConfigurationMap.getValue(
813 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
814 final long newConfig = (config == STATS_SELECT_MAP_A)
815 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
816 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
817 new U32(newConfig));
818 }
819 } catch (ErrnoException e) {
820 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
821 }
822
823 // After changing the config, it's needed to make sure all the current running eBPF
824 // programs are finished and all the CPUs are aware of this config change before the old
825 // map is modified. So special hack is needed here to wait for the kernel to do a
826 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
827 // be available to all cores and the next eBPF programs triggered inside the kernel will
828 // use the new map configuration. So once this function returns it is safe to modify the
829 // old stats map without concerning about race between the kernel and userspace.
830 final int err = mDeps.synchronizeKernelRCU();
831 maybeThrow(err, "synchronizeKernelRCU failed");
832 } else {
833 final int err = native_swapActiveStatsMap();
834 maybeThrow(err, "Unable to swap active stats map");
835 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800836 }
837
Ken Chenf5f51332022-01-28 10:08:16 +0800838 /**
839 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
840 * specified. Or remove all permissions from the uids.
841 *
842 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
843 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
844 * revoke all permissions for the uids.
845 * @param uids uid of users to grant permission
846 * @throws RemoteException when netd has crashed.
847 */
848 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000849 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800850 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800851 return;
852 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000853
854 if (sEnableJavaBpfMap) {
855 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
856 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
857 for (final int uid : uids) {
858 try {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000859 sUidPermissionMap.deleteEntry(new S32(uid));
Motomu Utsumi65271202022-07-05 08:21:41 +0000860 } catch (ErrnoException e) {
861 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
862 }
863 }
864 return;
865 }
866
867 for (final int uid : uids) {
868 try {
Maciej Żenczykowski785793f2022-09-17 02:35:20 +0000869 sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
Motomu Utsumi65271202022-07-05 08:21:41 +0000870 } catch (ErrnoException e) {
871 Log.e(TAG, "Failed to set permission "
872 + permissions + " to uid " + uid + ": " + e);
873 }
874 }
875 } else {
876 native_setPermissionForUids(permissions, uids);
877 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800878 }
879
Motomu Utsumi166f9662022-09-01 10:35:29 +0900880 /** Register callback for statsd to pull atom. */
881 public void setPullAtomCallback(final Context context) {
882 throwIfPreT("setPullAtomCallback is not available on pre-T devices");
883
884 final StatsManager statsManager = context.getSystemService(StatsManager.class);
885 statsManager.setPullAtomCallback(NETWORK_BPF_MAP_INFO, null /* metadata */,
886 BackgroundThread.getExecutor(), this::pullBpfMapInfoAtom);
887 }
888
889 private <K extends Struct, V extends Struct> int getMapSize(IBpfMap<K, V> map)
890 throws ErrnoException {
891 // forEach could restart iteration from the beginning if there is a concurrent entry
892 // deletion. netd and skDestroyListener could delete CookieTagMap entry concurrently.
893 // So using Set to count the number of entry in the map.
894 Set<K> keySet = new ArraySet<>();
895 map.forEach((k, v) -> keySet.add(k));
896 return keySet.size();
897 }
898
899 /** Callback for StatsManager#setPullAtomCallback */
900 @VisibleForTesting
901 public int pullBpfMapInfoAtom(final int atomTag, final List<StatsEvent> data) {
902 if (atomTag != NETWORK_BPF_MAP_INFO) {
903 Log.e(TAG, "Unexpected atom tag: " + atomTag);
904 return StatsManager.PULL_SKIP;
905 }
906
907 try {
908 data.add(mDeps.buildStatsEvent(getMapSize(sCookieTagMap), getMapSize(sUidOwnerMap),
909 getMapSize(sUidPermissionMap)));
910 } catch (ErrnoException e) {
911 Log.e(TAG, "Failed to pull NETWORK_BPF_MAP_INFO atom: " + e);
912 return StatsManager.PULL_SKIP;
913 }
914 return StatsManager.PULL_SUCCESS;
915 }
916
Ken Chene6d511f2022-01-25 11:10:42 +0800917 /**
918 * Dump BPF maps
919 *
920 * @param fd file descriptor to output
921 * @throws IOException when file descriptor is invalid.
922 * @throws ServiceSpecificException when the method is called on an unsupported device.
923 */
924 public void dump(final FileDescriptor fd, boolean verbose)
925 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000926 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +0800927 throw new ServiceSpecificException(
928 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
929 + " devices, use dumpsys netd trafficcontroller instead.");
930 }
Motomu Utsumidf8d2992022-09-01 17:08:27 +0900931 mDeps.nativeDump(fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +0800932 }
933
Motomu Utsumi3af8f0e2022-09-02 23:42:13 +0900934 private static native void native_init(boolean startSkDestroyListener);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800935 private native int native_addNaughtyApp(int uid);
936 private native int native_removeNaughtyApp(int uid);
937 private native int native_addNiceApp(int uid);
938 private native int native_removeNiceApp(int uid);
Motomu Utsumi114cd9c2022-08-01 02:08:35 +0000939 private native int native_setChildChain(int childChain, boolean enable);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800940 private native int native_replaceUidChain(String name, boolean isAllowlist, int[] uids);
941 private native int native_setUidRule(int childChain, int uid, int firewallRule);
942 private native int native_addUidInterfaceRules(String ifName, int[] uids);
943 private native int native_removeUidInterfaceRules(int[] uids);
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000944 private native int native_updateUidLockdownRule(int uid, boolean add);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800945 private native int native_swapActiveStatsMap();
Wayne Ma2fde98c2022-01-17 18:04:05 +0800946 private native void native_setPermissionForUids(int permissions, int[] uids);
Motomu Utsumidf8d2992022-09-01 17:08:27 +0900947 private static native void native_dump(FileDescriptor fd, boolean verbose);
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000948 private static native int native_synchronizeKernelRCU();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800949}