blob: 758c013418c686cc441f3cc1c2215b23e367ee0d [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 Utsumidf8d2992022-09-01 17:08:27 +0900297
298 /**
299 * Call native_dump
300 */
301 public void nativeDump(final FileDescriptor fd, final boolean verbose) {
302 native_dump(fd, verbose);
303 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000304 }
305
markchien49e944c2022-03-01 15:22:20 +0800306 /** Constructor used after T that doesn't need to use netd anymore. */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000307 public BpfNetMaps(final Context context) {
308 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800309
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000310 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800311 }
312
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000313 public BpfNetMaps(final Context context, final INetd netd) {
314 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000315 }
316
317 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000318 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000319 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000320 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000321 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800322 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000323 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800324 }
325
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000326 /**
327 * Get corresponding match from firewall chain.
328 */
329 @VisibleForTesting
330 public long getMatchByFirewallChain(final int chain) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000331 switch (chain) {
332 case FIREWALL_CHAIN_DOZABLE:
333 return DOZABLE_MATCH;
334 case FIREWALL_CHAIN_STANDBY:
335 return STANDBY_MATCH;
336 case FIREWALL_CHAIN_POWERSAVE:
337 return POWERSAVE_MATCH;
338 case FIREWALL_CHAIN_RESTRICTED:
339 return RESTRICTED_MATCH;
340 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
341 return LOW_POWER_STANDBY_MATCH;
342 case FIREWALL_CHAIN_OEM_DENY_1:
343 return OEM_DENY_1_MATCH;
344 case FIREWALL_CHAIN_OEM_DENY_2:
345 return OEM_DENY_2_MATCH;
346 case FIREWALL_CHAIN_OEM_DENY_3:
347 return OEM_DENY_3_MATCH;
348 default:
349 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000350 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000351 }
352
353 /**
354 * Get if the chain is allow list or not.
355 *
356 * ALLOWLIST means the firewall denies all by default, uids must be explicitly allowed
357 * DENYLIST means the firewall allows all by default, uids must be explicitly denyed
358 */
359 @VisibleForTesting
360 public boolean isFirewallAllowList(final int chain) {
361 switch (chain) {
362 case FIREWALL_CHAIN_DOZABLE:
363 case FIREWALL_CHAIN_POWERSAVE:
364 case FIREWALL_CHAIN_RESTRICTED:
365 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
366 return true;
367 case FIREWALL_CHAIN_STANDBY:
368 case FIREWALL_CHAIN_OEM_DENY_1:
369 case FIREWALL_CHAIN_OEM_DENY_2:
370 case FIREWALL_CHAIN_OEM_DENY_3:
371 return false;
372 default:
373 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
374 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000375 }
376
Ken Chenf5f51332022-01-28 10:08:16 +0800377 private void maybeThrow(final int err, final String msg) {
378 if (err != 0) {
379 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
380 }
381 }
382
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000383 private void throwIfPreT(final String msg) {
384 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000385 throw new UnsupportedOperationException(msg);
386 }
387 }
388
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000389 private void removeRule(final int uid, final long match, final String caller) {
390 try {
391 synchronized (sUidOwnerMap) {
392 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new U32(uid));
393
394 if (oldMatch == null) {
395 throw new ServiceSpecificException(ENOENT,
396 "sUidOwnerMap does not have entry for uid: " + uid);
397 }
398
399 final UidOwnerValue newMatch = new UidOwnerValue(
400 (match == IIF_MATCH) ? 0 : oldMatch.iif,
401 oldMatch.rule & ~match
402 );
403
404 if (newMatch.rule == 0) {
405 sUidOwnerMap.deleteEntry(new U32(uid));
406 } else {
407 sUidOwnerMap.updateEntry(new U32(uid), newMatch);
408 }
409 }
410 } catch (ErrnoException e) {
411 throw new ServiceSpecificException(e.errno,
412 caller + " failed to remove rule: " + Os.strerror(e.errno));
413 }
414 }
415
Motomu Utsumi389278e2022-06-28 07:05:05 +0000416 private void addRule(final int uid, final long match, final long iif, final String caller) {
417 if (match != IIF_MATCH && iif != 0) {
418 throw new ServiceSpecificException(EINVAL,
419 "Non-interface match must have zero interface index");
420 }
421
422 try {
423 synchronized (sUidOwnerMap) {
424 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new U32(uid));
425
426 final UidOwnerValue newMatch;
427 if (oldMatch != null) {
428 newMatch = new UidOwnerValue(
429 (match == IIF_MATCH) ? iif : oldMatch.iif,
430 oldMatch.rule | match
431 );
432 } else {
433 newMatch = new UidOwnerValue(
434 iif,
435 match
436 );
437 }
438 sUidOwnerMap.updateEntry(new U32(uid), newMatch);
439 }
440 } catch (ErrnoException e) {
441 throw new ServiceSpecificException(e.errno,
442 caller + " failed to add rule: " + Os.strerror(e.errno));
443 }
444 }
445
446 private void addRule(final int uid, final long match, final String caller) {
447 addRule(uid, match, 0 /* iif */, caller);
448 }
449
Ken Chenf5f51332022-01-28 10:08:16 +0800450 /**
451 * Add naughty app bandwidth rule for specific app
452 *
453 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800454 * @throws ServiceSpecificException in case of failure, with an error code indicating the
455 * cause of the failure.
456 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900457 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000458 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000459
460 if (sEnableJavaBpfMap) {
461 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
462 } else {
463 final int err = native_addNaughtyApp(uid);
464 maybeThrow(err, "Unable to add naughty app");
465 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800466 }
467
Ken Chenf5f51332022-01-28 10:08:16 +0800468 /**
469 * Remove naughty app bandwidth rule for specific app
470 *
471 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800472 * @throws ServiceSpecificException in case of failure, with an error code indicating the
473 * cause of the failure.
474 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900475 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000476 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000477
478 if (sEnableJavaBpfMap) {
479 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
480 } else {
481 final int err = native_removeNaughtyApp(uid);
482 maybeThrow(err, "Unable to remove naughty app");
483 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800484 }
485
Ken Chenf5f51332022-01-28 10:08:16 +0800486 /**
487 * Add nice app bandwidth rule for specific app
488 *
489 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800490 * @throws ServiceSpecificException in case of failure, with an error code indicating the
491 * cause of the failure.
492 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900493 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000494 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000495
496 if (sEnableJavaBpfMap) {
497 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
498 } else {
499 final int err = native_addNiceApp(uid);
500 maybeThrow(err, "Unable to add nice app");
501 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800502 }
503
Ken Chenf5f51332022-01-28 10:08:16 +0800504 /**
505 * Remove nice app bandwidth rule for specific app
506 *
507 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800508 * @throws ServiceSpecificException in case of failure, with an error code indicating the
509 * cause of the failure.
510 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900511 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000512 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000513
514 if (sEnableJavaBpfMap) {
515 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
516 } else {
517 final int err = native_removeNiceApp(uid);
518 maybeThrow(err, "Unable to remove nice app");
519 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800520 }
521
Ken Chenf5f51332022-01-28 10:08:16 +0800522 /**
523 * Set target firewall child chain
524 *
525 * @param childChain target chain to enable
526 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000527 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800528 * @throws ServiceSpecificException in case of failure, with an error code indicating the
529 * cause of the failure.
530 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900531 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000532 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000533
Motomu Utsumie057dd42022-08-03 01:23:49 +0000534 if (sEnableJavaBpfMap) {
535 final long match = getMatchByFirewallChain(childChain);
536 try {
537 synchronized (sUidRulesConfigBpfMapLock) {
538 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
539 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
540 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
541 }
542 } catch (ErrnoException e) {
543 throw new ServiceSpecificException(e.errno,
544 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000545 }
Motomu Utsumie057dd42022-08-03 01:23:49 +0000546 } else {
547 final int err = native_setChildChain(childChain, enable);
548 maybeThrow(err, "Unable to set child chain");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000549 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800550 }
551
552 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000553 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000554 *
555 * @param childChain target chain
556 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
557 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000558 * @throws ServiceSpecificException in case of failure, with an error code indicating the
559 * cause of the failure.
560 */
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000561 public boolean isChainEnabled(final int childChain) {
562 throwIfPreT("isChainEnabled is not available on pre-T devices");
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000563
564 final long match = getMatchByFirewallChain(childChain);
565 try {
566 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000567 return (config.val & match) != 0;
568 } catch (ErrnoException e) {
569 throw new ServiceSpecificException(e.errno,
570 "Unable to get firewall chain status: " + Os.strerror(e.errno));
571 }
572 }
573
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900574 private Set<Integer> asSet(final int[] uids) {
575 final Set<Integer> uidSet = new ArraySet<>();
576 for (final int uid: uids) {
577 uidSet.add(uid);
578 }
579 return uidSet;
580 }
581
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000582 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800583 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000584 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800585 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000586 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800587 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000588 * @throws UnsupportedOperationException if called on pre-T devices.
589 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800590 */
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000591 public void replaceUidChain(final int chain, final int[] uids) {
592 throwIfPreT("replaceUidChain is not available on pre-T devices");
593
Motomu Utsumic7c16852022-08-03 06:51:41 +0000594 if (sEnableJavaBpfMap) {
595 final long match;
596 try {
597 match = getMatchByFirewallChain(chain);
598 } catch (ServiceSpecificException e) {
599 // Throws IllegalArgumentException to keep the behavior of
600 // ConnectivityManager#replaceFirewallChain API
601 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000602 }
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900603 final Set<Integer> uidSet = asSet(uids);
604 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
Motomu Utsumic7c16852022-08-03 06:51:41 +0000605 try {
606 synchronized (sUidOwnerMap) {
607 sUidOwnerMap.forEach((uid, config) -> {
608 // config could be null if there is a concurrent entry deletion.
Motomu Utsumi8e420ea2022-08-24 18:03:30 +0900609 // http://b/220084230. But sUidOwnerMap update must be done while holding a
610 // lock, so this should not happen.
611 if (config == null) {
612 Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
613 } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
Motomu Utsumic7c16852022-08-03 06:51:41 +0000614 uidSetToRemoveRule.add((int) uid.val);
615 }
616 });
617
618 for (final int uid : uidSetToRemoveRule) {
619 removeRule(uid, match, "replaceUidChain");
620 }
621 for (final int uid : uids) {
622 addRule(uid, match, "replaceUidChain");
623 }
624 }
625 } catch (ErrnoException | ServiceSpecificException e) {
626 Log.e(TAG, "replaceUidChain failed: " + e);
627 }
628 } else {
629 final int err;
630 switch (chain) {
631 case FIREWALL_CHAIN_DOZABLE:
632 err = native_replaceUidChain("fw_dozable", true /* isAllowList */, uids);
633 break;
634 case FIREWALL_CHAIN_STANDBY:
635 err = native_replaceUidChain("fw_standby", false /* isAllowList */, uids);
636 break;
637 case FIREWALL_CHAIN_POWERSAVE:
638 err = native_replaceUidChain("fw_powersave", true /* isAllowList */, uids);
639 break;
640 case FIREWALL_CHAIN_RESTRICTED:
641 err = native_replaceUidChain("fw_restricted", true /* isAllowList */, uids);
642 break;
643 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
644 err = native_replaceUidChain(
645 "fw_low_power_standby", true /* isAllowList */, uids);
646 break;
647 case FIREWALL_CHAIN_OEM_DENY_1:
648 err = native_replaceUidChain("fw_oem_deny_1", false /* isAllowList */, uids);
649 break;
650 case FIREWALL_CHAIN_OEM_DENY_2:
651 err = native_replaceUidChain("fw_oem_deny_2", false /* isAllowList */, uids);
652 break;
653 case FIREWALL_CHAIN_OEM_DENY_3:
654 err = native_replaceUidChain("fw_oem_deny_3", false /* isAllowList */, uids);
655 break;
656 default:
657 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
658 + chain);
659 }
660 if (err != 0) {
661 Log.e(TAG, "replaceUidChain failed: " + Os.strerror(-err));
662 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800663 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800664 }
665
Ken Chenf5f51332022-01-28 10:08:16 +0800666 /**
667 * Set firewall rule for uid
668 *
669 * @param childChain target chain
670 * @param uid uid to allow/deny
671 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800672 * @throws ServiceSpecificException in case of failure, with an error code indicating the
673 * cause of the failure.
674 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900675 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000676 throwIfPreT("setUidRule is not available on pre-T devices");
677
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000678 if (sEnableJavaBpfMap) {
679 final long match = getMatchByFirewallChain(childChain);
680 final boolean isAllowList = isFirewallAllowList(childChain);
681 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
682 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000683
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000684 if (add) {
685 addRule(uid, match, "setUidRule");
686 } else {
687 removeRule(uid, match, "setUidRule");
688 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000689 } else {
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000690 final int err = native_setUidRule(childChain, uid, firewallRule);
691 maybeThrow(err, "Unable to set uid rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000692 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800693 }
694
695 /**
696 * Add ingress interface filtering rules to a list of UIDs
697 *
698 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
699 * allowed interface and loopback to be sent to the list of UIDs.
700 *
701 * Calling this method on one or more UIDs with an existing filtering rule but a different
702 * interface name will result in the filtering rule being updated to allow the new interface
703 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
704 *
705 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800706 * be received.
707 * @param uids an array of UIDs which the filtering rules will be set
708 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800709 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800710 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800711 */
Ken Chenf5f51332022-01-28 10:08:16 +0800712 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000713 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800714 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800715 return;
716 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000717
718 if (sEnableJavaBpfMap) {
719 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
720 // ifIndex is set to 0.
721 final int ifIndex;
722 if (ifName == null) {
723 ifIndex = 0;
724 } else {
725 ifIndex = mDeps.getIfIndex(ifName);
726 if (ifIndex == 0) {
727 throw new ServiceSpecificException(ENODEV,
728 "Failed to get index of interface " + ifName);
729 }
730 }
731 for (final int uid : uids) {
732 try {
733 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
734 } catch (ServiceSpecificException e) {
735 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
736 }
737 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000738 } else {
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000739 final int err = native_addUidInterfaceRules(ifName, uids);
740 maybeThrow(err, "Unable to add uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000741 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800742 }
743
744 /**
745 * Remove ingress interface filtering rules from a list of UIDs
746 *
747 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
748 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
749 *
750 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800751 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800752 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800753 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800754 */
Ken Chenf5f51332022-01-28 10:08:16 +0800755 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000756 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800757 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800758 return;
759 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000760
761 if (sEnableJavaBpfMap) {
762 for (final int uid : uids) {
763 try {
764 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
765 } catch (ServiceSpecificException e) {
766 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
767 }
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000768 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000769 } else {
770 final int err = native_removeUidInterfaceRules(uids);
771 maybeThrow(err, "Unable to remove uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000772 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800773 }
774
Ken Chenf5f51332022-01-28 10:08:16 +0800775 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000776 * Update lockdown rule for uid
777 *
778 * @param uid target uid to add/remove the rule
779 * @param add {@code true} to add the rule, {@code false} to remove the rule.
780 * @throws ServiceSpecificException in case of failure, with an error code indicating the
781 * cause of the failure.
782 */
783 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000784 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000785
786 if (sEnableJavaBpfMap) {
787 if (add) {
788 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
789 } else {
790 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
791 }
Motomu Utsumi697b2992022-06-30 02:25:29 +0000792 } else {
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000793 final int err = native_updateUidLockdownRule(uid, add);
794 maybeThrow(err, "Unable to update lockdown rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000795 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000796 }
797
798 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800799 * Request netd to change the current active network stats map.
800 *
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000801 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800802 * @throws ServiceSpecificException in case of failure, with an error code indicating the
803 * cause of the failure.
804 */
markchien49e944c2022-03-01 15:22:20 +0800805 public void swapActiveStatsMap() {
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000806 throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
807
808 if (sEnableJavaBpfMap) {
809 try {
810 synchronized (sCurrentStatsMapConfigLock) {
811 final long config = sConfigurationMap.getValue(
812 CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
813 final long newConfig = (config == STATS_SELECT_MAP_A)
814 ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
815 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
816 new U32(newConfig));
817 }
818 } catch (ErrnoException e) {
819 throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
820 }
821
822 // After changing the config, it's needed to make sure all the current running eBPF
823 // programs are finished and all the CPUs are aware of this config change before the old
824 // map is modified. So special hack is needed here to wait for the kernel to do a
825 // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
826 // be available to all cores and the next eBPF programs triggered inside the kernel will
827 // use the new map configuration. So once this function returns it is safe to modify the
828 // old stats map without concerning about race between the kernel and userspace.
829 final int err = mDeps.synchronizeKernelRCU();
830 maybeThrow(err, "synchronizeKernelRCU failed");
831 } else {
832 final int err = native_swapActiveStatsMap();
833 maybeThrow(err, "Unable to swap active stats map");
834 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800835 }
836
Ken Chenf5f51332022-01-28 10:08:16 +0800837 /**
838 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
839 * specified. Or remove all permissions from the uids.
840 *
841 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
842 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
843 * revoke all permissions for the uids.
844 * @param uids uid of users to grant permission
845 * @throws RemoteException when netd has crashed.
846 */
847 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000848 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800849 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800850 return;
851 }
Motomu Utsumi65271202022-07-05 08:21:41 +0000852
853 if (sEnableJavaBpfMap) {
854 // Remove the entry if package is uninstalled or uid has only INTERNET permission.
855 if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
856 for (final int uid : uids) {
857 try {
858 sUidPermissionMap.deleteEntry(new U32(uid));
859 } catch (ErrnoException e) {
860 Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
861 }
862 }
863 return;
864 }
865
866 for (final int uid : uids) {
867 try {
868 sUidPermissionMap.updateEntry(new U32(uid), new U8((short) permissions));
869 } catch (ErrnoException e) {
870 Log.e(TAG, "Failed to set permission "
871 + permissions + " to uid " + uid + ": " + e);
872 }
873 }
874 } else {
875 native_setPermissionForUids(permissions, uids);
876 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800877 }
878
Motomu Utsumi166f9662022-09-01 10:35:29 +0900879 /** Register callback for statsd to pull atom. */
880 public void setPullAtomCallback(final Context context) {
881 throwIfPreT("setPullAtomCallback is not available on pre-T devices");
882
883 final StatsManager statsManager = context.getSystemService(StatsManager.class);
884 statsManager.setPullAtomCallback(NETWORK_BPF_MAP_INFO, null /* metadata */,
885 BackgroundThread.getExecutor(), this::pullBpfMapInfoAtom);
886 }
887
888 private <K extends Struct, V extends Struct> int getMapSize(IBpfMap<K, V> map)
889 throws ErrnoException {
890 // forEach could restart iteration from the beginning if there is a concurrent entry
891 // deletion. netd and skDestroyListener could delete CookieTagMap entry concurrently.
892 // So using Set to count the number of entry in the map.
893 Set<K> keySet = new ArraySet<>();
894 map.forEach((k, v) -> keySet.add(k));
895 return keySet.size();
896 }
897
898 /** Callback for StatsManager#setPullAtomCallback */
899 @VisibleForTesting
900 public int pullBpfMapInfoAtom(final int atomTag, final List<StatsEvent> data) {
901 if (atomTag != NETWORK_BPF_MAP_INFO) {
902 Log.e(TAG, "Unexpected atom tag: " + atomTag);
903 return StatsManager.PULL_SKIP;
904 }
905
906 try {
907 data.add(mDeps.buildStatsEvent(getMapSize(sCookieTagMap), getMapSize(sUidOwnerMap),
908 getMapSize(sUidPermissionMap)));
909 } catch (ErrnoException e) {
910 Log.e(TAG, "Failed to pull NETWORK_BPF_MAP_INFO atom: " + e);
911 return StatsManager.PULL_SKIP;
912 }
913 return StatsManager.PULL_SUCCESS;
914 }
915
Ken Chene6d511f2022-01-25 11:10:42 +0800916 /**
917 * Dump BPF maps
918 *
919 * @param fd file descriptor to output
920 * @throws IOException when file descriptor is invalid.
921 * @throws ServiceSpecificException when the method is called on an unsupported device.
922 */
923 public void dump(final FileDescriptor fd, boolean verbose)
924 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000925 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +0800926 throw new ServiceSpecificException(
927 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
928 + " devices, use dumpsys netd trafficcontroller instead.");
929 }
Motomu Utsumidf8d2992022-09-01 17:08:27 +0900930 mDeps.nativeDump(fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +0800931 }
932
Motomu Utsumi3af8f0e2022-09-02 23:42:13 +0900933 private static native void native_init(boolean startSkDestroyListener);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800934 private native int native_addNaughtyApp(int uid);
935 private native int native_removeNaughtyApp(int uid);
936 private native int native_addNiceApp(int uid);
937 private native int native_removeNiceApp(int uid);
Motomu Utsumi114cd9c2022-08-01 02:08:35 +0000938 private native int native_setChildChain(int childChain, boolean enable);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800939 private native int native_replaceUidChain(String name, boolean isAllowlist, int[] uids);
940 private native int native_setUidRule(int childChain, int uid, int firewallRule);
941 private native int native_addUidInterfaceRules(String ifName, int[] uids);
942 private native int native_removeUidInterfaceRules(int[] uids);
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000943 private native int native_updateUidLockdownRule(int uid, boolean add);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800944 private native int native_swapActiveStatsMap();
Wayne Ma2fde98c2022-01-17 18:04:05 +0800945 private native void native_setPermissionForUids(int permissions, int[] uids);
Motomu Utsumidf8d2992022-09-01 17:08:27 +0900946 private static native void native_dump(FileDescriptor fd, boolean verbose);
Motomu Utsumi7abeaa42022-07-20 07:54:18 +0000947 private static native int native_synchronizeKernelRCU();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800948}