blob: 8671f6b2313e6f5548ea962a58c52e9884243f31 [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;
41import android.util.Log;
42
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000043import com.android.internal.annotations.VisibleForTesting;
Ken Chenf5f51332022-01-28 10:08:16 +080044import com.android.modules.utils.build.SdkLevel;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000045import com.android.net.module.util.BpfMap;
Motomu Utsumif688eeb2022-07-22 03:47:35 +000046import com.android.net.module.util.DeviceConfigUtils;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000047import com.android.net.module.util.Struct.U32;
Ken Chenf5f51332022-01-28 10:08:16 +080048
Ken Chene6d511f2022-01-25 11:10:42 +080049import java.io.FileDescriptor;
50import java.io.IOException;
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000051import java.util.Arrays;
52import java.util.HashSet;
53import java.util.Set;
54import java.util.stream.Collectors;
Ken Chene6d511f2022-01-25 11:10:42 +080055
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080056/**
57 * BpfNetMaps is responsible for providing traffic controller relevant functionality.
58 *
59 * {@hide}
60 */
61public class BpfNetMaps {
Motomu Utsumi305975f2022-06-27 09:24:32 +000062 private static final boolean PRE_T = !SdkLevel.isAtLeastT();
63 static {
64 if (!PRE_T) {
65 System.loadLibrary("service-connectivity");
66 }
67 }
68
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080069 private static final String TAG = "BpfNetMaps";
Wayne Ma2fde98c2022-01-17 18:04:05 +080070 private final INetd mNetd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +000071 private final Dependencies mDeps;
Ken Chenf5f51332022-01-28 10:08:16 +080072 // Use legacy netd for releases before T.
Ken Chenf5f51332022-01-28 10:08:16 +080073 private static boolean sInitialized = false;
Wayne Ma0ea3bdc2022-01-12 01:12:11 +080074
Motomu Utsumif688eeb2022-07-22 03:47:35 +000075 private static Boolean sEnableJavaBpfMap = null;
76 private static final String BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP =
77 "bpf_net_maps_enable_java_bpf_map";
78
Motomu Utsumi18b287d2022-06-19 10:45:30 +000079 // Lock for sConfigurationMap entry for UID_RULES_CONFIGURATION_KEY.
80 // This entry is not accessed by others.
81 // BpfNetMaps acquires this lock while sequence of read, modify, and write.
82 private static final Object sUidRulesConfigBpfMapLock = new Object();
83
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000084 private static final String CONFIGURATION_MAP_PATH =
85 "/sys/fs/bpf/netd_shared/map_netd_configuration_map";
Motomu Utsumi5a68a212022-06-24 10:14:31 +000086 private static final String UID_OWNER_MAP_PATH =
87 "/sys/fs/bpf/netd_shared/map_netd_uid_owner_map";
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000088 private static final U32 UID_RULES_CONFIGURATION_KEY = new U32(0);
Motomu Utsumiba2fa152022-07-25 01:57:23 +000089 private static final U32 CURRENT_STATS_MAP_CONFIGURATION_KEY = new U32(1);
90 private static final long UID_RULES_DEFAULT_CONFIGURATION = 0;
91 private static final long STATS_SELECT_MAP_A = 0;
92 private static final long STATS_SELECT_MAP_B = 1;
93
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000094 private static BpfMap<U32, U32> sConfigurationMap = null;
Motomu Utsumi5a68a212022-06-24 10:14:31 +000095 // BpfMap for UID_OWNER_MAP_PATH. This map is not accessed by others.
96 private static BpfMap<U32, UidOwnerValue> sUidOwnerMap = null;
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000097
98 // LINT.IfChange(match_type)
Motomu Utsumi60ed3be2022-06-24 10:38:57 +000099 @VisibleForTesting public static final long NO_MATCH = 0;
100 @VisibleForTesting public static final long HAPPY_BOX_MATCH = (1 << 0);
101 @VisibleForTesting public static final long PENALTY_BOX_MATCH = (1 << 1);
102 @VisibleForTesting public static final long DOZABLE_MATCH = (1 << 2);
103 @VisibleForTesting public static final long STANDBY_MATCH = (1 << 3);
104 @VisibleForTesting public static final long POWERSAVE_MATCH = (1 << 4);
105 @VisibleForTesting public static final long RESTRICTED_MATCH = (1 << 5);
106 @VisibleForTesting public static final long LOW_POWER_STANDBY_MATCH = (1 << 6);
107 @VisibleForTesting public static final long IIF_MATCH = (1 << 7);
108 @VisibleForTesting public static final long LOCKDOWN_VPN_MATCH = (1 << 8);
109 @VisibleForTesting public static final long OEM_DENY_1_MATCH = (1 << 9);
110 @VisibleForTesting public static final long OEM_DENY_2_MATCH = (1 << 10);
111 @VisibleForTesting public static final long OEM_DENY_3_MATCH = (1 << 11);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000112 // LINT.ThenChange(packages/modules/Connectivity/bpf_progs/bpf_shared.h)
113
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000114 /**
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000115 * Set sEnableJavaBpfMap for test.
116 */
117 @VisibleForTesting
118 public static void setEnableJavaBpfMapForTest(boolean enable) {
119 sEnableJavaBpfMap = enable;
120 }
121
122 /**
Motomu Utsumi305975f2022-06-27 09:24:32 +0000123 * Set configurationMap for test.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000124 */
125 @VisibleForTesting
Motomu Utsumi305975f2022-06-27 09:24:32 +0000126 public static void setConfigurationMapForTest(BpfMap<U32, U32> configurationMap) {
127 sConfigurationMap = configurationMap;
128 }
129
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000130 /**
131 * Set uidOwnerMap for test.
132 */
133 @VisibleForTesting
134 public static void setUidOwnerMapForTest(BpfMap<U32, UidOwnerValue> uidOwnerMap) {
135 sUidOwnerMap = uidOwnerMap;
136 }
137
Motomu Utsumi305975f2022-06-27 09:24:32 +0000138 private static BpfMap<U32, U32> getConfigurationMap() {
139 try {
140 return new BpfMap<>(
141 CONFIGURATION_MAP_PATH, BpfMap.BPF_F_RDWR, U32.class, U32.class);
142 } catch (ErrnoException e) {
143 throw new IllegalStateException("Cannot open netd configuration map", e);
144 }
145 }
146
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000147 private static BpfMap<U32, UidOwnerValue> getUidOwnerMap() {
148 try {
149 return new BpfMap<>(
150 UID_OWNER_MAP_PATH, BpfMap.BPF_F_RDWR, U32.class, UidOwnerValue.class);
151 } catch (ErrnoException e) {
152 throw new IllegalStateException("Cannot open uid owner map", e);
153 }
154 }
155
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000156 private static void initBpfMaps() {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000157 if (sConfigurationMap == null) {
158 sConfigurationMap = getConfigurationMap();
159 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000160 try {
161 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY,
162 new U32(UID_RULES_DEFAULT_CONFIGURATION));
163 } catch (ErrnoException e) {
164 throw new IllegalStateException("Failed to initialize uid rules configuration", e);
165 }
166 try {
167 sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
168 new U32(STATS_SELECT_MAP_A));
169 } catch (ErrnoException e) {
170 throw new IllegalStateException("Failed to initialize current stats configuration", e);
171 }
172
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000173 if (sUidOwnerMap == null) {
174 sUidOwnerMap = getUidOwnerMap();
175 }
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000176 try {
177 sUidOwnerMap.clear();
178 } catch (ErrnoException e) {
179 throw new IllegalStateException("Failed to initialize uid owner map", e);
180 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000181 }
182
Ken Chenf5f51332022-01-28 10:08:16 +0800183 /**
184 * Initializes the class if it is not already initialized. This method will open maps but not
185 * cause any other effects. This method may be called multiple times on any thread.
186 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000187 private static synchronized void ensureInitialized(final Context context) {
Ken Chenf5f51332022-01-28 10:08:16 +0800188 if (sInitialized) return;
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000189 if (sEnableJavaBpfMap == null) {
190 sEnableJavaBpfMap = DeviceConfigUtils.isFeatureEnabled(context,
191 DeviceConfig.NAMESPACE_TETHERING, BPF_NET_MAPS_ENABLE_JAVA_BPF_MAP,
192 SdkLevel.isAtLeastU() /* defaultValue */);
193 }
194 Log.d(TAG, "BpfNetMaps is initialized with sEnableJavaBpfMap=" + sEnableJavaBpfMap);
195
Motomu Utsumiba2fa152022-07-25 01:57:23 +0000196 initBpfMaps();
Motomu Utsumi305975f2022-06-27 09:24:32 +0000197 native_init();
Ken Chenf5f51332022-01-28 10:08:16 +0800198 sInitialized = true;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800199 }
200
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000201 /**
202 * Dependencies of BpfNetMaps, for injection in tests.
203 */
204 @VisibleForTesting
205 public static class Dependencies {
206 /**
207 * Get interface index.
208 */
209 public int getIfIndex(final String ifName) {
210 return Os.if_nametoindex(ifName);
211 }
212 }
213
markchien49e944c2022-03-01 15:22:20 +0800214 /** Constructor used after T that doesn't need to use netd anymore. */
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000215 public BpfNetMaps(final Context context) {
216 this(context, null);
markchien49e944c2022-03-01 15:22:20 +0800217
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000218 if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
markchien49e944c2022-03-01 15:22:20 +0800219 }
220
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000221 public BpfNetMaps(final Context context, final INetd netd) {
222 this(context, netd, new Dependencies());
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000223 }
224
225 @VisibleForTesting
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000226 public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
Motomu Utsumi305975f2022-06-27 09:24:32 +0000227 if (!PRE_T) {
Motomu Utsumif688eeb2022-07-22 03:47:35 +0000228 ensureInitialized(context);
Motomu Utsumi305975f2022-06-27 09:24:32 +0000229 }
Wayne Ma2fde98c2022-01-17 18:04:05 +0800230 mNetd = netd;
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000231 mDeps = deps;
Wayne Ma790c83e2022-01-13 10:35:05 +0800232 }
233
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000234 /**
235 * Get corresponding match from firewall chain.
236 */
237 @VisibleForTesting
238 public long getMatchByFirewallChain(final int chain) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000239 switch (chain) {
240 case FIREWALL_CHAIN_DOZABLE:
241 return DOZABLE_MATCH;
242 case FIREWALL_CHAIN_STANDBY:
243 return STANDBY_MATCH;
244 case FIREWALL_CHAIN_POWERSAVE:
245 return POWERSAVE_MATCH;
246 case FIREWALL_CHAIN_RESTRICTED:
247 return RESTRICTED_MATCH;
248 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
249 return LOW_POWER_STANDBY_MATCH;
250 case FIREWALL_CHAIN_OEM_DENY_1:
251 return OEM_DENY_1_MATCH;
252 case FIREWALL_CHAIN_OEM_DENY_2:
253 return OEM_DENY_2_MATCH;
254 case FIREWALL_CHAIN_OEM_DENY_3:
255 return OEM_DENY_3_MATCH;
256 default:
257 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000258 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000259 }
260
261 /**
262 * Get if the chain is allow list or not.
263 *
264 * ALLOWLIST means the firewall denies all by default, uids must be explicitly allowed
265 * DENYLIST means the firewall allows all by default, uids must be explicitly denyed
266 */
267 @VisibleForTesting
268 public boolean isFirewallAllowList(final int chain) {
269 switch (chain) {
270 case FIREWALL_CHAIN_DOZABLE:
271 case FIREWALL_CHAIN_POWERSAVE:
272 case FIREWALL_CHAIN_RESTRICTED:
273 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
274 return true;
275 case FIREWALL_CHAIN_STANDBY:
276 case FIREWALL_CHAIN_OEM_DENY_1:
277 case FIREWALL_CHAIN_OEM_DENY_2:
278 case FIREWALL_CHAIN_OEM_DENY_3:
279 return false;
280 default:
281 throw new ServiceSpecificException(EINVAL, "Invalid firewall chain: " + chain);
282 }
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000283 }
284
Ken Chenf5f51332022-01-28 10:08:16 +0800285 private void maybeThrow(final int err, final String msg) {
286 if (err != 0) {
287 throw new ServiceSpecificException(err, msg + ": " + Os.strerror(err));
288 }
289 }
290
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000291 private void throwIfPreT(final String msg) {
292 if (PRE_T) {
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000293 throw new UnsupportedOperationException(msg);
294 }
295 }
296
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000297 private void removeRule(final int uid, final long match, final String caller) {
298 try {
299 synchronized (sUidOwnerMap) {
300 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new U32(uid));
301
302 if (oldMatch == null) {
303 throw new ServiceSpecificException(ENOENT,
304 "sUidOwnerMap does not have entry for uid: " + uid);
305 }
306
307 final UidOwnerValue newMatch = new UidOwnerValue(
308 (match == IIF_MATCH) ? 0 : oldMatch.iif,
309 oldMatch.rule & ~match
310 );
311
312 if (newMatch.rule == 0) {
313 sUidOwnerMap.deleteEntry(new U32(uid));
314 } else {
315 sUidOwnerMap.updateEntry(new U32(uid), newMatch);
316 }
317 }
318 } catch (ErrnoException e) {
319 throw new ServiceSpecificException(e.errno,
320 caller + " failed to remove rule: " + Os.strerror(e.errno));
321 }
322 }
323
Motomu Utsumi389278e2022-06-28 07:05:05 +0000324 private void addRule(final int uid, final long match, final long iif, final String caller) {
325 if (match != IIF_MATCH && iif != 0) {
326 throw new ServiceSpecificException(EINVAL,
327 "Non-interface match must have zero interface index");
328 }
329
330 try {
331 synchronized (sUidOwnerMap) {
332 final UidOwnerValue oldMatch = sUidOwnerMap.getValue(new U32(uid));
333
334 final UidOwnerValue newMatch;
335 if (oldMatch != null) {
336 newMatch = new UidOwnerValue(
337 (match == IIF_MATCH) ? iif : oldMatch.iif,
338 oldMatch.rule | match
339 );
340 } else {
341 newMatch = new UidOwnerValue(
342 iif,
343 match
344 );
345 }
346 sUidOwnerMap.updateEntry(new U32(uid), newMatch);
347 }
348 } catch (ErrnoException e) {
349 throw new ServiceSpecificException(e.errno,
350 caller + " failed to add rule: " + Os.strerror(e.errno));
351 }
352 }
353
354 private void addRule(final int uid, final long match, final String caller) {
355 addRule(uid, match, 0 /* iif */, caller);
356 }
357
Ken Chenf5f51332022-01-28 10:08:16 +0800358 /**
359 * Add naughty app bandwidth rule for specific app
360 *
361 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800362 * @throws ServiceSpecificException in case of failure, with an error code indicating the
363 * cause of the failure.
364 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900365 public void addNaughtyApp(final int uid) {
Motomu Utsumi389278e2022-06-28 07:05:05 +0000366 throwIfPreT("addNaughtyApp is not available on pre-T devices");
Motomu Utsumi55c282e2022-08-03 06:25:33 +0000367
368 if (sEnableJavaBpfMap) {
369 addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
370 } else {
371 final int err = native_addNaughtyApp(uid);
372 maybeThrow(err, "Unable to add naughty app");
373 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800374 }
375
Ken Chenf5f51332022-01-28 10:08:16 +0800376 /**
377 * Remove naughty app bandwidth rule for specific app
378 *
379 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800380 * @throws ServiceSpecificException in case of failure, with an error code indicating the
381 * cause of the failure.
382 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900383 public void removeNaughtyApp(final int uid) {
Motomu Utsumi60ed3be2022-06-24 10:38:57 +0000384 throwIfPreT("removeNaughtyApp is not available on pre-T devices");
Motomu Utsumi878ce0d2022-08-03 06:22:42 +0000385
386 if (sEnableJavaBpfMap) {
387 removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
388 } else {
389 final int err = native_removeNaughtyApp(uid);
390 maybeThrow(err, "Unable to remove naughty app");
391 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800392 }
393
Ken Chenf5f51332022-01-28 10:08:16 +0800394 /**
395 * Add nice app bandwidth rule for specific app
396 *
397 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800398 * @throws ServiceSpecificException in case of failure, with an error code indicating the
399 * cause of the failure.
400 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900401 public void addNiceApp(final int uid) {
Motomu Utsumi55630d02022-06-29 07:46:52 +0000402 throwIfPreT("addNiceApp is not available on pre-T devices");
Motomu Utsumi7f19df92022-08-03 06:29:59 +0000403
404 if (sEnableJavaBpfMap) {
405 addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
406 } else {
407 final int err = native_addNiceApp(uid);
408 maybeThrow(err, "Unable to add nice app");
409 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800410 }
411
Ken Chenf5f51332022-01-28 10:08:16 +0800412 /**
413 * Remove nice app bandwidth rule for specific app
414 *
415 * @param uid uid of target app
Ken Chenf5f51332022-01-28 10:08:16 +0800416 * @throws ServiceSpecificException in case of failure, with an error code indicating the
417 * cause of the failure.
418 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900419 public void removeNiceApp(final int uid) {
Motomu Utsumi7392eb42022-06-29 03:53:03 +0000420 throwIfPreT("removeNiceApp is not available on pre-T devices");
Motomu Utsumi5f15f752022-08-03 06:27:51 +0000421
422 if (sEnableJavaBpfMap) {
423 removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
424 } else {
425 final int err = native_removeNiceApp(uid);
426 maybeThrow(err, "Unable to remove nice app");
427 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800428 }
429
Ken Chenf5f51332022-01-28 10:08:16 +0800430 /**
431 * Set target firewall child chain
432 *
433 * @param childChain target chain to enable
434 * @param enable whether to enable or disable child chain.
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000435 * @throws UnsupportedOperationException if called on pre-T devices.
Ken Chenf5f51332022-01-28 10:08:16 +0800436 * @throws ServiceSpecificException in case of failure, with an error code indicating the
437 * cause of the failure.
438 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900439 public void setChildChain(final int childChain, final boolean enable) {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000440 throwIfPreT("setChildChain is not available on pre-T devices");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000441
442 final long match = getMatchByFirewallChain(childChain);
443 try {
444 synchronized (sUidRulesConfigBpfMapLock) {
445 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000446 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000447 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
448 }
449 } catch (ErrnoException e) {
450 throw new ServiceSpecificException(e.errno,
451 "Unable to set child chain: " + Os.strerror(e.errno));
452 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800453 }
454
455 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000456 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000457 *
458 * @param childChain target chain
459 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
460 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000461 * @throws ServiceSpecificException in case of failure, with an error code indicating the
462 * cause of the failure.
463 */
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000464 public boolean isChainEnabled(final int childChain) {
465 throwIfPreT("isChainEnabled is not available on pre-T devices");
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000466
467 final long match = getMatchByFirewallChain(childChain);
468 try {
469 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000470 return (config.val & match) != 0;
471 } catch (ErrnoException e) {
472 throw new ServiceSpecificException(e.errno,
473 "Unable to get firewall chain status: " + Os.strerror(e.errno));
474 }
475 }
476
477 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800478 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000479 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800480 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000481 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800482 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000483 * @throws UnsupportedOperationException if called on pre-T devices.
484 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800485 */
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000486 public void replaceUidChain(final int chain, final int[] uids) {
487 throwIfPreT("replaceUidChain is not available on pre-T devices");
488
Motomu Utsumic7c16852022-08-03 06:51:41 +0000489 if (sEnableJavaBpfMap) {
490 final long match;
491 try {
492 match = getMatchByFirewallChain(chain);
493 } catch (ServiceSpecificException e) {
494 // Throws IllegalArgumentException to keep the behavior of
495 // ConnectivityManager#replaceFirewallChain API
496 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000497 }
Motomu Utsumic7c16852022-08-03 06:51:41 +0000498 final Set<Integer> uidSet = Arrays.stream(uids).boxed().collect(Collectors.toSet());
499 final Set<Integer> uidSetToRemoveRule = new HashSet<>();
500 try {
501 synchronized (sUidOwnerMap) {
502 sUidOwnerMap.forEach((uid, config) -> {
503 // config could be null if there is a concurrent entry deletion.
504 // http://b/220084230.
505 if (config != null
506 && !uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
507 uidSetToRemoveRule.add((int) uid.val);
508 }
509 });
510
511 for (final int uid : uidSetToRemoveRule) {
512 removeRule(uid, match, "replaceUidChain");
513 }
514 for (final int uid : uids) {
515 addRule(uid, match, "replaceUidChain");
516 }
517 }
518 } catch (ErrnoException | ServiceSpecificException e) {
519 Log.e(TAG, "replaceUidChain failed: " + e);
520 }
521 } else {
522 final int err;
523 switch (chain) {
524 case FIREWALL_CHAIN_DOZABLE:
525 err = native_replaceUidChain("fw_dozable", true /* isAllowList */, uids);
526 break;
527 case FIREWALL_CHAIN_STANDBY:
528 err = native_replaceUidChain("fw_standby", false /* isAllowList */, uids);
529 break;
530 case FIREWALL_CHAIN_POWERSAVE:
531 err = native_replaceUidChain("fw_powersave", true /* isAllowList */, uids);
532 break;
533 case FIREWALL_CHAIN_RESTRICTED:
534 err = native_replaceUidChain("fw_restricted", true /* isAllowList */, uids);
535 break;
536 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
537 err = native_replaceUidChain(
538 "fw_low_power_standby", true /* isAllowList */, uids);
539 break;
540 case FIREWALL_CHAIN_OEM_DENY_1:
541 err = native_replaceUidChain("fw_oem_deny_1", false /* isAllowList */, uids);
542 break;
543 case FIREWALL_CHAIN_OEM_DENY_2:
544 err = native_replaceUidChain("fw_oem_deny_2", false /* isAllowList */, uids);
545 break;
546 case FIREWALL_CHAIN_OEM_DENY_3:
547 err = native_replaceUidChain("fw_oem_deny_3", false /* isAllowList */, uids);
548 break;
549 default:
550 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
551 + chain);
552 }
553 if (err != 0) {
554 Log.e(TAG, "replaceUidChain failed: " + Os.strerror(-err));
555 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800556 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800557 }
558
Ken Chenf5f51332022-01-28 10:08:16 +0800559 /**
560 * Set firewall rule for uid
561 *
562 * @param childChain target chain
563 * @param uid uid to allow/deny
564 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800565 * @throws ServiceSpecificException in case of failure, with an error code indicating the
566 * cause of the failure.
567 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900568 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000569 throwIfPreT("setUidRule is not available on pre-T devices");
570
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000571 if (sEnableJavaBpfMap) {
572 final long match = getMatchByFirewallChain(childChain);
573 final boolean isAllowList = isFirewallAllowList(childChain);
574 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
575 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000576
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000577 if (add) {
578 addRule(uid, match, "setUidRule");
579 } else {
580 removeRule(uid, match, "setUidRule");
581 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000582 } else {
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000583 final int err = native_setUidRule(childChain, uid, firewallRule);
584 maybeThrow(err, "Unable to set uid rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000585 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800586 }
587
588 /**
589 * Add ingress interface filtering rules to a list of UIDs
590 *
591 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
592 * allowed interface and loopback to be sent to the list of UIDs.
593 *
594 * Calling this method on one or more UIDs with an existing filtering rule but a different
595 * interface name will result in the filtering rule being updated to allow the new interface
596 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
597 *
598 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800599 * be received.
600 * @param uids an array of UIDs which the filtering rules will be set
601 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800602 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800603 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800604 */
Ken Chenf5f51332022-01-28 10:08:16 +0800605 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000606 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800607 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800608 return;
609 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000610
611 if (sEnableJavaBpfMap) {
612 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
613 // ifIndex is set to 0.
614 final int ifIndex;
615 if (ifName == null) {
616 ifIndex = 0;
617 } else {
618 ifIndex = mDeps.getIfIndex(ifName);
619 if (ifIndex == 0) {
620 throw new ServiceSpecificException(ENODEV,
621 "Failed to get index of interface " + ifName);
622 }
623 }
624 for (final int uid : uids) {
625 try {
626 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
627 } catch (ServiceSpecificException e) {
628 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
629 }
630 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000631 } else {
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000632 final int err = native_addUidInterfaceRules(ifName, uids);
633 maybeThrow(err, "Unable to add uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000634 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800635 }
636
637 /**
638 * Remove ingress interface filtering rules from a list of UIDs
639 *
640 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
641 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
642 *
643 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800644 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800645 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800646 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800647 */
Ken Chenf5f51332022-01-28 10:08:16 +0800648 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000649 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800650 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800651 return;
652 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000653
654 if (sEnableJavaBpfMap) {
655 for (final int uid : uids) {
656 try {
657 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
658 } catch (ServiceSpecificException e) {
659 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
660 }
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000661 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000662 } else {
663 final int err = native_removeUidInterfaceRules(uids);
664 maybeThrow(err, "Unable to remove uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000665 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800666 }
667
Ken Chenf5f51332022-01-28 10:08:16 +0800668 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000669 * Update lockdown rule for uid
670 *
671 * @param uid target uid to add/remove the rule
672 * @param add {@code true} to add the rule, {@code false} to remove the rule.
673 * @throws ServiceSpecificException in case of failure, with an error code indicating the
674 * cause of the failure.
675 */
676 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000677 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000678
679 if (sEnableJavaBpfMap) {
680 if (add) {
681 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
682 } else {
683 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
684 }
Motomu Utsumi697b2992022-06-30 02:25:29 +0000685 } else {
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000686 final int err = native_updateUidLockdownRule(uid, add);
687 maybeThrow(err, "Unable to update lockdown rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000688 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000689 }
690
691 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800692 * Request netd to change the current active network stats map.
693 *
Ken Chenf5f51332022-01-28 10:08:16 +0800694 * @throws ServiceSpecificException in case of failure, with an error code indicating the
695 * cause of the failure.
696 */
markchien49e944c2022-03-01 15:22:20 +0800697 public void swapActiveStatsMap() {
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800698 final int err = native_swapActiveStatsMap();
Ken Chenf5f51332022-01-28 10:08:16 +0800699 maybeThrow(err, "Unable to swap active stats map");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800700 }
701
Ken Chenf5f51332022-01-28 10:08:16 +0800702 /**
703 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
704 * specified. Or remove all permissions from the uids.
705 *
706 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
707 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
708 * revoke all permissions for the uids.
709 * @param uids uid of users to grant permission
710 * @throws RemoteException when netd has crashed.
711 */
712 public void setNetPermForUids(final int permissions, 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.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800715 return;
716 }
717 native_setPermissionForUids(permissions, uids);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800718 }
719
Ken Chene6d511f2022-01-25 11:10:42 +0800720 /**
721 * Dump BPF maps
722 *
723 * @param fd file descriptor to output
724 * @throws IOException when file descriptor is invalid.
725 * @throws ServiceSpecificException when the method is called on an unsupported device.
726 */
727 public void dump(final FileDescriptor fd, boolean verbose)
728 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000729 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +0800730 throw new ServiceSpecificException(
731 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
732 + " devices, use dumpsys netd trafficcontroller instead.");
733 }
734 native_dump(fd, verbose);
735 }
736
Wayne Ma790c83e2022-01-13 10:35:05 +0800737 private static native void native_init();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800738 private native int native_addNaughtyApp(int uid);
739 private native int native_removeNaughtyApp(int uid);
740 private native int native_addNiceApp(int uid);
741 private native int native_removeNiceApp(int uid);
Motomu Utsumi114cd9c2022-08-01 02:08:35 +0000742 private native int native_setChildChain(int childChain, boolean enable);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800743 private native int native_replaceUidChain(String name, boolean isAllowlist, int[] uids);
744 private native int native_setUidRule(int childChain, int uid, int firewallRule);
745 private native int native_addUidInterfaceRules(String ifName, int[] uids);
746 private native int native_removeUidInterfaceRules(int[] uids);
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000747 private native int native_updateUidLockdownRule(int uid, boolean add);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800748 private native int native_swapActiveStatsMap();
Wayne Ma2fde98c2022-01-17 18:04:05 +0800749 private native void native_setPermissionForUids(int permissions, int[] uids);
Ken Chene6d511f2022-01-25 11:10:42 +0800750 private native void native_dump(FileDescriptor fd, boolean verbose);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800751}