blob: 594223ce3b2bf99dbe843038f1755cddb57de658 [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
Motomu Utsumie057dd42022-08-03 01:23:49 +0000442 if (sEnableJavaBpfMap) {
443 final long match = getMatchByFirewallChain(childChain);
444 try {
445 synchronized (sUidRulesConfigBpfMapLock) {
446 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
447 final long newConfig = enable ? (config.val | match) : (config.val & ~match);
448 sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
449 }
450 } catch (ErrnoException e) {
451 throw new ServiceSpecificException(e.errno,
452 "Unable to set child chain: " + Os.strerror(e.errno));
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000453 }
Motomu Utsumie057dd42022-08-03 01:23:49 +0000454 } else {
455 final int err = native_setChildChain(childChain, enable);
456 maybeThrow(err, "Unable to set child chain");
Motomu Utsumi18b287d2022-06-19 10:45:30 +0000457 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800458 }
459
460 /**
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000461 * Get the specified firewall chain's status.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000462 *
463 * @param childChain target chain
464 * @return {@code true} if chain is enabled, {@code false} if chain is not enabled.
465 * @throws UnsupportedOperationException if called on pre-T devices.
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000466 * @throws ServiceSpecificException in case of failure, with an error code indicating the
467 * cause of the failure.
468 */
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000469 public boolean isChainEnabled(final int childChain) {
470 throwIfPreT("isChainEnabled is not available on pre-T devices");
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000471
472 final long match = getMatchByFirewallChain(childChain);
473 try {
474 final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +0000475 return (config.val & match) != 0;
476 } catch (ErrnoException e) {
477 throw new ServiceSpecificException(e.errno,
478 "Unable to get firewall chain status: " + Os.strerror(e.errno));
479 }
480 }
481
482 /**
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800483 * Replaces the contents of the specified UID-based firewall chain.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000484 * Enables the chain for specified uids and disables the chain for non-specified uids.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800485 *
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000486 * @param chain Target chain.
Ken Chenf5f51332022-01-28 10:08:16 +0800487 * @param uids The list of UIDs to allow/deny.
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000488 * @throws UnsupportedOperationException if called on pre-T devices.
489 * @throws IllegalArgumentException if {@code chain} is not a valid chain.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800490 */
Motomu Utsumi9be2ea02022-07-05 06:14:59 +0000491 public void replaceUidChain(final int chain, final int[] uids) {
492 throwIfPreT("replaceUidChain is not available on pre-T devices");
493
Motomu Utsumic7c16852022-08-03 06:51:41 +0000494 if (sEnableJavaBpfMap) {
495 final long match;
496 try {
497 match = getMatchByFirewallChain(chain);
498 } catch (ServiceSpecificException e) {
499 // Throws IllegalArgumentException to keep the behavior of
500 // ConnectivityManager#replaceFirewallChain API
501 throw new IllegalArgumentException("Invalid firewall chain: " + chain);
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000502 }
Motomu Utsumic7c16852022-08-03 06:51:41 +0000503 final Set<Integer> uidSet = Arrays.stream(uids).boxed().collect(Collectors.toSet());
504 final Set<Integer> uidSetToRemoveRule = new HashSet<>();
505 try {
506 synchronized (sUidOwnerMap) {
507 sUidOwnerMap.forEach((uid, config) -> {
508 // config could be null if there is a concurrent entry deletion.
509 // http://b/220084230.
510 if (config != null
511 && !uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
512 uidSetToRemoveRule.add((int) uid.val);
513 }
514 });
515
516 for (final int uid : uidSetToRemoveRule) {
517 removeRule(uid, match, "replaceUidChain");
518 }
519 for (final int uid : uids) {
520 addRule(uid, match, "replaceUidChain");
521 }
522 }
523 } catch (ErrnoException | ServiceSpecificException e) {
524 Log.e(TAG, "replaceUidChain failed: " + e);
525 }
526 } else {
527 final int err;
528 switch (chain) {
529 case FIREWALL_CHAIN_DOZABLE:
530 err = native_replaceUidChain("fw_dozable", true /* isAllowList */, uids);
531 break;
532 case FIREWALL_CHAIN_STANDBY:
533 err = native_replaceUidChain("fw_standby", false /* isAllowList */, uids);
534 break;
535 case FIREWALL_CHAIN_POWERSAVE:
536 err = native_replaceUidChain("fw_powersave", true /* isAllowList */, uids);
537 break;
538 case FIREWALL_CHAIN_RESTRICTED:
539 err = native_replaceUidChain("fw_restricted", true /* isAllowList */, uids);
540 break;
541 case FIREWALL_CHAIN_LOW_POWER_STANDBY:
542 err = native_replaceUidChain(
543 "fw_low_power_standby", true /* isAllowList */, uids);
544 break;
545 case FIREWALL_CHAIN_OEM_DENY_1:
546 err = native_replaceUidChain("fw_oem_deny_1", false /* isAllowList */, uids);
547 break;
548 case FIREWALL_CHAIN_OEM_DENY_2:
549 err = native_replaceUidChain("fw_oem_deny_2", false /* isAllowList */, uids);
550 break;
551 case FIREWALL_CHAIN_OEM_DENY_3:
552 err = native_replaceUidChain("fw_oem_deny_3", false /* isAllowList */, uids);
553 break;
554 default:
555 throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
556 + chain);
557 }
558 if (err != 0) {
559 Log.e(TAG, "replaceUidChain failed: " + Os.strerror(-err));
560 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800561 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800562 }
563
Ken Chenf5f51332022-01-28 10:08:16 +0800564 /**
565 * Set firewall rule for uid
566 *
567 * @param childChain target chain
568 * @param uid uid to allow/deny
569 * @param firewallRule either FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
Ken Chenf5f51332022-01-28 10:08:16 +0800570 * @throws ServiceSpecificException in case of failure, with an error code indicating the
571 * cause of the failure.
572 */
Lorenzo Colitti82244fd2022-03-04 23:15:00 +0900573 public void setUidRule(final int childChain, final int uid, final int firewallRule) {
Motomu Utsumi40230be2022-07-05 03:27:35 +0000574 throwIfPreT("setUidRule is not available on pre-T devices");
575
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000576 if (sEnableJavaBpfMap) {
577 final long match = getMatchByFirewallChain(childChain);
578 final boolean isAllowList = isFirewallAllowList(childChain);
579 final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
580 || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
Motomu Utsumi40230be2022-07-05 03:27:35 +0000581
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000582 if (add) {
583 addRule(uid, match, "setUidRule");
584 } else {
585 removeRule(uid, match, "setUidRule");
586 }
Motomu Utsumi40230be2022-07-05 03:27:35 +0000587 } else {
Motomu Utsumi381ad9e2022-08-03 06:42:47 +0000588 final int err = native_setUidRule(childChain, uid, firewallRule);
589 maybeThrow(err, "Unable to set uid rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000590 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800591 }
592
593 /**
594 * Add ingress interface filtering rules to a list of UIDs
595 *
596 * For a given uid, once a filtering rule is added, the kernel will only allow packets from the
597 * allowed interface and loopback to be sent to the list of UIDs.
598 *
599 * Calling this method on one or more UIDs with an existing filtering rule but a different
600 * interface name will result in the filtering rule being updated to allow the new interface
601 * instead. Otherwise calling this method will not affect existing rules set on other UIDs.
602 *
603 * @param ifName the name of the interface on which the filtering rules will allow packets to
Ken Chenf5f51332022-01-28 10:08:16 +0800604 * be received.
605 * @param uids an array of UIDs which the filtering rules will be set
606 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800607 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800608 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800609 */
Ken Chenf5f51332022-01-28 10:08:16 +0800610 public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000611 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800612 mNetd.firewallAddUidInterfaceRules(ifName, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800613 return;
614 }
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000615
616 if (sEnableJavaBpfMap) {
617 // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
618 // ifIndex is set to 0.
619 final int ifIndex;
620 if (ifName == null) {
621 ifIndex = 0;
622 } else {
623 ifIndex = mDeps.getIfIndex(ifName);
624 if (ifIndex == 0) {
625 throw new ServiceSpecificException(ENODEV,
626 "Failed to get index of interface " + ifName);
627 }
628 }
629 for (final int uid : uids) {
630 try {
631 addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
632 } catch (ServiceSpecificException e) {
633 Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
634 }
635 }
Motomu Utsumi5f52f4f2022-06-30 03:31:09 +0000636 } else {
Motomu Utsumif794e7d2022-08-03 06:38:43 +0000637 final int err = native_addUidInterfaceRules(ifName, uids);
638 maybeThrow(err, "Unable to add uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000639 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800640 }
641
642 /**
643 * Remove ingress interface filtering rules from a list of UIDs
644 *
645 * Clear the ingress interface filtering rules from the list of UIDs which were previously set
646 * by addUidInterfaceRules(). Ignore any uid which does not have filtering rule.
647 *
648 * @param uids an array of UIDs from which the filtering rules will be removed
Ken Chenf5f51332022-01-28 10:08:16 +0800649 * @throws RemoteException when netd has crashed.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800650 * @throws ServiceSpecificException in case of failure, with an error code indicating the
Ken Chenf5f51332022-01-28 10:08:16 +0800651 * cause of the failure.
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800652 */
Ken Chenf5f51332022-01-28 10:08:16 +0800653 public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000654 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800655 mNetd.firewallRemoveUidInterfaceRules(uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800656 return;
657 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000658
659 if (sEnableJavaBpfMap) {
660 for (final int uid : uids) {
661 try {
662 removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
663 } catch (ServiceSpecificException e) {
664 Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
665 }
Motomu Utsumi599c4e52022-06-30 03:37:18 +0000666 }
Motomu Utsumi7dc657d2022-08-03 06:40:46 +0000667 } else {
668 final int err = native_removeUidInterfaceRules(uids);
669 maybeThrow(err, "Unable to remove uid interface rules");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000670 }
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800671 }
672
Ken Chenf5f51332022-01-28 10:08:16 +0800673 /**
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000674 * Update lockdown rule for uid
675 *
676 * @param uid target uid to add/remove the rule
677 * @param add {@code true} to add the rule, {@code false} to remove the rule.
678 * @throws ServiceSpecificException in case of failure, with an error code indicating the
679 * cause of the failure.
680 */
681 public void updateUidLockdownRule(final int uid, final boolean add) {
Motomu Utsumi697b2992022-06-30 02:25:29 +0000682 throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000683
684 if (sEnableJavaBpfMap) {
685 if (add) {
686 addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
687 } else {
688 removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
689 }
Motomu Utsumi697b2992022-06-30 02:25:29 +0000690 } else {
Motomu Utsumib2d32b72022-08-03 06:31:58 +0000691 final int err = native_updateUidLockdownRule(uid, add);
692 maybeThrow(err, "Unable to update lockdown rule");
Motomu Utsumi5a68a212022-06-24 10:14:31 +0000693 }
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000694 }
695
696 /**
Ken Chenf5f51332022-01-28 10:08:16 +0800697 * Request netd to change the current active network stats map.
698 *
Ken Chenf5f51332022-01-28 10:08:16 +0800699 * @throws ServiceSpecificException in case of failure, with an error code indicating the
700 * cause of the failure.
701 */
markchien49e944c2022-03-01 15:22:20 +0800702 public void swapActiveStatsMap() {
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800703 final int err = native_swapActiveStatsMap();
Ken Chenf5f51332022-01-28 10:08:16 +0800704 maybeThrow(err, "Unable to swap active stats map");
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800705 }
706
Ken Chenf5f51332022-01-28 10:08:16 +0800707 /**
708 * Assigns android.permission.INTERNET and/or android.permission.UPDATE_DEVICE_STATS to the uids
709 * specified. Or remove all permissions from the uids.
710 *
711 * @param permissions The permission to grant, it could be either PERMISSION_INTERNET and/or
712 * PERMISSION_UPDATE_DEVICE_STATS. If the permission is NO_PERMISSIONS, then
713 * revoke all permissions for the uids.
714 * @param uids uid of users to grant permission
715 * @throws RemoteException when netd has crashed.
716 */
717 public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000718 if (PRE_T) {
Ken Chenf5f51332022-01-28 10:08:16 +0800719 mNetd.trafficSetNetPermForUids(permissions, uids);
Wayne Ma2fde98c2022-01-17 18:04:05 +0800720 return;
721 }
722 native_setPermissionForUids(permissions, uids);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800723 }
724
Ken Chene6d511f2022-01-25 11:10:42 +0800725 /**
726 * Dump BPF maps
727 *
728 * @param fd file descriptor to output
729 * @throws IOException when file descriptor is invalid.
730 * @throws ServiceSpecificException when the method is called on an unsupported device.
731 */
732 public void dump(final FileDescriptor fd, boolean verbose)
733 throws IOException, ServiceSpecificException {
Motomu Utsumi25cf86f2022-06-27 08:50:19 +0000734 if (PRE_T) {
Ken Chene6d511f2022-01-25 11:10:42 +0800735 throw new ServiceSpecificException(
736 EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
737 + " devices, use dumpsys netd trafficcontroller instead.");
738 }
739 native_dump(fd, verbose);
740 }
741
Wayne Ma790c83e2022-01-13 10:35:05 +0800742 private static native void native_init();
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800743 private native int native_addNaughtyApp(int uid);
744 private native int native_removeNaughtyApp(int uid);
745 private native int native_addNiceApp(int uid);
746 private native int native_removeNiceApp(int uid);
Motomu Utsumi114cd9c2022-08-01 02:08:35 +0000747 private native int native_setChildChain(int childChain, boolean enable);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800748 private native int native_replaceUidChain(String name, boolean isAllowlist, int[] uids);
749 private native int native_setUidRule(int childChain, int uid, int firewallRule);
750 private native int native_addUidInterfaceRules(String ifName, int[] uids);
751 private native int native_removeUidInterfaceRules(int[] uids);
Motomu Utsumi8b42e6d2022-05-19 06:23:40 +0000752 private native int native_updateUidLockdownRule(int uid, boolean add);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800753 private native int native_swapActiveStatsMap();
Wayne Ma2fde98c2022-01-17 18:04:05 +0800754 private native void native_setPermissionForUids(int permissions, int[] uids);
Ken Chene6d511f2022-01-25 11:10:42 +0800755 private native void native_dump(FileDescriptor fd, boolean verbose);
Wayne Ma0ea3bdc2022-01-12 01:12:11 +0800756}