blob: bfa0808984e631d232be24906e9638783f80e9d8 [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;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000057import com.android.net.module.util.Struct.U32;
Motomu Utsumi65271202022-07-05 08:21:41 +000058import com.android.net.module.util.Struct.U8;
Motomu Utsumib9548862022-09-06 16:30:05 +090059import com.android.net.module.util.bpf.CookieTagMapKey;
60import com.android.net.module.util.bpf.CookieTagMapValue;
Ken Chenf5f51332022-01-28 10:08:16 +080061
Ken Chene6d511f2022-01-25 11:10:42 +080062import java.io.FileDescriptor;
63import java.io.IOException;
Motomu Utsumi166f9662022-09-01 10:35:29 +090064import java.util.List;
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000065import java.util.Set;
Ken Chene6d511f2022-01-25 11:10:42 +080066
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080067/**
68 * BpfNetMaps is responsible for providing traffic controller relevant functionality.
69 *
70 * {@hide}
71 */
72public class BpfNetMaps {
Motomu Utsumi305975f2022-06-27 09:24:32 +000073 private static final boolean PRE_T = !SdkLevel.isAtLeastT();
74 static {
75 if (!PRE_T) {
76 System.loadLibrary("service-connectivity");
77 }
78 }
79
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080080 private static final String TAG = "BpfNetMaps";
Wayne Ma2fde98c2022-01-17 18:04:05 +080081 private final INetd mNetd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000082 private final Dependencies mDeps;
Ken Chenf5f51332022-01-28 10:08:16 +080083 // Use legacy netd for releases before T.
Ken Chenf5f51332022-01-28 10:08:16 +080084 private static boolean sInitialized = false;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080085
Motomu Utsumif688eeb2022-07-22 03:47:35 +000086 private static Boolean sEnableJavaBpfMap = null;
87 private static final String BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP =
88 "bpf_net_maps_enable_java_bpf_map";
89
Motomu Utsumi18b287d2022-06-19 10:45:30 +000090 // Lock for sConfigurationMap entry for UID_RULES_CONFIGURATION_KEY.
91 // This entry is not accessed by others.
92 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
93 private static final Object sUidRulesConfigBpfMapLock = new Object();
94
Motomu Utsumi7abeaa42022-07-20 07:54:18 +000095 // Lock for sConfigurationMap entry for CURRENT_STATS_MAP_CONFIGURATION_KEY.
96 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
97 // BpfNetMaps is an only writer of this entry.
98 private static final Object sCurrentStatsMapConfigLock = new Object();
99
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000100 private static final String CONFIGURATION_MAP_PATH =
101 "/sys/fs/bpf/netd_shared/map_netd_configuration_map";
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000102 private static final String UID_OWNER_MAP_PATH =
103 "/sys/fs/bpf/netd_shared/map_netd_uid_owner_map";
Motomu Utsumi65271202022-07-05 08:21:41 +0000104 private static final String UID_PERMISSION_MAP_PATH =
105 "/sys/fs/bpf/netd_shared/map_netd_uid_permission_map";
Motomu Utsumib9548862022-09-06 16:30:05 +0900106 private static final String COOKIE_TAG_MAP_PATH =
107 "/sys/fs/bpf/netd_shared/map_netd_cookie_tag_map";
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000108 private static final U32 UID_RULES_CONFIGURATION_KEY = new U32(0);
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000109 private static final U32 CURRENT_STATS_MAP_CONFIGURATION_KEY = new U32(1);
110 private static final long UID_RULES_DEFAULT_CONFIGURATION = 0;
111 private static final long STATS_SELECT_MAP_A = 0;
112 private static final long STATS_SELECT_MAP_B = 1;
113
Motomu Utsumi73599a52022-08-24 11:59:21 +0900114 private static IBpfMap<U32, U32> sConfigurationMap = null;
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000115 // BpfMap for UID_OWNER_MAP_PATH. This map is not accessed by others.
Motomu Utsumi73599a52022-08-24 11:59:21 +0900116 private static IBpfMap<U32, UidOwnerValue> sUidOwnerMap = null;
117 private static IBpfMap<U32, U8> sUidPermissionMap = null;
Motomu Utsumib9548862022-09-06 16:30:05 +0900118 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> sCookieTagMap = null;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000119
120 // LINT.IfChange(match_type)
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000121 @VisibleForTesting public static final long NO_MATCH = 0;
122 @VisibleForTesting public static final long HAPPY_BOX_MATCH = (1 << 0);
123 @VisibleForTesting public static final long PENALTY_BOX_MATCH = (1 << 1);
124 @VisibleForTesting public static final long DOZABLE_MATCH = (1 << 2);
125 @VisibleForTesting public static final long STANDBY_MATCH = (1 << 3);
126 @VisibleForTesting public static final long POWERSAVE_MATCH = (1 << 4);
127 @VisibleForTesting public static final long RESTRICTED_MATCH = (1 << 5);
128 @VisibleForTesting public static final long LOW_POWER_STANDBY_MATCH = (1 << 6);
129 @VisibleForTesting public static final long IIF_MATCH = (1 << 7);
130 @VisibleForTesting public static final long LOCKDOWN_VPN_MATCH = (1 << 8);
131 @VisibleForTesting public static final long OEM_DENY_1_MATCH = (1 << 9);
132 @VisibleForTesting public static final long OEM_DENY_2_MATCH = (1 << 10);
133 @VisibleForTesting public static final long OEM_DENY_3_MATCH = (1 << 11);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000134 // LINT.ThenChange(packages/modules/Connectivity/bpf_progs/bpf_shared.h)
135
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000136 /**
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000137 * Set sEnableJavaBpfMap for test.
138 */
139 @VisibleForTesting
140 public static void setEnableJavaBpfMapForTest(boolean enable) {
141 sEnableJavaBpfMap = enable;
142 }
143
144 /**
Motomu Utsumi305975f2022-06-27 09:24:32 +0000145 * Set configurationMap for test.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000146 */
147 @VisibleForTesting
Motomu Utsumi73599a52022-08-24 11:59:21 +0900148 public static void setConfigurationMapForTest(IBpfMap<U32, U32> configurationMap) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000149 sConfigurationMap = configurationMap;
150 }
151
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000152 /**
153 * Set uidOwnerMap for test.
154 */
155 @VisibleForTesting
Motomu Utsumi73599a52022-08-24 11:59:21 +0900156 public static void setUidOwnerMapForTest(IBpfMap<U32, UidOwnerValue> uidOwnerMap) {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000157 sUidOwnerMap = uidOwnerMap;
158 }
159
Motomu Utsumi65271202022-07-05 08:21:41 +0000160 /**
161 * Set uidPermissionMap for test.
162 */
163 @VisibleForTesting
Motomu Utsumi73599a52022-08-24 11:59:21 +0900164 public static void setUidPermissionMapForTest(IBpfMap<U32, U8> uidPermissionMap) {
Motomu Utsumi65271202022-07-05 08:21:41 +0000165 sUidPermissionMap = uidPermissionMap;
166 }
167
Motomu Utsumib9548862022-09-06 16:30:05 +0900168 /**
169 * Set cookieTagMap for test.
170 */
171 @VisibleForTesting
172 public static void setCookieTagMapForTest(
173 IBpfMap<CookieTagMapKey, CookieTagMapValue> cookieTagMap) {
174 sCookieTagMap = cookieTagMap;
175 }
176
Motomu Utsumi73599a52022-08-24 11:59:21 +0900177 private static IBpfMap<U32, U32> getConfigurationMap() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000178 try {
179 return new BpfMap<>(
180 CONFIGURATION_MAP_PATH, BpfMap.BPF_F_RDWR, U32.class, U32.class);
181 } catch (ErrnoException e) {
182 throw new IllegalStateException("Cannot open netd configuration map", e);
183 }
184 }
185
Motomu Utsumi73599a52022-08-24 11:59:21 +0900186 private static IBpfMap<U32, UidOwnerValue> getUidOwnerMap() {
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000187 try {
188 return new BpfMap<>(
189 UID_OWNER_MAP_PATH, BpfMap.BPF_F_RDWR, U32.class, UidOwnerValue.class);
190 } catch (ErrnoException e) {
191 throw new IllegalStateException("Cannot open uid owner map", e);
192 }
193 }
194
Motomu Utsumi73599a52022-08-24 11:59:21 +0900195 private static IBpfMap<U32, U8> getUidPermissionMap() {
Motomu Utsumi65271202022-07-05 08:21:41 +0000196 try {
197 return new BpfMap<>(
198 UID_PERMISSION_MAP_PATH, BpfMap.BPF_F_RDWR, U32.class, U8.class);
199 } catch (ErrnoException e) {
200 throw new IllegalStateException("Cannot open uid permission map", e);
201 }
202 }
203
Motomu Utsumib9548862022-09-06 16:30:05 +0900204 private static IBpfMap<CookieTagMapKey, CookieTagMapValue> getCookieTagMap() {
205 try {
206 return new BpfMap<>(COOKIE_TAG_MAP_PATH, BpfMap.BPF_F_RDWR,
207 CookieTagMapKey.class, CookieTagMapValue.class);
208 } catch (ErrnoException e) {
209 throw new IllegalStateException("Cannot open cookie tag map", e);
210 }
211 }
212
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000213 private static void initBpfMaps() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000214 if (sConfigurationMap == null) {
215 sConfigurationMap = getConfigurationMap();
216 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000217 try {
218 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY,
219 new U32(UID_RULES_DEFAULT_CONFIGURATION));
220 } catch (ErrnoException e) {
221 throw new IllegalStateException("Failed to initialize uid rules configuration", e);
222 }
223 try {
224 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
225 new U32(STATS_SELECT_MAP_A));
226 } catch (ErrnoException e) {
227 throw new IllegalStateException("Failed to initialize current stats configuration", e);
228 }
229
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000230 if (sUidOwnerMap == null) {
231 sUidOwnerMap = getUidOwnerMap();
232 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000233 try {
234 sUidOwnerMap.clear();
235 } catch (ErrnoException e) {
236 throw new IllegalStateException("Failed to initialize uid owner map", e);
237 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000238
239 if (sUidPermissionMap == null) {
240 sUidPermissionMap = getUidPermissionMap();
241 }
Motomu Utsumib9548862022-09-06 16:30:05 +0900242
243 if (sCookieTagMap == null) {
244 sCookieTagMap = getCookieTagMap();
245 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000246 }
247
Ken Chenf5f51332022-01-28 10:08:16 +0800248 /**
249 * Initializes the class if it is not already initialized. This method will open maps but not
250 * cause any other effects. This method may be called multiple times on any thread.
251 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000252 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800253 if (sInitialized) return;
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000254 if (sEnableJavaBpfMap == null) {
255 sEnableJavaBpfMap = DeviceConfigUtils.isFeatureEnabled(context,
256 DeviceConfig.NAMESPACE_TETHERING, BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP,
257 SdkLevel.isAtLeastU() /* defaultValue */);
258 }
259 Log.d(TAG, "BpfNetMaps is initialized with sEnableJavaBpfMap=" + sEnableJavaBpfMap);
260
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000261 initBpfMaps();
Motomu Utsumid95a0da2022-09-03 00:40:30 +0900262 native_init(!sEnableJavaBpfMap /* startSkDestroyListener */);
Ken Chenf5f51332022-01-28 10:08:16 +0800263 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800264 }
265
Motomu Utsumid95a0da2022-09-03 00:40:30 +0900266 public boolean isSkDestroyListenerRunning() {
267 return !sEnableJavaBpfMap;
268 }
269
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000270 /**
271 * Dependencies of BpfNetMaps, for injection in tests.
272 */
273 @VisibleForTesting
274 public static class Dependencies {
275 /**
276 * Get interface index.
277 */
278 public int getIfIndex(final String ifName) {
279 return Os.if_nametoindex(ifName);
280 }
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000281
282 /**
283 * Call synchronize_rcu()
284 */
285 public int synchronizeKernelRCU() {
286 return native_synchronizeKernelRCU();
287 }
Motomu Utsumi166f9662022-09-01 10:35:29 +0900288
289 /**
290 * Build Stats Event for NETWORK_BPF_MAP_INFO atom
291 */
292 public StatsEvent buildStatsEvent(final int cookieTagMapSize, final int uidOwnerMapSize,
293 final int uidPermissionMapSize) {
294 return ConnectivityStatsLog.buildStatsEvent(NETWORK_BPF_MAP_INFO, cookieTagMapSize,
295 uidOwnerMapSize, uidPermissionMapSize);
296 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000297 }
298
markchien49e944c2022-03-01 15:22:20 +0800299 /** Constructor used after T that doesn't need to use netd anymore. */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000300 public BpfNetMaps(final Context context) {
301 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800302
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000303 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800304 }
305
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000306 public BpfNetMaps(final Context context, final INetd netd) {
307 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000308 }
309
310 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000311 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000312 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000313 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000314 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800315 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000316 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800317 }
318
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000319 /**
320 * Get corresponding match from firewall chain.
321 */
322 @VisibleForTesting
323 public long getMatchByFirewallChain(final int chain) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000324 switch (chain) {
325 case FIREWALL_CHAIN_DOZABLE:
326 return DOZABLE_MATCH;
327 case FIREWALL_CHAIN_STANDBY:
328 return STANDBY_MATCH;
329 case FIREWALL_CHAIN_POWERSAVE:
330 return POWERSAVE_MATCH;
331 case FIREWALL_CHAIN_RESTRICTED:
332 return RESTRICTED_MATCH;
333 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
334 return LOW_POWER_STANDBY_MATCH;
335 case FIREWALL_CHAIN_OEM_DENY_1:
336 return OEM_DENY_1_MATCH;
337 case FIREWALL_CHAIN_OEM_DENY_2:
338 return OEM_DENY_2_MATCH;
339 case FIREWALL_CHAIN_OEM_DENY_3:
340 return OEM_DENY_3_MATCH;
341 default:
342 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000343 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000344 }
345
346 /**
347 * Get if the chain is allow list or not.
348 *
349 * ALLOWLIST means the firewall denies all by default, uids must be explicitly allowed
350 * DENYLIST means the firewall allows all by default, uids must be explicitly denyed
351 */
352 @VisibleForTesting
353 public boolean isFirewallAllowList(final int chain) {
354 switch (chain) {
355 case FIREWALL_CHAIN_DOZABLE:
356 case FIREWALL_CHAIN_POWERSAVE:
357 case FIREWALL_CHAIN_RESTRICTED:
358 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
359 return true;
360 case FIREWALL_CHAIN_STANDBY:
361 case FIREWALL_CHAIN_OEM_DENY_1:
362 case FIREWALL_CHAIN_OEM_DENY_2:
363 case FIREWALL_CHAIN_OEM_DENY_3:
364 return false;
365 default:
366 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
367 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000368 }
369
Ken Chenf5f51332022-01-28 10:08:16 +0800370 private void maybeThrow(final int err, final String msg) {
371 if (err != 0) {
372 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
373 }
374 }
375
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000376 private void throwIfPreT(final String msg) {
377 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000378 throw new UnsupportedOperationException(msg);
379 }
380 }
381
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000382 private void removeRule(final int uid, final long match, final String caller) {
383 try {
384 synchronized (sUidOwnerMap) {
385 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new U32(uid));
386
387 if (oldMatch == null) {
388 throw new ServiceSpecificException(ENOENT,
389 "sUidOwnerMap does not have entry for uid: " + uid);
390 }
391
392 final UidOwnerValue newMatch = new UidOwnerValue(
393 (match == IIF_MATCH) ? 0 : oldMatch.iif,
394 oldMatch.rule & ~match
395 );
396
397 if (newMatch.rule == 0) {
398 sUidOwnerMap.deleteEntry(new U32(uid));
399 } else {
400 sUidOwnerMap.updateEntry(new U32(uid), newMatch);
401 }
402 }
403 } catch (ErrnoException e) {
404 throw new ServiceSpecificException(e.errno,
405 caller + " failed to remove rule: " + Os.strerror(e.errno));
406 }
407 }
408
Motomu Utsumi389278e2022-06-28 07:05:05 +0000409 private void addRule(final int uid, final long match, final long iif, final String caller) {
410 if (match != IIF_MATCH && iif != 0) {
411 throw new ServiceSpecificException(EINVAL,
412 "Non-interface match must have zero interface index");
413 }
414
415 try {
416 synchronized (sUidOwnerMap) {
417 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new U32(uid));
418
419 final UidOwnerValue newMatch;
420 if (oldMatch != null) {
421 newMatch = new UidOwnerValue(
422 (match == IIF_MATCH) ? iif : oldMatch.iif,
423 oldMatch.rule | match
424 );
425 } else {
426 newMatch = new UidOwnerValue(
427 iif,
428 match
429 );
430 }
431 sUidOwnerMap.updateEntry(new U32(uid), newMatch);
432 }
433 } catch (ErrnoException e) {
434 throw new ServiceSpecificException(e.errno,
435 caller + " failed to add rule: " + Os.strerror(e.errno));
436 }
437 }
438
439 private void addRule(final int uid, final long match, final String caller) {
440 addRule(uid, match, 0 /* iif */, caller);
441 }
442
Ken Chenf5f51332022-01-28 10:08:16 +0800443 /**
444 * Add naughty app bandwidth rule for specific app
445 *
446 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800447 * @throws ServiceSpecificException in case of failure, with an error code indicating the
448 * cause of the failure.
449 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900450 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000451 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000452
453 if (sEnableJavaBpfMap) {
454 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
455 } else {
456 final int err = native_addNaughtyApp(uid);
457 maybeThrow(err, "Unable to add naughty app");
458 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800459 }
460
Ken Chenf5f51332022-01-28 10:08:16 +0800461 /**
462 * Remove naughty app bandwidth rule for specific app
463 *
464 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800465 * @throws ServiceSpecificException in case of failure, with an error code indicating the
466 * cause of the failure.
467 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900468 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000469 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000470
471 if (sEnableJavaBpfMap) {
472 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
473 } else {
474 final int err = native_removeNaughtyApp(uid);
475 maybeThrow(err, "Unable to remove naughty app");
476 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800477 }
478
Ken Chenf5f51332022-01-28 10:08:16 +0800479 /**
480 * Add nice app bandwidth rule for specific app
481 *
482 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800483 * @throws ServiceSpecificException in case of failure, with an error code indicating the
484 * cause of the failure.
485 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900486 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000487 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000488
489 if (sEnableJavaBpfMap) {
490 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
491 } else {
492 final int err = native_addNiceApp(uid);
493 maybeThrow(err, "Unable to add nice app");
494 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800495 }
496
Ken Chenf5f51332022-01-28 10:08:16 +0800497 /**
498 * Remove nice app bandwidth rule for specific app
499 *
500 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800501 * @throws ServiceSpecificException in case of failure, with an error code indicating the
502 * cause of the failure.
503 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900504 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000505 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000506
507 if (sEnableJavaBpfMap) {
508 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
509 } else {
510 final int err = native_removeNiceApp(uid);
511 maybeThrow(err, "Unable to remove nice app");
512 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800513 }
514
Ken Chenf5f51332022-01-28 10:08:16 +0800515 /**
516 * Set target firewall child chain
517 *
518 * @param childChain target chain to enable
519 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000520 * @throws UnsupportedOperationException if called on pre-T devices.
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 setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000525 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000526
Motomu Utsumie057dd42022-08-03 01:23:49 +0000527 if (sEnableJavaBpfMap) {
528 final long match = getMatchByFirewallChain(childChain);
529 try {
530 synchronized (sUidRulesConfigBpfMapLock) {
531 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
532 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
533 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
534 }
535 } catch (ErrnoException e) {
536 throw new ServiceSpecificException(e.errno,
537 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000538 }
Motomu Utsumie057dd42022-08-03 01:23:49 +0000539 } else {
540 final int err = native_setChildChain(childChain, enable);
541 maybeThrow(err, "Unable to set child chain");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000542 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800543 }
544
545 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000546 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000547 *
548 * @param childChain target chain
549 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
550 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000551 * @throws ServiceSpecificException in case of failure, with an error code indicating the
552 * cause of the failure.
553 */
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000554 public boolean isChainEnabled(final int childChain) {
555 throwIfPreT("isChainEnabled is not available on pre-T devices");
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000556
557 final long match = getMatchByFirewallChain(childChain);
558 try {
559 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000560 return (config.val & match) != 0;
561 } catch (ErrnoException e) {
562 throw new ServiceSpecificException(e.errno,
563 "Unable to get firewall chain status: " + Os.strerror(e.errno));
564 }
565 }
566
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900567 private Set<Integer> asSet(final int[] uids) {
568 final Set<Integer> uidSet = new ArraySet<>();
569 for (final int uid: uids) {
570 uidSet.add(uid);
571 }
572 return uidSet;
573 }
574
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000575 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800576 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000577 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800578 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000579 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800580 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000581 * @throws UnsupportedOperationException if called on pre-T devices.
582 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800583 */
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000584 public void replaceUidChain(final int chain, final int[] uids) {
585 throwIfPreT("replaceUidChain is not available on pre-T devices");
586
Motomu Utsumic7c16852022-08-03 06:51:41 +0000587 if (sEnableJavaBpfMap) {
588 final long match;
589 try {
590 match = getMatchByFirewallChain(chain);
591 } catch (ServiceSpecificException e) {
592 // Throws IllegalArgumentException to keep the behavior of
593 // ConnectivityManager#replaceFirewallChain API
594 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000595 }
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900596 final Set<Integer> uidSet = asSet(uids);
597 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
Motomu Utsumic7c16852022-08-03 06:51:41 +0000598 try {
599 synchronized (sUidOwnerMap) {
600 sUidOwnerMap.forEach((uid, config) -> {
601 // config could be null if there is a concurrent entry deletion.
Motomu Utsumi8e420ea2022-08-24 18:03:30 +0900602 // http://b/220084230. But sUidOwnerMap update must be done while holding a
603 // lock, so this should not happen.
604 if (config == null) {
605 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
606 } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
Motomu Utsumic7c16852022-08-03 06:51:41 +0000607 uidSetToRemoveRule.add((int) uid.val);
608 }
609 });
610
611 for (final int uid : uidSetToRemoveRule) {
612 removeRule(uid, match, "replaceUidChain");
613 }
614 for (final int uid : uids) {
615 addRule(uid, match, "replaceUidChain");
616 }
617 }
618 } catch (ErrnoException | ServiceSpecificException e) {
619 Log.e(TAG, "replaceUidChain failed: " + e);
620 }
621 } else {
622 final int err;
623 switch (chain) {
624 case FIREWALL_CHAIN_DOZABLE:
625 err = native_replaceUidChain("fw_dozable", true /* isAllowList */, uids);
626 break;
627 case FIREWALL_CHAIN_STANDBY:
628 err = native_replaceUidChain("fw_standby", false /* isAllowList */, uids);
629 break;
630 case FIREWALL_CHAIN_POWERSAVE:
631 err = native_replaceUidChain("fw_powersave", true /* isAllowList */, uids);
632 break;
633 case FIREWALL_CHAIN_RESTRICTED:
634 err = native_replaceUidChain("fw_restricted", true /* isAllowList */, uids);
635 break;
636 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
637 err = native_replaceUidChain(
638 "fw_low_power_standby", true /* isAllowList */, uids);
639 break;
640 case FIREWALL_CHAIN_OEM_DENY_1:
641 err = native_replaceUidChain("fw_oem_deny_1", false /* isAllowList */, uids);
642 break;
643 case FIREWALL_CHAIN_OEM_DENY_2:
644 err = native_replaceUidChain("fw_oem_deny_2", false /* isAllowList */, uids);
645 break;
646 case FIREWALL_CHAIN_OEM_DENY_3:
647 err = native_replaceUidChain("fw_oem_deny_3", false /* isAllowList */, uids);
648 break;
649 default:
650 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
651 + chain);
652 }
653 if (err != 0) {
654 Log.e(TAG, "replaceUidChain failed: " + Os.strerror(-err));
655 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800656 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800657 }
658
Ken Chenf5f51332022-01-28 10:08:16 +0800659 /**
660 * Set firewall rule for uid
661 *
662 * @param childChain target chain
663 * @param uid uid to allow/deny
664 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800665 * @throws ServiceSpecificException in case of failure, with an error code indicating the
666 * cause of the failure.
667 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900668 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000669 throwIfPreT("setUidRule is not available on pre-T devices");
670
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000671 if (sEnableJavaBpfMap) {
672 final long match = getMatchByFirewallChain(childChain);
673 final boolean isAllowList = isFirewallAllowList(childChain);
674 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
675 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000676
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000677 if (add) {
678 addRule(uid, match, "setUidRule");
679 } else {
680 removeRule(uid, match, "setUidRule");
681 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000682 } else {
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000683 final int err = native_setUidRule(childChain, uid, firewallRule);
684 maybeThrow(err, "Unable to set uid rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000685 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800686 }
687
688 /**
689 * Add ingress interface filtering rules to a list of UIDs
690 *
691 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
692 * allowed interface and loopback to be sent to the list of UIDs.
693 *
694 * Calling this method on one or more UIDs with an existing filtering rule but a different
695 * interface name will result in the filtering rule being updated to allow the new interface
696 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
697 *
698 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800699 * be received.
700 * @param uids an array of UIDs which the filtering rules will be set
701 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800702 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800703 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800704 */
Ken Chenf5f51332022-01-28 10:08:16 +0800705 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000706 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800707 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800708 return;
709 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000710
711 if (sEnableJavaBpfMap) {
712 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
713 // ifIndex is set to 0.
714 final int ifIndex;
715 if (ifName == null) {
716 ifIndex = 0;
717 } else {
718 ifIndex = mDeps.getIfIndex(ifName);
719 if (ifIndex == 0) {
720 throw new ServiceSpecificException(ENODEV,
721 "Failed to get index of interface " + ifName);
722 }
723 }
724 for (final int uid : uids) {
725 try {
726 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
727 } catch (ServiceSpecificException e) {
728 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
729 }
730 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000731 } else {
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000732 final int err = native_addUidInterfaceRules(ifName, uids);
733 maybeThrow(err, "Unable to add uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000734 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800735 }
736
737 /**
738 * Remove ingress interface filtering rules from a list of UIDs
739 *
740 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
741 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
742 *
743 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800744 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800745 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800746 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800747 */
Ken Chenf5f51332022-01-28 10:08:16 +0800748 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000749 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800750 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800751 return;
752 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000753
754 if (sEnableJavaBpfMap) {
755 for (final int uid : uids) {
756 try {
757 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
758 } catch (ServiceSpecificException e) {
759 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
760 }
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000761 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000762 } else {
763 final int err = native_removeUidInterfaceRules(uids);
764 maybeThrow(err, "Unable to remove uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000765 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800766 }
767
Ken Chenf5f51332022-01-28 10:08:16 +0800768 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000769 * Update lockdown rule for uid
770 *
771 * @param uid target uid to add/remove the rule
772 * @param add {@code true} to add the rule, {@code false} to remove the rule.
773 * @throws ServiceSpecificException in case of failure, with an error code indicating the
774 * cause of the failure.
775 */
776 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000777 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000778
779 if (sEnableJavaBpfMap) {
780 if (add) {
781 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
782 } else {
783 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
784 }
Motomu Utsumi697b2992022-06-30 02:25:29 +0000785 } else {
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000786 final int err = native_updateUidLockdownRule(uid, add);
787 maybeThrow(err, "Unable to update lockdown rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000788 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000789 }
790
791 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800792 * Request netd to change the current active network stats map.
793 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000794 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800795 * @throws ServiceSpecificException in case of failure, with an error code indicating the
796 * cause of the failure.
797 */
markchien49e944c2022-03-01 15:22:20 +0800798 public void swapActiveStatsMap() {
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000799 throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
800
801 if (sEnableJavaBpfMap) {
802 try {
803 synchronized (sCurrentStatsMapConfigLock) {
804 final long config = sConfigurationMap.getValue(
805 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
806 final long newConfig = (config == STATS_SELECT_MAP_A)
807 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
808 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
809 new U32(newConfig));
810 }
811 } catch (ErrnoException e) {
812 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
813 }
814
815 // After changing the config, it's needed to make sure all the current running eBPF
816 // programs are finished and all the CPUs are aware of this config change before the old
817 // map is modified. So special hack is needed here to wait for the kernel to do a
818 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
819 // be available to all cores and the next eBPF programs triggered inside the kernel will
820 // use the new map configuration. So once this function returns it is safe to modify the
821 // old stats map without concerning about race between the kernel and userspace.
822 final int err = mDeps.synchronizeKernelRCU();
823 maybeThrow(err, "synchronizeKernelRCU failed");
824 } else {
825 final int err = native_swapActiveStatsMap();
826 maybeThrow(err, "Unable to swap active stats map");
827 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800828 }
829
Ken Chenf5f51332022-01-28 10:08:16 +0800830 /**
831 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
832 * specified. Or remove all permissions from the uids.
833 *
834 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
835 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
836 * revoke all permissions for the uids.
837 * @param uids uid of users to grant permission
838 * @throws RemoteException when netd has crashed.
839 */
840 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000841 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800842 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800843 return;
844 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000845
846 if (sEnableJavaBpfMap) {
847 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
848 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
849 for (final int uid : uids) {
850 try {
851 sUidPermissionMap.deleteEntry(new U32(uid));
852 } catch (ErrnoException e) {
853 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
854 }
855 }
856 return;
857 }
858
859 for (final int uid : uids) {
860 try {
861 sUidPermissionMap.updateEntry(new U32(uid), new U8((short) permissions));
862 } catch (ErrnoException e) {
863 Log.e(TAG, "Failed to set permission "
864 + permissions + " to uid " + uid + ": " + e);
865 }
866 }
867 } else {
868 native_setPermissionForUids(permissions, uids);
869 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800870 }
871
Motomu Utsumi166f9662022-09-01 10:35:29 +0900872 /** Register callback for statsd to pull atom. */
873 public void setPullAtomCallback(final Context context) {
874 throwIfPreT("setPullAtomCallback is not available on pre-T devices");
875
876 final StatsManager statsManager = context.getSystemService(StatsManager.class);
877 statsManager.setPullAtomCallback(NETWORK_BPF_MAP_INFO, null /* metadata */,
878 BackgroundThread.getExecutor(), this::pullBpfMapInfoAtom);
879 }
880
881 private <K extends Struct, V extends Struct> int getMapSize(IBpfMap<K, V> map)
882 throws ErrnoException {
883 // forEach could restart iteration from the beginning if there is a concurrent entry
884 // deletion. netd and skDestroyListener could delete CookieTagMap entry concurrently.
885 // So using Set to count the number of entry in the map.
886 Set<K> keySet = new ArraySet<>();
887 map.forEach((k, v) -> keySet.add(k));
888 return keySet.size();
889 }
890
891 /** Callback for StatsManager#setPullAtomCallback */
892 @VisibleForTesting
893 public int pullBpfMapInfoAtom(final int atomTag, final List<StatsEvent> data) {
894 if (atomTag != NETWORK_BPF_MAP_INFO) {
895 Log.e(TAG, "Unexpected atom tag: " + atomTag);
896 return StatsManager.PULL_SKIP;
897 }
898
899 try {
900 data.add(mDeps.buildStatsEvent(getMapSize(sCookieTagMap), getMapSize(sUidOwnerMap),
901 getMapSize(sUidPermissionMap)));
902 } catch (ErrnoException e) {
903 Log.e(TAG, "Failed to pull NETWORK_BPF_MAP_INFO atom: " + e);
904 return StatsManager.PULL_SKIP;
905 }
906 return StatsManager.PULL_SUCCESS;
907 }
908
Ken Chene6d511f2022-01-25 11:10:42 +0800909 /**
910 * Dump BPF maps
911 *
912 * @param fd file descriptor to output
913 * @throws IOException when file descriptor is invalid.
914 * @throws ServiceSpecificException when the method is called on an unsupported device.
915 */
916 public void dump(final FileDescriptor fd, boolean verbose)
917 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000918 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +0800919 throw new ServiceSpecificException(
920 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
921 + " devices, use dumpsys netd trafficcontroller instead.");
922 }
923 native_dump(fd, verbose);
924 }
925
Motomu Utsumi3af8f0e2022-09-02 23:42:13 +0900926 private static native void native_init(boolean startSkDestroyListener);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800927 private native int native_addNaughtyApp(int uid);
928 private native int native_removeNaughtyApp(int uid);
929 private native int native_addNiceApp(int uid);
930 private native int native_removeNiceApp(int uid);
Motomu Utsumi114cd9c2022-08-01 02:08:35 +0000931 private native int native_setChildChain(int childChain, boolean enable);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800932 private native int native_replaceUidChain(String name, boolean isAllowlist, int[] uids);
933 private native int native_setUidRule(int childChain, int uid, int firewallRule);
934 private native int native_addUidInterfaceRules(String ifName, int[] uids);
935 private native int native_removeUidInterfaceRules(int[] uids);
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000936 private native int native_updateUidLockdownRule(int uid, boolean add);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800937 private native int native_swapActiveStatsMap();
Wayne Ma2fde98c2022-01-17 18:04:05 +0800938 private native void native_setPermissionForUids(int permissions, int[] uids);
Ken Chene6d511f2022-01-25 11:10:42 +0800939 private native void native_dump(FileDescriptor fd, boolean verbose);
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000940 private static native int native_synchronizeKernelRCU();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800941}