Merge "Merge sc-v2-dev-plus-aosp-without-vendor@8084891" into stage-aosp-master
diff --git a/Tethering/src/com/android/networkstack/tethering/BpfCoordinator.java b/Tethering/src/com/android/networkstack/tethering/BpfCoordinator.java
index 40956f7..6550de2 100644
--- a/Tethering/src/com/android/networkstack/tethering/BpfCoordinator.java
+++ b/Tethering/src/com/android/networkstack/tethering/BpfCoordinator.java
@@ -52,6 +52,7 @@
import android.system.OsConstants;
import android.text.TextUtils;
import android.util.ArraySet;
+import android.util.Base64;
import android.util.Log;
import android.util.SparseArray;
@@ -118,6 +119,9 @@
private static final String TETHER_ERROR_MAP_PATH = makeMapPath("error");
private static final String TETHER_DEV_MAP_PATH = makeMapPath("dev");
+ // Using "," as a separator is safe because base64 characters are [0-9a-zA-Z/=+].
+ private static final String DUMP_BASE64_DELIMITER = ",";
+
/** The names of all the BPF counters defined in bpf_tethering.h. */
public static final String[] sBpfCounterNames = getBpfCounterNames();
@@ -1068,6 +1072,42 @@
}
}
+ private String ipv4RuleToBase64String(Tether4Key key, Tether4Value value) {
+ final byte[] keyBytes = key.writeToBytes();
+ final String keyBase64Str = Base64.encodeToString(keyBytes, Base64.DEFAULT)
+ .replace("\n", "");
+ final byte[] valueBytes = value.writeToBytes();
+ final String valueBase64Str = Base64.encodeToString(valueBytes, Base64.DEFAULT)
+ .replace("\n", "");
+
+ return keyBase64Str + DUMP_BASE64_DELIMITER + valueBase64Str;
+ }
+
+ private void dumpRawIpv4ForwardingRuleMap(
+ BpfMap<Tether4Key, Tether4Value> map, IndentingPrintWriter pw) throws ErrnoException {
+ if (map == null) {
+ pw.println("No IPv4 support");
+ return;
+ }
+ if (map.isEmpty()) {
+ pw.println("No rules");
+ return;
+ }
+ map.forEach((k, v) -> pw.println(ipv4RuleToBase64String(k, v)));
+ }
+
+ /**
+ * Dump raw BPF map in base64 encoded strings. For test only.
+ */
+ public void dumpRawMap(@NonNull IndentingPrintWriter pw) {
+ try (BpfMap<Tether4Key, Tether4Value> upstreamMap = mDeps.getBpfUpstream4Map()) {
+ // TODO: dump downstream map.
+ dumpRawIpv4ForwardingRuleMap(upstreamMap, pw);
+ } catch (ErrnoException e) {
+ pw.println("Error dumping IPv4 map: " + e);
+ }
+ }
+
private String l4protoToString(int proto) {
if (proto == OsConstants.IPPROTO_TCP) {
return "tcp";
diff --git a/Tethering/src/com/android/networkstack/tethering/Tethering.java b/Tethering/src/com/android/networkstack/tethering/Tethering.java
index db9a64f..301a682 100644
--- a/Tethering/src/com/android/networkstack/tethering/Tethering.java
+++ b/Tethering/src/com/android/networkstack/tethering/Tethering.java
@@ -2479,6 +2479,13 @@
@SuppressWarnings("resource") final IndentingPrintWriter pw = new IndentingPrintWriter(
writer, " ");
+ // Used for testing instead of human debug.
+ // TODO: add options to choose which map to dump.
+ if (argsContain(args, "bpfRawMap")) {
+ mBpfCoordinator.dumpRawMap(pw);
+ return;
+ }
+
if (argsContain(args, "bpf")) {
dumpBpf(pw);
return;
diff --git a/framework-t/Android.bp b/framework-t/Android.bp
index f464322..50a3eb2 100644
--- a/framework-t/Android.bp
+++ b/framework-t/Android.bp
@@ -128,7 +128,7 @@
"//packages/modules/CaptivePortalLogin/tests",
"//packages/modules/Connectivity/Tethering/tests:__subpackages__",
"//packages/modules/Connectivity/tests:__subpackages__",
- "//packages/modules/IPsec/tests/iketests",
+ "//packages/modules/IPsec/tests/iketests",
"//packages/modules/NetworkStack/tests:__subpackages__",
"//packages/modules/Nearby/tests:__subpackages__",
"//packages/modules/Wifi/service/tests/wifitests",
diff --git a/framework/api/module-lib-current.txt b/framework/api/module-lib-current.txt
index fda1045..5579db6 100644
--- a/framework/api/module-lib-current.txt
+++ b/framework/api/module-lib-current.txt
@@ -10,6 +10,8 @@
method @NonNull @RequiresPermission(anyOf={android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, android.Manifest.permission.NETWORK_STACK, android.Manifest.permission.NETWORK_SETTINGS}) public java.util.List<android.net.NetworkStateSnapshot> getAllNetworkStateSnapshots();
method @Nullable public android.net.ProxyInfo getGlobalProxy();
method @NonNull public static android.util.Range<java.lang.Integer> getIpSecNetIdRange();
+ method @Nullable @RequiresPermission(anyOf={android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, android.Manifest.permission.NETWORK_STACK, android.Manifest.permission.NETWORK_SETTINGS}) public android.net.LinkProperties redactLinkPropertiesForPackage(@NonNull android.net.LinkProperties, int, @NonNull String);
+ method @Nullable @RequiresPermission(anyOf={android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, android.Manifest.permission.NETWORK_STACK, android.Manifest.permission.NETWORK_SETTINGS}) public android.net.NetworkCapabilities redactNetworkCapabilitiesForPackage(@NonNull android.net.NetworkCapabilities, int, @NonNull String);
method @RequiresPermission(anyOf={android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, android.Manifest.permission.NETWORK_SETTINGS}) public void registerDefaultNetworkCallbackForUid(int, @NonNull android.net.ConnectivityManager.NetworkCallback, @NonNull android.os.Handler);
method @RequiresPermission(anyOf={android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, android.Manifest.permission.NETWORK_SETTINGS}) public void registerSystemDefaultNetworkCallback(@NonNull android.net.ConnectivityManager.NetworkCallback, @NonNull android.os.Handler);
method @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_SETTINGS, android.Manifest.permission.NETWORK_STACK, android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK}) public void replaceFirewallChain(int, @NonNull int[]);
diff --git a/framework/src/android/net/ConnectivityManager.java b/framework/src/android/net/ConnectivityManager.java
index 5246623..e8e1efa 100644
--- a/framework/src/android/net/ConnectivityManager.java
+++ b/framework/src/android/net/ConnectivityManager.java
@@ -1625,16 +1625,45 @@
}
/**
- * Get the {@link NetworkCapabilities} for the given {@link Network}. This
- * will return {@code null} if the network is unknown or if the |network| argument is null.
+ * Redact {@link LinkProperties} for a given package
*
- * This will remove any location sensitive data in {@link TransportInfo} embedded in
- * {@link NetworkCapabilities#getTransportInfo()}. Some transport info instances like
- * {@link android.net.wifi.WifiInfo} contain location sensitive information. Retrieving
- * this location sensitive information (subject to app's location permissions) will be
- * noted by system. To include any location sensitive data in {@link TransportInfo},
- * use a {@link NetworkCallback} with
- * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag.
+ * Returns an instance of the given {@link LinkProperties} appropriately redacted to send to the
+ * given package, considering its permissions.
+ *
+ * @param lp A {@link LinkProperties} which will be redacted.
+ * @param uid The target uid.
+ * @param packageName The name of the package, for appops logging.
+ * @return A redacted {@link LinkProperties} which is appropriate to send to the given uid,
+ * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
+ * @hide
+ */
+ @RequiresPermission(anyOf = {
+ NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+ android.Manifest.permission.NETWORK_STACK,
+ android.Manifest.permission.NETWORK_SETTINGS})
+ @SystemApi(client = MODULE_LIBRARIES)
+ @Nullable
+ public LinkProperties redactLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
+ @NonNull String packageName) {
+ try {
+ return mService.redactLinkPropertiesForPackage(
+ lp, uid, packageName, getAttributionTag());
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Get the {@link NetworkCapabilities} for the given {@link Network}, or null.
+ *
+ * This will remove any location sensitive data in the returned {@link NetworkCapabilities}.
+ * Some {@link TransportInfo} instances like {@link android.net.wifi.WifiInfo} contain location
+ * sensitive information. To retrieve this location sensitive information (subject to
+ * the caller's location permissions), use a {@link NetworkCallback} with the
+ * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} flag instead.
+ *
+ * This method returns {@code null} if the network is unknown or if the |network| argument
+ * is null.
*
* @param network The {@link Network} object identifying the network in question.
* @return The {@link NetworkCapabilities} for the network, or {@code null}.
@@ -1651,6 +1680,38 @@
}
/**
+ * Redact {@link NetworkCapabilities} for a given package.
+ *
+ * Returns an instance of {@link NetworkCapabilities} that is appropriately redacted to send
+ * to the given package, considering its permissions. Calling this method will blame the UID for
+ * retrieving the device location if the passed capabilities contain location-sensitive
+ * information.
+ *
+ * @param nc A {@link NetworkCapabilities} instance which will be redacted.
+ * @param uid The target uid.
+ * @param packageName The name of the package, for appops logging.
+ * @return A redacted {@link NetworkCapabilities} which is appropriate to send to the given uid,
+ * or null if the uid lacks the ACCESS_NETWORK_STATE permission.
+ * @hide
+ */
+ @RequiresPermission(anyOf = {
+ NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+ android.Manifest.permission.NETWORK_STACK,
+ android.Manifest.permission.NETWORK_SETTINGS})
+ @SystemApi(client = MODULE_LIBRARIES)
+ @Nullable
+ public NetworkCapabilities redactNetworkCapabilitiesForPackage(
+ @NonNull NetworkCapabilities nc,
+ int uid, @NonNull String packageName) {
+ try {
+ return mService.redactNetworkCapabilitiesForPackage(nc, uid, packageName,
+ getAttributionTag());
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
* Gets a URL that can be used for resolving whether a captive portal is present.
* 1. This URL should respond with a 204 response to a GET request to indicate no captive
* portal is present.
@@ -3547,7 +3608,20 @@
* @hide
*/
public static final int FLAG_NONE = 0;
+
/**
+ * Inclusion of this flag means location-sensitive redaction requests keeping location info.
+ *
+ * Some objects like {@link NetworkCapabilities} may contain location-sensitive information.
+ * Prior to Android 12, this information is always returned to apps holding the appropriate
+ * permission, possibly noting that the app has used location.
+ * <p>In Android 12 and above, by default the sent objects do not contain any location
+ * information, even if the app holds the necessary permissions, and the system does not
+ * take note of location usage by the app. Apps can request that location information is
+ * included, in which case the system will check location permission and the location
+ * toggle state, and take note of location usage by the app if any such information is
+ * returned.
+ *
* Use this flag to include any location sensitive data in {@link NetworkCapabilities} sent
* via {@link #onCapabilitiesChanged(Network, NetworkCapabilities)}.
* <p>
@@ -3564,8 +3638,7 @@
* <li> Retrieving this location sensitive information (subject to app's location
* permissions) will be noted by system. </li>
* <li> Without this flag any {@link NetworkCapabilities} provided via the callback does
- * not include location sensitive info.
- * </p>
+ * not include location sensitive information.
*/
// Note: Some existing fields which are location sensitive may still be included without
// this flag if the app targets SDK < S (to maintain backwards compatibility).
diff --git a/framework/src/android/net/IConnectivityManager.aidl b/framework/src/android/net/IConnectivityManager.aidl
index df4663f..23a3850 100644
--- a/framework/src/android/net/IConnectivityManager.aidl
+++ b/framework/src/android/net/IConnectivityManager.aidl
@@ -76,10 +76,15 @@
LinkProperties getActiveLinkProperties();
LinkProperties getLinkPropertiesForType(int networkType);
LinkProperties getLinkProperties(in Network network);
+ LinkProperties redactLinkPropertiesForPackage(in LinkProperties lp, int uid, String packageName,
+ String callingAttributionTag);
NetworkCapabilities getNetworkCapabilities(in Network network, String callingPackageName,
String callingAttributionTag);
+ NetworkCapabilities redactNetworkCapabilitiesForPackage(in NetworkCapabilities nc, int uid,
+ String callingPackageName, String callingAttributionTag);
+
@UnsupportedAppUsage(maxTargetSdk = 30, trackingBug = 170729553)
NetworkState[] getAllNetworkState();
diff --git a/framework/src/android/net/NetworkCapabilities.java b/framework/src/android/net/NetworkCapabilities.java
index b6cd760..41be732 100644
--- a/framework/src/android/net/NetworkCapabilities.java
+++ b/framework/src/android/net/NetworkCapabilities.java
@@ -1536,9 +1536,12 @@
*/
public @NonNull NetworkCapabilities setNetworkSpecifier(
@NonNull NetworkSpecifier networkSpecifier) {
- if (networkSpecifier != null && Long.bitCount(mTransportTypes) != 1) {
- throw new IllegalStateException("Must have a single transport specified to use " +
- "setNetworkSpecifier");
+ if (networkSpecifier != null
+ // Transport can be test, or test + a single other transport
+ && mTransportTypes != (1L << TRANSPORT_TEST)
+ && Long.bitCount(mTransportTypes & ~(1L << TRANSPORT_TEST)) != 1) {
+ throw new IllegalStateException("Must have a single non-test transport specified to "
+ + "use setNetworkSpecifier");
}
mNetworkSpecifier = networkSpecifier;
diff --git a/service/jni/com_android_server_BpfNetMaps.cpp b/service/jni/com_android_server_BpfNetMaps.cpp
index 2aaa4c3..c29eb2b 100644
--- a/service/jni/com_android_server_BpfNetMaps.cpp
+++ b/service/jni/com_android_server_BpfNetMaps.cpp
@@ -202,24 +202,6 @@
mTc.setPermissionForUids(permission, data);
}
-static jint native_setCounterSet(JNIEnv* env, jobject clazz, jint setNum, jint uid) {
- uid_t callingUid = getuid();
- int res = mTc.setCounterSet(setNum, (uid_t)uid, callingUid);
- if (res) {
- ALOGE("%s failed, error code = %d", __func__, res);
- }
- return (jint)res;
-}
-
-static jint native_deleteTagData(JNIEnv* env, jobject clazz, jint tagNum, jint uid) {
- uid_t callingUid = getuid();
- int res = mTc.deleteTagData(tagNum, (uid_t)uid, callingUid);
- if (res) {
- ALOGE("%s failed, error code = %d", __func__, res);
- }
- return (jint)res;
-}
-
/*
* JNI registration.
*/
@@ -250,10 +232,6 @@
(void*)native_swapActiveStatsMap},
{"native_setPermissionForUids", "(I[I)V",
(void*)native_setPermissionForUids},
- {"native_setCounterSet", "(II)I",
- (void*)native_setCounterSet},
- {"native_deleteTagData", "(II)I",
- (void*)native_deleteTagData},
};
// clang-format on
diff --git a/service/native/TrafficController.cpp b/service/native/TrafficController.cpp
index 5981906..1cbfd94 100644
--- a/service/native/TrafficController.cpp
+++ b/service/native/TrafficController.cpp
@@ -54,7 +54,6 @@
using base::StringPrintf;
using base::unique_fd;
using bpf::BpfMap;
-using bpf::OVERFLOW_COUNTERSET;
using bpf::synchronizeKernelRCU;
using netdutils::DumpWriter;
using netdutils::getIfaceList;
@@ -239,99 +238,6 @@
return netdutils::status::ok;
}
-int TrafficController::setCounterSet(int counterSetNum, uid_t uid, uid_t callingUid) {
- if (counterSetNum < 0 || counterSetNum >= OVERFLOW_COUNTERSET) return -EINVAL;
-
- std::lock_guard guard(mMutex);
- if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
-
- // The default counter set for all uid is 0, so deleting the current counterset for that uid
- // will automatically set it to 0.
- if (counterSetNum == 0) {
- Status res = mUidCounterSetMap.deleteValue(uid);
- if (isOk(res) || (!isOk(res) && res.code() == ENOENT)) {
- return 0;
- } else {
- ALOGE("Failed to delete the counterSet: %s\n", strerror(res.code()));
- return -res.code();
- }
- }
- uint8_t tmpCounterSetNum = (uint8_t)counterSetNum;
- Status res = mUidCounterSetMap.writeValue(uid, tmpCounterSetNum, BPF_ANY);
- if (!isOk(res)) {
- ALOGE("Failed to set the counterSet: %s, fd: %d", strerror(res.code()),
- mUidCounterSetMap.getMap().get());
- return -res.code();
- }
- return 0;
-}
-
-// This method only get called by system_server when an app get uinstalled, it
-// is called inside removeUidsLocked() while holding mStatsLock. So it is safe
-// to iterate and modify the stats maps.
-int TrafficController::deleteTagData(uint32_t tag, uid_t uid, uid_t callingUid) {
- std::lock_guard guard(mMutex);
- if (!hasUpdateDeviceStatsPermission(callingUid)) return -EPERM;
-
- // First we go through the cookieTagMap to delete the target uid tag combination. Or delete all
- // the tags related to the uid if the tag is 0.
- const auto deleteMatchedCookieEntries = [uid, tag](const uint64_t& key,
- const UidTagValue& value,
- BpfMap<uint64_t, UidTagValue>& map) {
- if (value.uid == uid && (value.tag == tag || tag == 0)) {
- auto res = map.deleteValue(key);
- if (res.ok() || (res.error().code() == ENOENT)) {
- return base::Result<void>();
- }
- ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s\n", key,
- strerror(res.error().code()));
- }
- // Move forward to next cookie in the map.
- return base::Result<void>();
- };
- mCookieTagMap.iterateWithValue(deleteMatchedCookieEntries);
- // Now we go through the Tag stats map and delete the data entry with correct uid and tag
- // combination. Or all tag stats under that uid if the target tag is 0.
- const auto deleteMatchedUidTagEntries = [uid, tag](const StatsKey& key,
- BpfMap<StatsKey, StatsValue>& map) {
- if (key.uid == uid && (key.tag == tag || tag == 0)) {
- auto res = map.deleteValue(key);
- if (res.ok() || (res.error().code() == ENOENT)) {
- //Entry is deleted, use the current key to get a new nextKey;
- return base::Result<void>();
- }
- ALOGE("Failed to delete data(uid=%u, tag=%u): %s\n", key.uid, key.tag,
- strerror(res.error().code()));
- }
- return base::Result<void>();
- };
- mStatsMapB.iterate(deleteMatchedUidTagEntries);
- mStatsMapA.iterate(deleteMatchedUidTagEntries);
- // If the tag is not zero, we already deleted all the data entry required. If tag is 0, we also
- // need to delete the stats stored in uidStatsMap and counterSet map.
- if (tag != 0) return 0;
-
- auto res = mUidCounterSetMap.deleteValue(uid);
- if (!res.ok() && res.error().code() != ENOENT) {
- ALOGE("Failed to delete counterSet data(uid=%u, tag=%u): %s\n", uid, tag,
- strerror(res.error().code()));
- }
-
- auto deleteAppUidStatsEntry = [uid](const uint32_t& key,
- BpfMap<uint32_t, StatsValue>& map) -> base::Result<void> {
- if (key == uid) {
- auto res = map.deleteValue(key);
- if (res.ok() || (res.error().code() == ENOENT)) {
- return {};
- }
- ALOGE("Failed to delete data(uid=%u): %s", key, strerror(res.error().code()));
- }
- return {};
- };
- mAppUidStatsMap.iterate(deleteAppUidStatsEntry);
- return 0;
-}
-
int TrafficController::addInterface(const char* name, uint32_t ifaceIndex) {
IfaceValue iface;
if (ifaceIndex == 0) {
diff --git a/service/native/TrafficControllerTest.cpp b/service/native/TrafficControllerTest.cpp
index d0eca34..9529cae 100644
--- a/service/native/TrafficControllerTest.cpp
+++ b/service/native/TrafficControllerTest.cpp
@@ -55,7 +55,6 @@
constexpr uid_t TEST_UID3 = 98765;
constexpr uint32_t TEST_TAG = 42;
constexpr uint32_t TEST_COUNTERSET = 1;
-constexpr uint32_t DEFAULT_COUNTERSET = 0;
#define ASSERT_VALID(x) ASSERT_TRUE((x).isValid())
@@ -64,7 +63,6 @@
TrafficControllerTest() {}
TrafficController mTc;
BpfMap<uint64_t, UidTagValue> mFakeCookieTagMap;
- BpfMap<uint32_t, uint8_t> mFakeUidCounterSetMap;
BpfMap<uint32_t, StatsValue> mFakeAppUidStatsMap;
BpfMap<StatsKey, StatsValue> mFakeStatsMapA;
BpfMap<uint32_t, uint8_t> mFakeConfigurationMap;
@@ -79,10 +77,6 @@
TEST_MAP_SIZE, 0));
ASSERT_VALID(mFakeCookieTagMap);
- mFakeUidCounterSetMap.reset(
- createMap(BPF_MAP_TYPE_HASH, sizeof(uint32_t), sizeof(uint8_t), TEST_MAP_SIZE, 0));
- ASSERT_VALID(mFakeUidCounterSetMap);
-
mFakeAppUidStatsMap.reset(createMap(BPF_MAP_TYPE_HASH, sizeof(uint32_t), sizeof(StatsValue),
TEST_MAP_SIZE, 0));
ASSERT_VALID(mFakeAppUidStatsMap);
@@ -104,8 +98,6 @@
mTc.mCookieTagMap.reset(dupFd(mFakeCookieTagMap.getMap()));
ASSERT_VALID(mTc.mCookieTagMap);
- mTc.mUidCounterSetMap.reset(dupFd(mFakeUidCounterSetMap.getMap()));
- ASSERT_VALID(mTc.mUidCounterSetMap);
mTc.mAppUidStatsMap.reset(dupFd(mFakeAppUidStatsMap.getMap()));
ASSERT_VALID(mTc.mAppUidStatsMap);
mTc.mStatsMapA.reset(dupFd(mFakeStatsMapA.getMap()));
@@ -132,8 +124,6 @@
EXPECT_RESULT_OK(mFakeCookieTagMap.writeValue(cookie, cookieMapkey, BPF_ANY));
*key = {.uid = uid, .tag = tag, .counterSet = TEST_COUNTERSET, .ifaceIndex = 1};
StatsValue statsMapValue = {.rxPackets = 1, .rxBytes = 100};
- uint8_t counterSet = TEST_COUNTERSET;
- EXPECT_RESULT_OK(mFakeUidCounterSetMap.writeValue(uid, counterSet, BPF_ANY));
EXPECT_RESULT_OK(mFakeStatsMapA.writeValue(*key, statsMapValue, BPF_ANY));
key->tag = 0;
EXPECT_RESULT_OK(mFakeStatsMapA.writeValue(*key, statsMapValue, BPF_ANY));
@@ -259,9 +249,6 @@
EXPECT_RESULT_OK(cookieMapResult);
EXPECT_EQ(uid, cookieMapResult.value().uid);
EXPECT_EQ(tag, cookieMapResult.value().tag);
- Result<uint8_t> counterSetResult = mFakeUidCounterSetMap.readValue(uid);
- EXPECT_RESULT_OK(counterSetResult);
- EXPECT_EQ(TEST_COUNTERSET, counterSetResult.value());
Result<StatsValue> statsMapResult = mFakeStatsMapA.readValue(tagStatsMapKey);
EXPECT_RESULT_OK(statsMapResult);
EXPECT_EQ((uint64_t)1, statsMapResult.value().rxPackets);
@@ -289,157 +276,6 @@
};
-TEST_F(TrafficControllerTest, TestSetCounterSet) {
- uid_t callingUid = TEST_UID2;
- addPrivilegedUid(callingUid);
- ASSERT_EQ(0, mTc.setCounterSet(TEST_COUNTERSET, TEST_UID, callingUid));
- uid_t uid = TEST_UID;
- Result<uint8_t> counterSetResult = mFakeUidCounterSetMap.readValue(uid);
- ASSERT_RESULT_OK(counterSetResult);
- ASSERT_EQ(TEST_COUNTERSET, counterSetResult.value());
- ASSERT_EQ(0, mTc.setCounterSet(DEFAULT_COUNTERSET, TEST_UID, callingUid));
- ASSERT_FALSE(mFakeUidCounterSetMap.readValue(uid).ok());
- expectMapEmpty(mFakeUidCounterSetMap);
-}
-
-TEST_F(TrafficControllerTest, TestSetCounterSetWithoutPermission) {
- ASSERT_EQ(-EPERM, mTc.setCounterSet(TEST_COUNTERSET, TEST_UID, TEST_UID2));
- uid_t uid = TEST_UID;
- ASSERT_FALSE(mFakeUidCounterSetMap.readValue(uid).ok());
- expectMapEmpty(mFakeUidCounterSetMap);
-}
-
-TEST_F(TrafficControllerTest, TestSetInvalidCounterSet) {
- uid_t callingUid = TEST_UID2;
- addPrivilegedUid(callingUid);
- ASSERT_GT(0, mTc.setCounterSet(OVERFLOW_COUNTERSET, TEST_UID, callingUid));
- uid_t uid = TEST_UID;
- ASSERT_FALSE(mFakeUidCounterSetMap.readValue(uid).ok());
- expectMapEmpty(mFakeUidCounterSetMap);
-}
-
-TEST_F(TrafficControllerTest, TestDeleteTagDataWithoutPermission) {
- uint64_t cookie = 1;
- uid_t uid = TEST_UID;
- uint32_t tag = TEST_TAG;
- StatsKey tagStatsMapKey;
- populateFakeStats(cookie, uid, tag, &tagStatsMapKey);
- ASSERT_EQ(-EPERM, mTc.deleteTagData(0, TEST_UID, TEST_UID2));
-
- expectFakeStatsUnchanged(cookie, tag, uid, tagStatsMapKey);
-}
-
-TEST_F(TrafficControllerTest, TestDeleteTagData) {
- uid_t callingUid = TEST_UID2;
- addPrivilegedUid(callingUid);
- uint64_t cookie = 1;
- uid_t uid = TEST_UID;
- uint32_t tag = TEST_TAG;
- StatsKey tagStatsMapKey;
- populateFakeStats(cookie, uid, tag, &tagStatsMapKey);
- ASSERT_EQ(0, mTc.deleteTagData(TEST_TAG, TEST_UID, callingUid));
- ASSERT_FALSE(mFakeCookieTagMap.readValue(cookie).ok());
- Result<uint8_t> counterSetResult = mFakeUidCounterSetMap.readValue(uid);
- ASSERT_RESULT_OK(counterSetResult);
- ASSERT_EQ(TEST_COUNTERSET, counterSetResult.value());
- ASSERT_FALSE(mFakeStatsMapA.readValue(tagStatsMapKey).ok());
- tagStatsMapKey.tag = 0;
- Result<StatsValue> statsMapResult = mFakeStatsMapA.readValue(tagStatsMapKey);
- ASSERT_RESULT_OK(statsMapResult);
- ASSERT_EQ((uint64_t)1, statsMapResult.value().rxPackets);
- ASSERT_EQ((uint64_t)100, statsMapResult.value().rxBytes);
- auto appStatsResult = mFakeAppUidStatsMap.readValue(TEST_UID);
- ASSERT_RESULT_OK(appStatsResult);
- ASSERT_EQ((uint64_t)1, appStatsResult.value().rxPackets);
- ASSERT_EQ((uint64_t)100, appStatsResult.value().rxBytes);
-}
-
-TEST_F(TrafficControllerTest, TestDeleteAllUidData) {
- uid_t callingUid = TEST_UID2;
- addPrivilegedUid(callingUid);
- uint64_t cookie = 1;
- uid_t uid = TEST_UID;
- uint32_t tag = TEST_TAG;
- StatsKey tagStatsMapKey;
- populateFakeStats(cookie, uid, tag, &tagStatsMapKey);
- ASSERT_EQ(0, mTc.deleteTagData(0, TEST_UID, callingUid));
- ASSERT_FALSE(mFakeCookieTagMap.readValue(cookie).ok());
- ASSERT_FALSE(mFakeUidCounterSetMap.readValue(uid).ok());
- ASSERT_FALSE(mFakeStatsMapA.readValue(tagStatsMapKey).ok());
- tagStatsMapKey.tag = 0;
- ASSERT_FALSE(mFakeStatsMapA.readValue(tagStatsMapKey).ok());
- ASSERT_FALSE(mFakeAppUidStatsMap.readValue(TEST_UID).ok());
-}
-
-TEST_F(TrafficControllerTest, TestDeleteDataWithTwoTags) {
- uid_t callingUid = TEST_UID2;
- addPrivilegedUid(callingUid);
- uint64_t cookie1 = 1;
- uint64_t cookie2 = 2;
- uid_t uid = TEST_UID;
- uint32_t tag1 = TEST_TAG;
- uint32_t tag2 = TEST_TAG + 1;
- StatsKey tagStatsMapKey1;
- StatsKey tagStatsMapKey2;
- populateFakeStats(cookie1, uid, tag1, &tagStatsMapKey1);
- populateFakeStats(cookie2, uid, tag2, &tagStatsMapKey2);
- ASSERT_EQ(0, mTc.deleteTagData(TEST_TAG, TEST_UID, callingUid));
- ASSERT_FALSE(mFakeCookieTagMap.readValue(cookie1).ok());
- Result<UidTagValue> cookieMapResult = mFakeCookieTagMap.readValue(cookie2);
- ASSERT_RESULT_OK(cookieMapResult);
- ASSERT_EQ(TEST_UID, cookieMapResult.value().uid);
- ASSERT_EQ(TEST_TAG + 1, cookieMapResult.value().tag);
- Result<uint8_t> counterSetResult = mFakeUidCounterSetMap.readValue(uid);
- ASSERT_RESULT_OK(counterSetResult);
- ASSERT_EQ(TEST_COUNTERSET, counterSetResult.value());
- ASSERT_FALSE(mFakeStatsMapA.readValue(tagStatsMapKey1).ok());
- Result<StatsValue> statsMapResult = mFakeStatsMapA.readValue(tagStatsMapKey2);
- ASSERT_RESULT_OK(statsMapResult);
- ASSERT_EQ((uint64_t)1, statsMapResult.value().rxPackets);
- ASSERT_EQ((uint64_t)100, statsMapResult.value().rxBytes);
-}
-
-TEST_F(TrafficControllerTest, TestDeleteDataWithTwoUids) {
- uid_t callingUid = TEST_UID2;
- addPrivilegedUid(callingUid);
- uint64_t cookie1 = 1;
- uint64_t cookie2 = 2;
- uid_t uid1 = TEST_UID;
- uid_t uid2 = TEST_UID + 1;
- uint32_t tag = TEST_TAG;
- StatsKey tagStatsMapKey1;
- StatsKey tagStatsMapKey2;
- populateFakeStats(cookie1, uid1, tag, &tagStatsMapKey1);
- populateFakeStats(cookie2, uid2, tag, &tagStatsMapKey2);
-
- // Delete the stats of one of the uid. Check if it is properly collected by
- // removedStats.
- ASSERT_EQ(0, mTc.deleteTagData(0, uid2, callingUid));
- ASSERT_FALSE(mFakeCookieTagMap.readValue(cookie2).ok());
- Result<uint8_t> counterSetResult = mFakeUidCounterSetMap.readValue(uid1);
- ASSERT_RESULT_OK(counterSetResult);
- ASSERT_EQ(TEST_COUNTERSET, counterSetResult.value());
- ASSERT_FALSE(mFakeUidCounterSetMap.readValue(uid2).ok());
- ASSERT_FALSE(mFakeStatsMapA.readValue(tagStatsMapKey2).ok());
- tagStatsMapKey2.tag = 0;
- ASSERT_FALSE(mFakeStatsMapA.readValue(tagStatsMapKey2).ok());
- ASSERT_FALSE(mFakeAppUidStatsMap.readValue(uid2).ok());
- tagStatsMapKey1.tag = 0;
- Result<StatsValue> statsMapResult = mFakeStatsMapA.readValue(tagStatsMapKey1);
- ASSERT_RESULT_OK(statsMapResult);
- ASSERT_EQ((uint64_t)1, statsMapResult.value().rxPackets);
- ASSERT_EQ((uint64_t)100, statsMapResult.value().rxBytes);
- auto appStatsResult = mFakeAppUidStatsMap.readValue(uid1);
- ASSERT_RESULT_OK(appStatsResult);
- ASSERT_EQ((uint64_t)1, appStatsResult.value().rxPackets);
- ASSERT_EQ((uint64_t)100, appStatsResult.value().rxBytes);
-
- // Delete the stats of the other uid.
- ASSERT_EQ(0, mTc.deleteTagData(0, uid1, callingUid));
- ASSERT_FALSE(mFakeStatsMapA.readValue(tagStatsMapKey1).ok());
- ASSERT_FALSE(mFakeAppUidStatsMap.readValue(uid1).ok());
-}
-
TEST_F(TrafficControllerTest, TestUpdateOwnerMapEntry) {
uint32_t uid = TEST_UID;
ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, DENY, DENYLIST)));
diff --git a/service/native/include/TrafficController.h b/service/native/include/TrafficController.h
index e741dd6..6fe117f 100644
--- a/service/native/include/TrafficController.h
+++ b/service/native/include/TrafficController.h
@@ -40,18 +40,6 @@
*/
netdutils::Status start();
- int setCounterSet(int counterSetNum, uid_t uid, uid_t callingUid) EXCLUDES(mMutex);
-
- /*
- * When deleting a tag data, the qtaguid module will grab the spinlock of each
- * related rb_tree one by one and delete the tag information, counterSet
- * information, iface stats information and uid stats information one by one.
- * The new eBPF implementation is done similiarly by removing the entry on
- * each map one by one. And deleting processes are also protected by the
- * spinlock of the map. So no additional lock is required.
- */
- int deleteTagData(uint32_t tag, uid_t uid, uid_t callingUid) EXCLUDES(mMutex);
-
/*
* Swap the stats map config from current active stats map to the idle one.
*/
diff --git a/service/src/com/android/server/BpfNetMaps.java b/service/src/com/android/server/BpfNetMaps.java
index 7a3bab3..ddee275 100644
--- a/service/src/com/android/server/BpfNetMaps.java
+++ b/service/src/com/android/server/BpfNetMaps.java
@@ -273,32 +273,6 @@
native_setPermissionForUids(permissions, uids);
}
- /**
- * Set counter set for uid
- *
- * @param counterSet either SET_DEFAULT or SET_FOREGROUND
- * @param uid uid to foreground/background
- * @throws ServiceSpecificException in case of failure, with an error code indicating the
- * cause of the failure.
- */
- public void setCounterSet(final int counterSet, final int uid) {
- final int err = native_setCounterSet(counterSet, uid);
- maybeThrow(err, "setCounterSet failed");
- }
-
- /**
- * Reset Uid stats
- *
- * @param tag default 0
- * @param uid given uid to be clear
- * @throws ServiceSpecificException in case of failure, with an error code indicating the
- * cause of the failure.
- */
- public void deleteTagData(final int tag, final int uid) {
- final int err = native_deleteTagData(tag, uid);
- maybeThrow(err, "deleteTagData failed");
- }
-
private static native void native_init();
private native int native_addNaughtyApp(int uid);
private native int native_removeNaughtyApp(int uid);
@@ -311,6 +285,4 @@
private native int native_removeUidInterfaceRules(int[] uids);
private native int native_swapActiveStatsMap();
private native void native_setPermissionForUids(int permissions, int[] uids);
- private native int native_setCounterSet(int counterSet, int uid);
- private native int native_deleteTagData(int tag, int uid);
}
diff --git a/service/src/com/android/server/ConnectivityService.java b/service/src/com/android/server/ConnectivityService.java
index 7bb4529..6024a2a 100644
--- a/service/src/com/android/server/ConnectivityService.java
+++ b/service/src/com/android/server/ConnectivityService.java
@@ -2164,6 +2164,19 @@
}
}
+ @Override
+ @Nullable
+ public LinkProperties redactLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
+ @NonNull String packageName, @Nullable String callingAttributionTag) {
+ Objects.requireNonNull(packageName);
+ Objects.requireNonNull(lp);
+ enforceNetworkStackOrSettingsPermission();
+ if (!checkAccessPermission(-1 /* pid */, uid)) {
+ return null;
+ }
+ return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
+ }
+
private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
}
@@ -2187,13 +2200,34 @@
getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
}
+ @Override
+ public NetworkCapabilities redactNetworkCapabilitiesForPackage(@NonNull NetworkCapabilities nc,
+ int uid, @NonNull String packageName, @Nullable String callingAttributionTag) {
+ Objects.requireNonNull(nc);
+ Objects.requireNonNull(packageName);
+ enforceNetworkStackOrSettingsPermission();
+ if (!checkAccessPermission(-1 /* pid */, uid)) {
+ return null;
+ }
+ return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
+ networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
+ true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
+ callingAttributionTag);
+ }
+
@VisibleForTesting
NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
NetworkCapabilities nc, int callerPid, int callerUid) {
+ // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
+ // this would be expensive (one more permission check every time any NC callback is
+ // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
+ // it happens for some reason (e.g. the package is uninstalled while CS is trying to
+ // send the callback) it would crash the system server with NPE.
final NetworkCapabilities newNc = new NetworkCapabilities(nc);
if (!checkSettingsPermission(callerPid, callerUid)) {
newNc.setUids(null);
newNc.setSSID(null);
+ // TODO: Processes holding NETWORK_FACTORY should be able to see the underlying networks
newNc.setUnderlyingNetworks(null);
}
if (newNc.getNetworkSpecifier() != null) {
@@ -2211,7 +2245,7 @@
/**
* Wrapper used to cache the permission check results performed for the corresponding
- * app. This avoid performing multiple permission checks for different fields in
+ * app. This avoids performing multiple permission checks for different fields in
* NetworkCapabilities.
* Note: This wrapper does not support any sort of invalidation and thus must not be
* persistent or long-lived. It may only be used for the time necessary to
@@ -2339,6 +2373,8 @@
includeLocationSensitiveInfo);
final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
// Reset owner uid if not destined for the owner app.
+ // TODO : calling UID is redacted because apps should generally not know what UID is
+ // bringing up the VPN, but this should not apply to some very privileged apps like settings
if (callingUid != nc.getOwnerUid()) {
newNc.setOwnerUid(INVALID_UID);
return newNc;
@@ -2364,9 +2400,15 @@
return newNc;
}
+ @NonNull
private LinkProperties linkPropertiesRestrictedForCallerPermissions(
LinkProperties lp, int callerPid, int callerUid) {
if (lp == null) return new LinkProperties();
+ // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
+ // this would be expensive (one more permission check every time any LP callback is
+ // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
+ // it happens for some reason (e.g. the package is uninstalled while CS is trying to
+ // send the callback) it would crash the system server with NPE.
// Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
final boolean needsSanitization =
@@ -2737,6 +2779,11 @@
"ConnectivityService");
}
+ private boolean checkAccessPermission(int pid, int uid) {
+ return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
+ == PERMISSION_GRANTED;
+ }
+
/**
* Performs a strict and comprehensive check of whether a calling package is allowed to
* change the state of network, as the condition differs for pre-M, M+, and
diff --git a/tests/common/java/android/net/NetworkCapabilitiesTest.java b/tests/common/java/android/net/NetworkCapabilitiesTest.java
index 742044b..b6926a8 100644
--- a/tests/common/java/android/net/NetworkCapabilitiesTest.java
+++ b/tests/common/java/android/net/NetworkCapabilitiesTest.java
@@ -49,6 +49,7 @@
import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
import static android.net.NetworkCapabilities.SIGNAL_STRENGTH_UNSPECIFIED;
import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
+import static android.net.NetworkCapabilities.TRANSPORT_ETHERNET;
import static android.net.NetworkCapabilities.TRANSPORT_TEST;
import static android.net.NetworkCapabilities.TRANSPORT_USB;
import static android.net.NetworkCapabilities.TRANSPORT_VPN;
@@ -727,25 +728,38 @@
@Test
public void testSetNetworkSpecifierOnMultiTransportNc() {
// Sequence 1: Transport + Transport + NetworkSpecifier
- NetworkCapabilities nc1 = new NetworkCapabilities();
+ NetworkCapabilities.Builder nc1 = new NetworkCapabilities.Builder();
nc1.addTransportType(TRANSPORT_CELLULAR).addTransportType(TRANSPORT_WIFI);
- try {
- nc1.setNetworkSpecifier(CompatUtil.makeEthernetNetworkSpecifier("eth0"));
- fail("Cannot set NetworkSpecifier on a NetworkCapability with multiple transports!");
- } catch (IllegalStateException expected) {
- // empty
- }
+ final NetworkSpecifier specifier = CompatUtil.makeEthernetNetworkSpecifier("eth0");
+ assertThrows("Cannot set NetworkSpecifier on a NetworkCapability with multiple transports!",
+ IllegalStateException.class,
+ () -> nc1.build().setNetworkSpecifier(specifier));
+ assertThrows("Cannot set NetworkSpecifier on a NetworkCapability with multiple transports!",
+ IllegalStateException.class,
+ () -> nc1.setNetworkSpecifier(specifier));
// Sequence 2: Transport + NetworkSpecifier + Transport
- NetworkCapabilities nc2 = new NetworkCapabilities();
- nc2.addTransportType(TRANSPORT_CELLULAR).setNetworkSpecifier(
- CompatUtil.makeEthernetNetworkSpecifier("testtap3"));
- try {
- nc2.addTransportType(TRANSPORT_WIFI);
- fail("Cannot set a second TransportType of a network which has a NetworkSpecifier!");
- } catch (IllegalStateException expected) {
- // empty
- }
+ NetworkCapabilities.Builder nc2 = new NetworkCapabilities.Builder();
+ nc2.addTransportType(TRANSPORT_CELLULAR).setNetworkSpecifier(specifier);
+
+ assertThrows("Cannot set a second TransportType of a network which has a NetworkSpecifier!",
+ IllegalStateException.class,
+ () -> nc2.build().addTransportType(TRANSPORT_WIFI));
+ assertThrows("Cannot set a second TransportType of a network which has a NetworkSpecifier!",
+ IllegalStateException.class,
+ () -> nc2.addTransportType(TRANSPORT_WIFI));
+ }
+
+ @Test @IgnoreUpTo(Build.VERSION_CODES.R) // New behavior in updatable NetworkCapabilities (S+)
+ public void testSetNetworkSpecifierOnTestMultiTransportNc() {
+ final NetworkSpecifier specifier = CompatUtil.makeEthernetNetworkSpecifier("eth0");
+ NetworkCapabilities nc = new NetworkCapabilities.Builder()
+ .addTransportType(TRANSPORT_TEST)
+ .addTransportType(TRANSPORT_ETHERNET)
+ .setNetworkSpecifier(specifier)
+ .build();
+ // Adding a specifier did not crash with 2 transports if one is TEST
+ assertEquals(specifier, nc.getNetworkSpecifier());
}
@Test
diff --git a/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java b/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java
index 53e4ab7..ea64252 100644
--- a/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java
+++ b/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java
@@ -16,9 +16,15 @@
package android.net.cts;
+import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
+import static android.Manifest.permission.ACCESS_FINE_LOCATION;
+import static android.Manifest.permission.ACCESS_NETWORK_STATE;
import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
import static android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS;
+import static android.Manifest.permission.NETWORK_FACTORY;
import static android.Manifest.permission.NETWORK_SETTINGS;
+import static android.Manifest.permission.NETWORK_SETUP_WIZARD;
+import static android.Manifest.permission.NETWORK_STACK;
import static android.Manifest.permission.READ_DEVICE_CONFIG;
import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
import static android.content.pm.PackageManager.FEATURE_ETHERNET;
@@ -54,7 +60,9 @@
import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
import static android.net.NetworkCapabilities.TRANSPORT_TEST;
+import static android.net.NetworkCapabilities.TRANSPORT_VPN;
import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
+import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
import static android.net.cts.util.CtsNetUtils.ConnectivityActionReceiver;
import static android.net.cts.util.CtsNetUtils.HTTP_PORT;
import static android.net.cts.util.CtsNetUtils.NETWORK_CALLBACK_ACTION;
@@ -64,6 +72,7 @@
import static android.net.util.NetworkStackUtils.TEST_CAPTIVE_PORTAL_HTTPS_URL;
import static android.net.util.NetworkStackUtils.TEST_CAPTIVE_PORTAL_HTTP_URL;
import static android.os.MessageQueue.OnFileDescriptorEventListener.EVENT_INPUT;
+import static android.os.Process.INVALID_UID;
import static android.provider.Settings.Global.NETWORK_METERED_MULTIPATH_PREFERENCE;
import static android.system.OsConstants.AF_INET;
import static android.system.OsConstants.AF_INET6;
@@ -76,6 +85,7 @@
import static com.android.networkstack.apishim.ConstantsShim.BLOCKED_REASON_LOCKDOWN_VPN;
import static com.android.networkstack.apishim.ConstantsShim.BLOCKED_REASON_NONE;
import static com.android.testutils.Cleanup.testAndCleanup;
+import static com.android.testutils.DevSdkIgnoreRuleKt.SC_V2;
import static com.android.testutils.MiscAsserts.assertThrows;
import static com.android.testutils.TestNetworkTrackerKt.initTestNetwork;
import static com.android.testutils.TestPermissionUtil.runAsShell;
@@ -103,6 +113,7 @@
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
+import android.net.CaptivePortalData;
import android.net.ConnectivityManager;
import android.net.ConnectivityManager.NetworkCallback;
import android.net.ConnectivitySettingsManager;
@@ -132,6 +143,7 @@
import android.net.cts.util.CtsNetUtils;
import android.net.cts.util.CtsTetheringUtils;
import android.net.util.KeepaliveUtils;
+import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.Build;
@@ -160,6 +172,7 @@
import com.android.internal.util.ArrayUtils;
import com.android.modules.utils.build.SdkLevel;
+import com.android.net.module.util.CollectionUtils;
import com.android.networkstack.apishim.ConnectivityManagerShimImpl;
import com.android.networkstack.apishim.ConstantsShim;
import com.android.networkstack.apishim.NetworkInformationShimImpl;
@@ -554,6 +567,223 @@
}
}
+ private boolean checkPermission(String perm, int uid) {
+ return mContext.checkPermission(perm, -1 /* pid */, uid) == PERMISSION_GRANTED;
+ }
+
+ private String findPackageByPermissions(@NonNull List<String> requiredPermissions,
+ @NonNull List<String> forbiddenPermissions) throws Exception {
+ final List<PackageInfo> packageInfos =
+ mPackageManager.getInstalledPackages(GET_PERMISSIONS);
+ for (PackageInfo packageInfo : packageInfos) {
+ final int uid = mPackageManager.getPackageUid(packageInfo.packageName, 0 /* flags */);
+ if (!CollectionUtils.all(requiredPermissions, perm -> checkPermission(perm, uid))) {
+ continue;
+ }
+ if (CollectionUtils.any(forbiddenPermissions, perm -> checkPermission(perm, uid))) {
+ continue;
+ }
+
+ return packageInfo.packageName;
+ }
+ return null;
+ }
+
+ @DevSdkIgnoreRule.IgnoreUpTo(SC_V2)
+ @Test
+ public void testRedactLinkPropertiesForPackage() throws Exception {
+ final String groundedPkg = findPackageByPermissions(
+ List.of(), /* requiredPermissions */
+ List.of(ACCESS_NETWORK_STATE) /* forbiddenPermissions */);
+ assertNotNull("Couldn't find any package without ACCESS_NETWORK_STATE", groundedPkg);
+ final int groundedUid = mPackageManager.getPackageUid(groundedPkg, 0 /* flags */);
+
+ final String normalPkg = findPackageByPermissions(
+ List.of(ACCESS_NETWORK_STATE) /* requiredPermissions */,
+ List.of(NETWORK_SETTINGS, NETWORK_STACK,
+ PERMISSION_MAINLINE_NETWORK_STACK) /* forbiddenPermissions */);
+ assertNotNull("Couldn't find any package with ACCESS_NETWORK_STATE but"
+ + " without NETWORK_SETTINGS", normalPkg);
+ final int normalUid = mPackageManager.getPackageUid(normalPkg, 0 /* flags */);
+
+ // There are some privileged packages on the system, like the phone process, the network
+ // stack and the system server.
+ final String privilegedPkg = findPackageByPermissions(
+ List.of(ACCESS_NETWORK_STATE, NETWORK_SETTINGS), /* requiredPermissions */
+ List.of() /* forbiddenPermissions */);
+ assertNotNull("Couldn't find a package with sufficient permissions", privilegedPkg);
+ final int privilegedUid = mPackageManager.getPackageUid(privilegedPkg, 0);
+
+ // Set parcelSensitiveFields to true to preserve CaptivePortalApiUrl & CaptivePortalData
+ // when parceling.
+ final LinkProperties lp = new LinkProperties(new LinkProperties(),
+ true /* parcelSensitiveFields */);
+ final Uri capportUrl = Uri.parse("https://capport.example.com/api");
+ final CaptivePortalData capportData = new CaptivePortalData.Builder().build();
+ final int mtu = 12345;
+ lp.setMtu(mtu);
+ lp.setCaptivePortalApiUrl(capportUrl);
+ lp.setCaptivePortalData(capportData);
+
+ // No matter what the given uid is, a SecurityException will be thrown if the caller
+ // doesn't hold the NETWORK_SETTINGS permission.
+ assertThrows(SecurityException.class,
+ () -> mCm.redactLinkPropertiesForPackage(lp, groundedUid, groundedPkg));
+ assertThrows(SecurityException.class,
+ () -> mCm.redactLinkPropertiesForPackage(lp, normalUid, normalPkg));
+ assertThrows(SecurityException.class,
+ () -> mCm.redactLinkPropertiesForPackage(lp, privilegedUid, privilegedPkg));
+
+ runAsShell(NETWORK_SETTINGS, () -> {
+ // No matter what the given uid is, if the given LinkProperties is null, then
+ // NullPointerException will be thrown.
+ assertThrows(NullPointerException.class,
+ () -> mCm.redactLinkPropertiesForPackage(null, groundedUid, groundedPkg));
+ assertThrows(NullPointerException.class,
+ () -> mCm.redactLinkPropertiesForPackage(null, normalUid, normalPkg));
+ assertThrows(NullPointerException.class,
+ () -> mCm.redactLinkPropertiesForPackage(null, privilegedUid, privilegedPkg));
+
+ // Make sure null is returned for a UID without ACCESS_NETWORK_STATE.
+ assertNull(mCm.redactLinkPropertiesForPackage(lp, groundedUid, groundedPkg));
+
+ // CaptivePortalApiUrl & CaptivePortalData will be set to null if given uid doesn't hold
+ // the NETWORK_SETTINGS permission.
+ assertNull(mCm.redactLinkPropertiesForPackage(lp, normalUid, normalPkg)
+ .getCaptivePortalApiUrl());
+ assertNull(mCm.redactLinkPropertiesForPackage(lp, normalUid, normalPkg)
+ .getCaptivePortalData());
+ // MTU is not sensitive and is not redacted.
+ assertEquals(mtu, mCm.redactLinkPropertiesForPackage(lp, normalUid, normalPkg)
+ .getMtu());
+
+ // CaptivePortalApiUrl & CaptivePortalData will be preserved if the given uid holds the
+ // NETWORK_SETTINGS permission.
+ assertEquals(capportUrl,
+ mCm.redactLinkPropertiesForPackage(lp, privilegedUid, privilegedPkg)
+ .getCaptivePortalApiUrl());
+ assertEquals(capportData,
+ mCm.redactLinkPropertiesForPackage(lp, privilegedUid, privilegedPkg)
+ .getCaptivePortalData());
+ });
+ }
+
+ private NetworkCapabilities redactNc(@NonNull final NetworkCapabilities nc, int uid,
+ @NonNull String packageName) {
+ return mCm.redactNetworkCapabilitiesForPackage(nc, uid, packageName);
+ }
+
+ @DevSdkIgnoreRule.IgnoreUpTo(SC_V2)
+ @Test
+ public void testRedactNetworkCapabilitiesForPackage() throws Exception {
+ final String groundedPkg = findPackageByPermissions(
+ List.of(), /* requiredPermissions */
+ List.of(ACCESS_NETWORK_STATE) /* forbiddenPermissions */);
+ assertNotNull("Couldn't find any package without ACCESS_NETWORK_STATE", groundedPkg);
+ final int groundedUid = mPackageManager.getPackageUid(groundedPkg, 0 /* flags */);
+
+ // A package which doesn't have any of the permissions below, but has NETWORK_STATE.
+ // There should be a number of packages like this on the device; AOSP has many,
+ // including contacts, webview, the keyboard, pacprocessor, messaging.
+ final String normalPkg = findPackageByPermissions(
+ List.of(ACCESS_NETWORK_STATE) /* requiredPermissions */,
+ List.of(NETWORK_SETTINGS, NETWORK_FACTORY, NETWORK_SETUP_WIZARD,
+ NETWORK_STACK, PERMISSION_MAINLINE_NETWORK_STACK,
+ ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION) /* forbiddenPermissions */);
+ assertNotNull("Can't find a package with ACCESS_NETWORK_STATE but without any of"
+ + " the forbidden permissions", normalPkg);
+ final int normalUid = mPackageManager.getPackageUid(normalPkg, 0 /* flags */);
+
+ // There are some privileged packages on the system, like the phone process, the network
+ // stack and the system server.
+ final String privilegedPkg = findPackageByPermissions(
+ List.of(ACCESS_NETWORK_STATE, NETWORK_SETTINGS, NETWORK_FACTORY,
+ ACCESS_FINE_LOCATION), /* requiredPermissions */
+ List.of() /* forbiddenPermissions */);
+ assertNotNull("Couldn't find a package with sufficient permissions", privilegedPkg);
+ final int privilegedUid = mPackageManager.getPackageUid(privilegedPkg, 0);
+
+ final Set<Range<Integer>> uids = new ArraySet<>();
+ uids.add(new Range<>(10000, 10100));
+ uids.add(new Range<>(10200, 10300));
+ final String ssid = "My-WiFi";
+ // This test will set underlying networks in the capabilities to redact to see if they
+ // are appropriately redacted, so fetch the default network to put in there as an example.
+ final Network defaultNetwork = mCm.getActiveNetwork();
+ assertNotNull("CTS requires a working Internet connection", defaultNetwork);
+ final int subId1 = 1;
+ final int subId2 = 2;
+ final int[] administratorUids = {normalUid};
+ final String bssid = "location sensitive";
+ final int rssi = 43; // not location sensitive
+ final WifiInfo wifiInfo = new WifiInfo.Builder()
+ .setBssid(bssid)
+ .setRssi(rssi)
+ .build();
+ final NetworkCapabilities nc = new NetworkCapabilities.Builder()
+ .setUids(uids)
+ .setSsid(ssid)
+ .setUnderlyingNetworks(List.of(defaultNetwork))
+ .setSubscriptionIds(Set.of(subId1, subId2))
+ .setAdministratorUids(administratorUids)
+ .setOwnerUid(normalUid)
+ .setTransportInfo(wifiInfo)
+ .build();
+
+ // No matter what the given uid is, a SecurityException will be thrown if the caller
+ // doesn't hold the NETWORK_SETTINGS permission.
+ assertThrows(SecurityException.class, () -> redactNc(nc, groundedUid, groundedPkg));
+ assertThrows(SecurityException.class, () -> redactNc(nc, normalUid, normalPkg));
+ assertThrows(SecurityException.class, () -> redactNc(nc, privilegedUid, privilegedPkg));
+
+ runAsShell(NETWORK_SETTINGS, () -> {
+ // Make sure that the NC is null if the package doesn't hold ACCESS_NETWORK_STATE.
+ assertNull(redactNc(nc, groundedUid, groundedPkg));
+
+ // Uids, ssid, underlying networks & subscriptionIds will be redacted if the given uid
+ // doesn't hold the associated permissions. The wifi transport info is also suitably
+ // redacted.
+ final NetworkCapabilities redactedNormal = redactNc(nc, normalUid, normalPkg);
+ assertNull(redactedNormal.getUids());
+ assertNull(redactedNormal.getSsid());
+ assertNull(redactedNormal.getUnderlyingNetworks());
+ assertEquals(0, redactedNormal.getSubscriptionIds().size());
+ assertEquals(WifiInfo.DEFAULT_MAC_ADDRESS,
+ ((WifiInfo) redactedNormal.getTransportInfo()).getBSSID());
+ assertEquals(rssi, ((WifiInfo) redactedNormal.getTransportInfo()).getRssi());
+
+ // Uids, ssid, underlying networks & subscriptionIds will be preserved if the given uid
+ // holds the associated permissions.
+ final NetworkCapabilities redactedPrivileged =
+ redactNc(nc, privilegedUid, privilegedPkg);
+ assertEquals(uids, redactedPrivileged.getUids());
+ assertEquals(ssid, redactedPrivileged.getSsid());
+ assertEquals(List.of(defaultNetwork), redactedPrivileged.getUnderlyingNetworks());
+ assertEquals(Set.of(subId1, subId2), redactedPrivileged.getSubscriptionIds());
+ assertEquals(bssid, ((WifiInfo) redactedPrivileged.getTransportInfo()).getBSSID());
+ assertEquals(rssi, ((WifiInfo) redactedPrivileged.getTransportInfo()).getRssi());
+
+ // The owner uid is only preserved when the network is a VPN and the uid is the
+ // same as the owner uid.
+ nc.addTransportType(TRANSPORT_VPN);
+ assertEquals(normalUid, redactNc(nc, normalUid, normalPkg).getOwnerUid());
+ assertEquals(INVALID_UID, redactNc(nc, privilegedUid, privilegedPkg).getOwnerUid());
+ nc.removeTransportType(TRANSPORT_VPN);
+
+ // If the given uid doesn't hold location permissions, the owner uid will be set to
+ // INVALID_UID even when sent to that UID (this avoids a wifi suggestor knowing where
+ // the device is by virtue of the device connecting to its own network).
+ assertEquals(INVALID_UID, redactNc(nc, normalUid, normalPkg).getOwnerUid());
+
+ // If the given uid holds location permissions, the owner uid is preserved. This works
+ // because the shell holds ACCESS_FINE_LOCATION.
+ final int[] administratorUids2 = { privilegedUid };
+ nc.setAdministratorUids(administratorUids2);
+ nc.setOwnerUid(privilegedUid);
+ assertEquals(privilegedUid, redactNc(nc, privilegedUid, privilegedPkg).getOwnerUid());
+ });
+ }
+
/**
* Tests that connections can be opened on WiFi and cellphone networks,
* and that they are made from different IP addresses.
diff --git a/tests/unit/java/android/net/Ikev2VpnProfileTest.java b/tests/unit/java/android/net/Ikev2VpnProfileTest.java
index c3d3bf7..8559c20 100644
--- a/tests/unit/java/android/net/Ikev2VpnProfileTest.java
+++ b/tests/unit/java/android/net/Ikev2VpnProfileTest.java
@@ -16,6 +16,8 @@
package android.net;
+import static com.android.testutils.DevSdkIgnoreRuleKt.SC_V2;
+
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@@ -264,8 +266,8 @@
}
- // TODO: Refer to Build.VERSION_CODES.SC_V2 when it's available in AOSP
- @DevSdkIgnoreRule.IgnoreUpTo(32)
+ // TODO: Refer to Build.VERSION_CODES.SC_V2 when it's available in AOSP and mainline branch
+ @DevSdkIgnoreRule.IgnoreUpTo(SC_V2)
@Test
public void testBuildExcludeLocalRoutesSet() throws Exception {
final Ikev2VpnProfile.Builder builder = getBuilderWithDefaultOptions();