blob: 9c14f79ea8c12802db46304749f283191ed209ec [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 Utsumi18b287d2022-06-19 10:45:30 +000029import static android.system.OsConstants.EINVAL;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000030import static android.system.OsConstants.ENODEV;
Motomu Utsumi60ed3be2022-06-24 10:38:57 +000031import static android.system.OsConstants.ENOENT;
Ken Chene6d511f2022-01-25 11:10:42 +080032import static android.system.OsConstants.EOPNOTSUPP;
33
Motomu Utsumif688eeb2022-07-22 03:47:35 +000034import android.content.Context;
Wayne Ma2fde98c2022-01-17 18:04:05 +080035import android.net.INetd;
36import android.os.RemoteException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080037import android.os.ServiceSpecificException;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000038import android.provider.DeviceConfig;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000039import android.system.ErrnoException;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080040import android.system.Os;
Motomu Utsumi1a477b02022-08-23 15:14:56 +090041import android.util.ArraySet;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080042import android.util.Log;
43
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000044import com.android.internal.annotations.VisibleForTesting;
Ken Chenf5f51332022-01-28 10:08:16 +080045import com.android.modules.utils.build.SdkLevel;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000046import com.android.net.module.util.BpfMap;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000047import com.android.net.module.util.DeviceConfigUtils;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000048import com.android.net.module.util.Struct.U32;
Ken Chenf5f51332022-01-28 10:08:16 +080049
Ken Chene6d511f2022-01-25 11:10:42 +080050import java.io.FileDescriptor;
51import java.io.IOException;
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000052import java.util.Set;
Ken Chene6d511f2022-01-25 11:10:42 +080053
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080054/**
55 * BpfNetMaps is responsible for providing traffic controller relevant functionality.
56 *
57 * {@hide}
58 */
59public class BpfNetMaps {
Motomu Utsumi305975f2022-06-27 09:24:32 +000060 private static final boolean PRE_T = !SdkLevel.isAtLeastT();
61 static {
62 if (!PRE_T) {
63 System.loadLibrary("service-connectivity");
64 }
65 }
66
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080067 private static final String TAG = "BpfNetMaps";
Wayne Ma2fde98c2022-01-17 18:04:05 +080068 private final INetd mNetd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000069 private final Dependencies mDeps;
Ken Chenf5f51332022-01-28 10:08:16 +080070 // Use legacy netd for releases before T.
Ken Chenf5f51332022-01-28 10:08:16 +080071 private static boolean sInitialized = false;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080072
Motomu Utsumif688eeb2022-07-22 03:47:35 +000073 private static Boolean sEnableJavaBpfMap = null;
74 private static final String BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP =
75 "bpf_net_maps_enable_java_bpf_map";
76
Motomu Utsumi18b287d2022-06-19 10:45:30 +000077 // Lock for sConfigurationMap entry for UID_RULES_CONFIGURATION_KEY.
78 // This entry is not accessed by others.
79 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
80 private static final Object sUidRulesConfigBpfMapLock = new Object();
81
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000082 private static final String CONFIGURATION_MAP_PATH =
83 "/sys/fs/bpf/netd_shared/map_netd_configuration_map";
Motomu Utsumi5a68a212022-06-24 10:14:31 +000084 private static final String UID_OWNER_MAP_PATH =
85 "/sys/fs/bpf/netd_shared/map_netd_uid_owner_map";
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000086 private static final U32 UID_RULES_CONFIGURATION_KEY = new U32(0);
Motomu Utsumiba2fa152022-07-25 01:57:23 +000087 private static final U32 CURRENT_STATS_MAP_CONFIGURATION_KEY = new U32(1);
88 private static final long UID_RULES_DEFAULT_CONFIGURATION = 0;
89 private static final long STATS_SELECT_MAP_A = 0;
90 private static final long STATS_SELECT_MAP_B = 1;
91
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000092 private static BpfMap<U32, U32> sConfigurationMap = null;
Motomu Utsumi5a68a212022-06-24 10:14:31 +000093 // BpfMap for UID_OWNER_MAP_PATH. This map is not accessed by others.
94 private static BpfMap<U32, UidOwnerValue> sUidOwnerMap = null;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000095
96 // LINT.IfChange(match_type)
Motomu Utsumi60ed3be2022-06-24 10:38:57 +000097 @VisibleForTesting public static final long NO_MATCH = 0;
98 @VisibleForTesting public static final long HAPPY_BOX_MATCH = (1 << 0);
99 @VisibleForTesting public static final long PENALTY_BOX_MATCH = (1 << 1);
100 @VisibleForTesting public static final long DOZABLE_MATCH = (1 << 2);
101 @VisibleForTesting public static final long STANDBY_MATCH = (1 << 3);
102 @VisibleForTesting public static final long POWERSAVE_MATCH = (1 << 4);
103 @VisibleForTesting public static final long RESTRICTED_MATCH = (1 << 5);
104 @VisibleForTesting public static final long LOW_POWER_STANDBY_MATCH = (1 << 6);
105 @VisibleForTesting public static final long IIF_MATCH = (1 << 7);
106 @VisibleForTesting public static final long LOCKDOWN_VPN_MATCH = (1 << 8);
107 @VisibleForTesting public static final long OEM_DENY_1_MATCH = (1 << 9);
108 @VisibleForTesting public static final long OEM_DENY_2_MATCH = (1 << 10);
109 @VisibleForTesting public static final long OEM_DENY_3_MATCH = (1 << 11);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000110 // LINT.ThenChange(packages/modules/Connectivity/bpf_progs/bpf_shared.h)
111
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000112 /**
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000113 * Set sEnableJavaBpfMap for test.
114 */
115 @VisibleForTesting
116 public static void setEnableJavaBpfMapForTest(boolean enable) {
117 sEnableJavaBpfMap = enable;
118 }
119
120 /**
Motomu Utsumi305975f2022-06-27 09:24:32 +0000121 * Set configurationMap for test.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000122 */
123 @VisibleForTesting
Motomu Utsumi305975f2022-06-27 09:24:32 +0000124 public static void setConfigurationMapForTest(BpfMap<U32, U32> configurationMap) {
125 sConfigurationMap = configurationMap;
126 }
127
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000128 /**
129 * Set uidOwnerMap for test.
130 */
131 @VisibleForTesting
132 public static void setUidOwnerMapForTest(BpfMap<U32, UidOwnerValue> uidOwnerMap) {
133 sUidOwnerMap = uidOwnerMap;
134 }
135
Motomu Utsumi305975f2022-06-27 09:24:32 +0000136 private static BpfMap<U32, U32> getConfigurationMap() {
137 try {
138 return new BpfMap<>(
139 CONFIGURATION_MAP_PATH, BpfMap.BPF_F_RDWR, U32.class, U32.class);
140 } catch (ErrnoException e) {
141 throw new IllegalStateException("Cannot open netd configuration map", e);
142 }
143 }
144
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000145 private static BpfMap<U32, UidOwnerValue> getUidOwnerMap() {
146 try {
147 return new BpfMap<>(
148 UID_OWNER_MAP_PATH, BpfMap.BPF_F_RDWR, U32.class, UidOwnerValue.class);
149 } catch (ErrnoException e) {
150 throw new IllegalStateException("Cannot open uid owner map", e);
151 }
152 }
153
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000154 private static void initBpfMaps() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000155 if (sConfigurationMap == null) {
156 sConfigurationMap = getConfigurationMap();
157 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000158 try {
159 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY,
160 new U32(UID_RULES_DEFAULT_CONFIGURATION));
161 } catch (ErrnoException e) {
162 throw new IllegalStateException("Failed to initialize uid rules configuration", e);
163 }
164 try {
165 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
166 new U32(STATS_SELECT_MAP_A));
167 } catch (ErrnoException e) {
168 throw new IllegalStateException("Failed to initialize current stats configuration", e);
169 }
170
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000171 if (sUidOwnerMap == null) {
172 sUidOwnerMap = getUidOwnerMap();
173 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000174 try {
175 sUidOwnerMap.clear();
176 } catch (ErrnoException e) {
177 throw new IllegalStateException("Failed to initialize uid owner map", e);
178 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000179 }
180
Ken Chenf5f51332022-01-28 10:08:16 +0800181 /**
182 * Initializes the class if it is not already initialized. This method will open maps but not
183 * cause any other effects. This method may be called multiple times on any thread.
184 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000185 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800186 if (sInitialized) return;
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000187 if (sEnableJavaBpfMap == null) {
188 sEnableJavaBpfMap = DeviceConfigUtils.isFeatureEnabled(context,
189 DeviceConfig.NAMESPACE_TETHERING, BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP,
190 SdkLevel.isAtLeastU() /* defaultValue */);
191 }
192 Log.d(TAG, "BpfNetMaps is initialized with sEnableJavaBpfMap=" + sEnableJavaBpfMap);
193
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000194 initBpfMaps();
Motomu Utsumi305975f2022-06-27 09:24:32 +0000195 native_init();
Ken Chenf5f51332022-01-28 10:08:16 +0800196 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800197 }
198
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000199 /**
200 * Dependencies of BpfNetMaps, for injection in tests.
201 */
202 @VisibleForTesting
203 public static class Dependencies {
204 /**
205 * Get interface index.
206 */
207 public int getIfIndex(final String ifName) {
208 return Os.if_nametoindex(ifName);
209 }
210 }
211
markchien49e944c2022-03-01 15:22:20 +0800212 /** Constructor used after T that doesn't need to use netd anymore. */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000213 public BpfNetMaps(final Context context) {
214 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800215
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000216 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800217 }
218
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000219 public BpfNetMaps(final Context context, final INetd netd) {
220 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000221 }
222
223 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000224 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000225 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000226 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000227 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800228 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000229 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800230 }
231
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000232 /**
233 * Get corresponding match from firewall chain.
234 */
235 @VisibleForTesting
236 public long getMatchByFirewallChain(final int chain) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000237 switch (chain) {
238 case FIREWALL_CHAIN_DOZABLE:
239 return DOZABLE_MATCH;
240 case FIREWALL_CHAIN_STANDBY:
241 return STANDBY_MATCH;
242 case FIREWALL_CHAIN_POWERSAVE:
243 return POWERSAVE_MATCH;
244 case FIREWALL_CHAIN_RESTRICTED:
245 return RESTRICTED_MATCH;
246 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
247 return LOW_POWER_STANDBY_MATCH;
248 case FIREWALL_CHAIN_OEM_DENY_1:
249 return OEM_DENY_1_MATCH;
250 case FIREWALL_CHAIN_OEM_DENY_2:
251 return OEM_DENY_2_MATCH;
252 case FIREWALL_CHAIN_OEM_DENY_3:
253 return OEM_DENY_3_MATCH;
254 default:
255 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000256 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000257 }
258
259 /**
260 * Get if the chain is allow list or not.
261 *
262 * ALLOWLIST means the firewall denies all by default, uids must be explicitly allowed
263 * DENYLIST means the firewall allows all by default, uids must be explicitly denyed
264 */
265 @VisibleForTesting
266 public boolean isFirewallAllowList(final int chain) {
267 switch (chain) {
268 case FIREWALL_CHAIN_DOZABLE:
269 case FIREWALL_CHAIN_POWERSAVE:
270 case FIREWALL_CHAIN_RESTRICTED:
271 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
272 return true;
273 case FIREWALL_CHAIN_STANDBY:
274 case FIREWALL_CHAIN_OEM_DENY_1:
275 case FIREWALL_CHAIN_OEM_DENY_2:
276 case FIREWALL_CHAIN_OEM_DENY_3:
277 return false;
278 default:
279 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
280 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000281 }
282
Ken Chenf5f51332022-01-28 10:08:16 +0800283 private void maybeThrow(final int err, final String msg) {
284 if (err != 0) {
285 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
286 }
287 }
288
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000289 private void throwIfPreT(final String msg) {
290 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000291 throw new UnsupportedOperationException(msg);
292 }
293 }
294
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000295 private void removeRule(final int uid, final long match, final String caller) {
296 try {
297 synchronized (sUidOwnerMap) {
298 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new U32(uid));
299
300 if (oldMatch == null) {
301 throw new ServiceSpecificException(ENOENT,
302 "sUidOwnerMap does not have entry for uid: " + uid);
303 }
304
305 final UidOwnerValue newMatch = new UidOwnerValue(
306 (match == IIF_MATCH) ? 0 : oldMatch.iif,
307 oldMatch.rule & ~match
308 );
309
310 if (newMatch.rule == 0) {
311 sUidOwnerMap.deleteEntry(new U32(uid));
312 } else {
313 sUidOwnerMap.updateEntry(new U32(uid), newMatch);
314 }
315 }
316 } catch (ErrnoException e) {
317 throw new ServiceSpecificException(e.errno,
318 caller + " failed to remove rule: " + Os.strerror(e.errno));
319 }
320 }
321
Motomu Utsumi389278e2022-06-28 07:05:05 +0000322 private void addRule(final int uid, final long match, final long iif, final String caller) {
323 if (match != IIF_MATCH && iif != 0) {
324 throw new ServiceSpecificException(EINVAL,
325 "Non-interface match must have zero interface index");
326 }
327
328 try {
329 synchronized (sUidOwnerMap) {
330 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new U32(uid));
331
332 final UidOwnerValue newMatch;
333 if (oldMatch != null) {
334 newMatch = new UidOwnerValue(
335 (match == IIF_MATCH) ? iif : oldMatch.iif,
336 oldMatch.rule | match
337 );
338 } else {
339 newMatch = new UidOwnerValue(
340 iif,
341 match
342 );
343 }
344 sUidOwnerMap.updateEntry(new U32(uid), newMatch);
345 }
346 } catch (ErrnoException e) {
347 throw new ServiceSpecificException(e.errno,
348 caller + " failed to add rule: " + Os.strerror(e.errno));
349 }
350 }
351
352 private void addRule(final int uid, final long match, final String caller) {
353 addRule(uid, match, 0 /* iif */, caller);
354 }
355
Ken Chenf5f51332022-01-28 10:08:16 +0800356 /**
357 * Add naughty app bandwidth rule for specific app
358 *
359 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800360 * @throws ServiceSpecificException in case of failure, with an error code indicating the
361 * cause of the failure.
362 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900363 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000364 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000365
366 if (sEnableJavaBpfMap) {
367 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
368 } else {
369 final int err = native_addNaughtyApp(uid);
370 maybeThrow(err, "Unable to add naughty app");
371 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800372 }
373
Ken Chenf5f51332022-01-28 10:08:16 +0800374 /**
375 * Remove naughty app bandwidth rule for specific app
376 *
377 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800378 * @throws ServiceSpecificException in case of failure, with an error code indicating the
379 * cause of the failure.
380 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900381 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000382 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000383
384 if (sEnableJavaBpfMap) {
385 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
386 } else {
387 final int err = native_removeNaughtyApp(uid);
388 maybeThrow(err, "Unable to remove naughty app");
389 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800390 }
391
Ken Chenf5f51332022-01-28 10:08:16 +0800392 /**
393 * Add nice app bandwidth rule for specific app
394 *
395 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800396 * @throws ServiceSpecificException in case of failure, with an error code indicating the
397 * cause of the failure.
398 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900399 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000400 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000401
402 if (sEnableJavaBpfMap) {
403 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
404 } else {
405 final int err = native_addNiceApp(uid);
406 maybeThrow(err, "Unable to add nice app");
407 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800408 }
409
Ken Chenf5f51332022-01-28 10:08:16 +0800410 /**
411 * Remove nice app bandwidth rule for specific app
412 *
413 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800414 * @throws ServiceSpecificException in case of failure, with an error code indicating the
415 * cause of the failure.
416 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900417 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000418 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000419
420 if (sEnableJavaBpfMap) {
421 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
422 } else {
423 final int err = native_removeNiceApp(uid);
424 maybeThrow(err, "Unable to remove nice app");
425 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800426 }
427
Ken Chenf5f51332022-01-28 10:08:16 +0800428 /**
429 * Set target firewall child chain
430 *
431 * @param childChain target chain to enable
432 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000433 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800434 * @throws ServiceSpecificException in case of failure, with an error code indicating the
435 * cause of the failure.
436 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900437 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000438 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000439
Motomu Utsumie057dd42022-08-03 01:23:49 +0000440 if (sEnableJavaBpfMap) {
441 final long match = getMatchByFirewallChain(childChain);
442 try {
443 synchronized (sUidRulesConfigBpfMapLock) {
444 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
445 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
446 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
447 }
448 } catch (ErrnoException e) {
449 throw new ServiceSpecificException(e.errno,
450 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000451 }
Motomu Utsumie057dd42022-08-03 01:23:49 +0000452 } else {
453 final int err = native_setChildChain(childChain, enable);
454 maybeThrow(err, "Unable to set child chain");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000455 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800456 }
457
458 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000459 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000460 *
461 * @param childChain target chain
462 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
463 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000464 * @throws ServiceSpecificException in case of failure, with an error code indicating the
465 * cause of the failure.
466 */
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000467 public boolean isChainEnabled(final int childChain) {
468 throwIfPreT("isChainEnabled is not available on pre-T devices");
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000469
470 final long match = getMatchByFirewallChain(childChain);
471 try {
472 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000473 return (config.val & match) != 0;
474 } catch (ErrnoException e) {
475 throw new ServiceSpecificException(e.errno,
476 "Unable to get firewall chain status: " + Os.strerror(e.errno));
477 }
478 }
479
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900480 private Set<Integer> asSet(final int[] uids) {
481 final Set<Integer> uidSet = new ArraySet<>();
482 for (final int uid: uids) {
483 uidSet.add(uid);
484 }
485 return uidSet;
486 }
487
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000488 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800489 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000490 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800491 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000492 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800493 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000494 * @throws UnsupportedOperationException if called on pre-T devices.
495 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800496 */
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000497 public void replaceUidChain(final int chain, final int[] uids) {
498 throwIfPreT("replaceUidChain is not available on pre-T devices");
499
Motomu Utsumic7c16852022-08-03 06:51:41 +0000500 if (sEnableJavaBpfMap) {
501 final long match;
502 try {
503 match = getMatchByFirewallChain(chain);
504 } catch (ServiceSpecificException e) {
505 // Throws IllegalArgumentException to keep the behavior of
506 // ConnectivityManager#replaceFirewallChain API
507 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000508 }
Motomu Utsumi1a477b02022-08-23 15:14:56 +0900509 final Set<Integer> uidSet = asSet(uids);
510 final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
Motomu Utsumic7c16852022-08-03 06:51:41 +0000511 try {
512 synchronized (sUidOwnerMap) {
513 sUidOwnerMap.forEach((uid, config) -> {
514 // config could be null if there is a concurrent entry deletion.
515 // http://b/220084230.
516 if (config != null
517 && !uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
518 uidSetToRemoveRule.add((int) uid.val);
519 }
520 });
521
522 for (final int uid : uidSetToRemoveRule) {
523 removeRule(uid, match, "replaceUidChain");
524 }
525 for (final int uid : uids) {
526 addRule(uid, match, "replaceUidChain");
527 }
528 }
529 } catch (ErrnoException | ServiceSpecificException e) {
530 Log.e(TAG, "replaceUidChain failed: " + e);
531 }
532 } else {
533 final int err;
534 switch (chain) {
535 case FIREWALL_CHAIN_DOZABLE:
536 err = native_replaceUidChain("fw_dozable", true /* isAllowList */, uids);
537 break;
538 case FIREWALL_CHAIN_STANDBY:
539 err = native_replaceUidChain("fw_standby", false /* isAllowList */, uids);
540 break;
541 case FIREWALL_CHAIN_POWERSAVE:
542 err = native_replaceUidChain("fw_powersave", true /* isAllowList */, uids);
543 break;
544 case FIREWALL_CHAIN_RESTRICTED:
545 err = native_replaceUidChain("fw_restricted", true /* isAllowList */, uids);
546 break;
547 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
548 err = native_replaceUidChain(
549 "fw_low_power_standby", true /* isAllowList */, uids);
550 break;
551 case FIREWALL_CHAIN_OEM_DENY_1:
552 err = native_replaceUidChain("fw_oem_deny_1", false /* isAllowList */, uids);
553 break;
554 case FIREWALL_CHAIN_OEM_DENY_2:
555 err = native_replaceUidChain("fw_oem_deny_2", false /* isAllowList */, uids);
556 break;
557 case FIREWALL_CHAIN_OEM_DENY_3:
558 err = native_replaceUidChain("fw_oem_deny_3", false /* isAllowList */, uids);
559 break;
560 default:
561 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
562 + chain);
563 }
564 if (err != 0) {
565 Log.e(TAG, "replaceUidChain failed: " + Os.strerror(-err));
566 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800567 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800568 }
569
Ken Chenf5f51332022-01-28 10:08:16 +0800570 /**
571 * Set firewall rule for uid
572 *
573 * @param childChain target chain
574 * @param uid uid to allow/deny
575 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800576 * @throws ServiceSpecificException in case of failure, with an error code indicating the
577 * cause of the failure.
578 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900579 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000580 throwIfPreT("setUidRule is not available on pre-T devices");
581
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000582 if (sEnableJavaBpfMap) {
583 final long match = getMatchByFirewallChain(childChain);
584 final boolean isAllowList = isFirewallAllowList(childChain);
585 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
586 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000587
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000588 if (add) {
589 addRule(uid, match, "setUidRule");
590 } else {
591 removeRule(uid, match, "setUidRule");
592 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000593 } else {
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000594 final int err = native_setUidRule(childChain, uid, firewallRule);
595 maybeThrow(err, "Unable to set uid rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000596 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800597 }
598
599 /**
600 * Add ingress interface filtering rules to a list of UIDs
601 *
602 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
603 * allowed interface and loopback to be sent to the list of UIDs.
604 *
605 * Calling this method on one or more UIDs with an existing filtering rule but a different
606 * interface name will result in the filtering rule being updated to allow the new interface
607 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
608 *
609 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800610 * be received.
611 * @param uids an array of UIDs which the filtering rules will be set
612 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800613 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800614 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800615 */
Ken Chenf5f51332022-01-28 10:08:16 +0800616 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000617 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800618 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800619 return;
620 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000621
622 if (sEnableJavaBpfMap) {
623 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
624 // ifIndex is set to 0.
625 final int ifIndex;
626 if (ifName == null) {
627 ifIndex = 0;
628 } else {
629 ifIndex = mDeps.getIfIndex(ifName);
630 if (ifIndex == 0) {
631 throw new ServiceSpecificException(ENODEV,
632 "Failed to get index of interface " + ifName);
633 }
634 }
635 for (final int uid : uids) {
636 try {
637 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
638 } catch (ServiceSpecificException e) {
639 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
640 }
641 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000642 } else {
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000643 final int err = native_addUidInterfaceRules(ifName, uids);
644 maybeThrow(err, "Unable to add uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000645 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800646 }
647
648 /**
649 * Remove ingress interface filtering rules from a list of UIDs
650 *
651 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
652 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
653 *
654 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800655 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800656 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800657 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800658 */
Ken Chenf5f51332022-01-28 10:08:16 +0800659 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000660 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800661 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800662 return;
663 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000664
665 if (sEnableJavaBpfMap) {
666 for (final int uid : uids) {
667 try {
668 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
669 } catch (ServiceSpecificException e) {
670 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
671 }
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000672 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000673 } else {
674 final int err = native_removeUidInterfaceRules(uids);
675 maybeThrow(err, "Unable to remove uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000676 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800677 }
678
Ken Chenf5f51332022-01-28 10:08:16 +0800679 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000680 * Update lockdown rule for uid
681 *
682 * @param uid target uid to add/remove the rule
683 * @param add {@code true} to add the rule, {@code false} to remove the rule.
684 * @throws ServiceSpecificException in case of failure, with an error code indicating the
685 * cause of the failure.
686 */
687 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000688 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000689
690 if (sEnableJavaBpfMap) {
691 if (add) {
692 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
693 } else {
694 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
695 }
Motomu Utsumi697b2992022-06-30 02:25:29 +0000696 } else {
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000697 final int err = native_updateUidLockdownRule(uid, add);
698 maybeThrow(err, "Unable to update lockdown rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000699 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000700 }
701
702 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800703 * Request netd to change the current active network stats map.
704 *
Ken Chenf5f51332022-01-28 10:08:16 +0800705 * @throws ServiceSpecificException in case of failure, with an error code indicating the
706 * cause of the failure.
707 */
markchien49e944c2022-03-01 15:22:20 +0800708 public void swapActiveStatsMap() {
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800709 final int err = native_swapActiveStatsMap();
Ken Chenf5f51332022-01-28 10:08:16 +0800710 maybeThrow(err, "Unable to swap active stats map");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800711 }
712
Ken Chenf5f51332022-01-28 10:08:16 +0800713 /**
714 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
715 * specified. Or remove all permissions from the uids.
716 *
717 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
718 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
719 * revoke all permissions for the uids.
720 * @param uids uid of users to grant permission
721 * @throws RemoteException when netd has crashed.
722 */
723 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000724 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800725 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800726 return;
727 }
728 native_setPermissionForUids(permissions, uids);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800729 }
730
Ken Chene6d511f2022-01-25 11:10:42 +0800731 /**
732 * Dump BPF maps
733 *
734 * @param fd file descriptor to output
735 * @throws IOException when file descriptor is invalid.
736 * @throws ServiceSpecificException when the method is called on an unsupported device.
737 */
738 public void dump(final FileDescriptor fd, boolean verbose)
739 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000740 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +0800741 throw new ServiceSpecificException(
742 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
743 + " devices, use dumpsys netd trafficcontroller instead.");
744 }
745 native_dump(fd, verbose);
746 }
747
Wayne Ma790c83e2022-01-13 10:35:05 +0800748 private static native void native_init();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800749 private native int native_addNaughtyApp(int uid);
750 private native int native_removeNaughtyApp(int uid);
751 private native int native_addNiceApp(int uid);
752 private native int native_removeNiceApp(int uid);
Motomu Utsumi114cd9c2022-08-01 02:08:35 +0000753 private native int native_setChildChain(int childChain, boolean enable);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800754 private native int native_replaceUidChain(String name, boolean isAllowlist, int[] uids);
755 private native int native_setUidRule(int childChain, int uid, int firewallRule);
756 private native int native_addUidInterfaceRules(String ifName, int[] uids);
757 private native int native_removeUidInterfaceRules(int[] uids);
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000758 private native int native_updateUidLockdownRule(int uid, boolean add);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800759 private native int native_swapActiveStatsMap();
Wayne Ma2fde98c2022-01-17 18:04:05 +0800760 private native void native_setPermissionForUids(int permissions, int[] uids);
Ken Chene6d511f2022-01-25 11:10:42 +0800761 private native void native_dump(FileDescriptor fd, boolean verbose);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800762}