Check network slicing declaration for network request

When the application wants to request network with
NET_CAPABILITY_PRIORITIZE_BANDWIDTH or
NET_CAPABILITY_PRIORITIZE_LATENCY, it has to declare
PackageManager.PROPERTY_NETWORK_SLICE_DECLARATIONS property and also
adds the declaration in a separate XML files. Otherwise, the request
will fail with a SecurityException being thrown.

Test: atest FrameworksNetTests CtsNetTestCases
Bug: 266524688
Change-Id: I6affc857b803211517368da288e1b2fdc06a955b
diff --git a/service/src/com/android/server/ConnectivityService.java b/service/src/com/android/server/ConnectivityService.java
index e32ea8f..3a38f45 100755
--- a/service/src/com/android/server/ConnectivityService.java
+++ b/service/src/com/android/server/ConnectivityService.java
@@ -113,6 +113,7 @@
 import android.app.BroadcastOptions;
 import android.app.PendingIntent;
 import android.app.admin.DevicePolicyManager;
+import android.app.compat.CompatChanges;
 import android.app.usage.NetworkStatsManager;
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
@@ -121,6 +122,7 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.pm.PackageManager;
+import android.content.res.XmlResourceParser;
 import android.database.ContentObserver;
 import android.net.CaptivePortal;
 import android.net.CaptivePortalData;
@@ -195,6 +197,7 @@
 import android.net.Uri;
 import android.net.VpnManager;
 import android.net.VpnTransportInfo;
+import android.net.connectivity.ConnectivityCompatChanges;
 import android.net.metrics.IpConnectivityLog;
 import android.net.metrics.NetworkEvent;
 import android.net.netd.aidl.NativeUidRangeConfig;
@@ -269,6 +272,7 @@
 import com.android.networkstack.apishim.ConstantsShim;
 import com.android.networkstack.apishim.common.BroadcastOptionsShim;
 import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
+import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
 import com.android.server.connectivity.AutodestructReference;
 import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
 import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
@@ -279,6 +283,7 @@
 import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
 import com.android.server.connectivity.DscpPolicyTracker;
 import com.android.server.connectivity.FullScore;
+import com.android.server.connectivity.InvalidTagException;
 import com.android.server.connectivity.KeepaliveTracker;
 import com.android.server.connectivity.LingerMonitor;
 import com.android.server.connectivity.MockableSystemProperties;
@@ -300,6 +305,8 @@
 
 import libcore.io.IoUtils;
 
+import org.xmlpull.v1.XmlPullParserException;
+
 import java.io.FileDescriptor;
 import java.io.IOException;
 import java.io.PrintWriter;
@@ -902,6 +909,13 @@
     // Only the handler thread is allowed to access this field.
     private long mIngressRateLimit = -1;
 
+    // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
+    // value can be accessed from both handler thread and any random binder thread. Therefore,
+    // accessing this value requires holding a lock.
+    @GuardedBy("mSelfCertifiedCapabilityCache")
+    private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
+            mSelfCertifiedCapabilityCache = new HashMap<>();
+
     /**
      * Implements support for the legacy "one network per network type" model.
      *
@@ -1452,6 +1466,20 @@
         public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
             return BroadcastOptionsShimImpl.newInstance(options);
         }
+
+        /**
+         * Wrapper method for
+         * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
+         *
+         * @param changeId    The ID of the compatibility change in question.
+         * @param packageName The package name of the app in question.
+         * @param user        The user that the operation is done for.
+         * @return {@code true} if the change is enabled for the specified package.
+         */
+        public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
+                @NonNull final UserHandle user) {
+            return CompatChanges.isChangeEnabled(changeId, packageName, user);
+        }
     }
 
     public ConnectivityService(Context context) {
@@ -6319,6 +6347,11 @@
         if (isMappedInOemNetworkPreference(packageName)) {
             handleSetOemNetworkPreference(mOemNetworkPreferences, null);
         }
+
+        // Invalidates cache entry when the package is updated.
+        synchronized (mSelfCertifiedCapabilityCache) {
+            mSelfCertifiedCapabilityCache.remove(packageName);
+        }
     }
 
     private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
@@ -6947,8 +6980,69 @@
                 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
     }
 
+    private boolean shouldCheckCapabilitiesDeclaration(
+            @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
+            @NonNull final String callingPackageName) {
+        final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
+        // Only run the check if the change is enabled.
+        if (!mDeps.isChangeEnabled(
+                ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
+                callingPackageName, user)) {
+            return false;
+        }
+
+        return networkCapabilities.hasCapability(
+                NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
+                || networkCapabilities.hasCapability(
+                NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
+    }
+
+    private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
+            @NonNull final NetworkCapabilities networkCapabilities) {
+        // This check is added to fix the linter error for "current min is 30", which is not going
+        // to happen because Connectivity service always run in S+.
+        if (!SdkLevel.isAtLeastS()) {
+            Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
+            return;
+        }
+        ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
+        try {
+            synchronized (mSelfCertifiedCapabilityCache) {
+                applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
+                        callerPackageName);
+                if (applicationNetworkCapabilities == null) {
+                    final PackageManager packageManager = mContext.getPackageManager();
+                    final PackageManager.Property networkSliceProperty = packageManager.getProperty(
+                            ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
+                            callerPackageName
+                    );
+                    final XmlResourceParser parser = packageManager
+                            .getResourcesForApplication(callerPackageName)
+                            .getXml(networkSliceProperty.getResourceId());
+                    applicationNetworkCapabilities =
+                            ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
+                    mSelfCertifiedCapabilityCache.put(callerPackageName,
+                            applicationNetworkCapabilities);
+                }
+
+            }
+        } catch (PackageManager.NameNotFoundException ne) {
+            throw new SecurityException(
+                    "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
+                            + " property");
+        } catch (XmlPullParserException | IOException | InvalidTagException e) {
+            throw new SecurityException(e.getMessage());
+        }
+
+        applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
+                networkCapabilities);
+    }
     private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
             String callingPackageName, String callingAttributionTag, final int callingUid) {
+        if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
+                callingPackageName)) {
+            enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
+        }
         if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
             // For T+ devices, callers with carrier privilege could request with CBS capabilities.
             if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
diff --git a/service/src/com/android/server/connectivity/ApplicationSelfCertifiedNetworkCapabilities.java b/service/src/com/android/server/connectivity/ApplicationSelfCertifiedNetworkCapabilities.java
new file mode 100644
index 0000000..76e966f
--- /dev/null
+++ b/service/src/com/android/server/connectivity/ApplicationSelfCertifiedNetworkCapabilities.java
@@ -0,0 +1,209 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.connectivity;
+
+
+import android.annotation.NonNull;
+import android.net.NetworkCapabilities;
+import android.util.Log;
+
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+
+import java.io.IOException;
+import java.util.ArrayDeque;
+
+
+/**
+ * The class for parsing and checking the self-declared application network capabilities.
+ *
+ * ApplicationSelfCertifiedNetworkCapabilities is an immutable class that
+ * can parse the self-declared application network capabilities in the application resources. The
+ * class also provides a helper method to check whether the requested network capabilities
+ * already self-declared.
+ */
+public final class ApplicationSelfCertifiedNetworkCapabilities {
+
+    public static final String PRIORITIZE_LATENCY = "NET_CAPABILITY_PRIORITIZE_LATENCY";
+    public static final String PRIORITIZE_BANDWIDTH = "NET_CAPABILITY_PRIORITIZE_BANDWIDTH";
+
+    private static final String TAG =
+            ApplicationSelfCertifiedNetworkCapabilities.class.getSimpleName();
+    private static final String NETWORK_CAPABILITIES_DECLARATION_TAG =
+            "network-capabilities-declaration";
+    private static final String USES_NETWORK_CAPABILITY_TAG = "uses-network-capability";
+    private static final String NAME_TAG = "name";
+
+    private long mRequestedNetworkCapabilities = 0;
+
+    /**
+     * Creates {@link ApplicationSelfCertifiedNetworkCapabilities} from a xml parser.
+     *
+     * <p> Here is an example of the xml syntax:
+     *
+     * <pre>
+     * {@code
+     *  <network-capabilities-declaration xmlns:android="http://schemas.android.com/apk/res/android">
+     *     <uses-network-capability android:name="NET_CAPABILITY_PRIORITIZE_LATENCY"/>
+     *     <uses-network-capability android:name="NET_CAPABILITY_PRIORITIZE_BANDWIDTH"/>
+     * </network-capabilities-declaration>
+     * }
+     * </pre>
+     * <p>
+     *
+     * @param xmlParser The underlying {@link XmlPullParser} that will read the xml.
+     * @return An ApplicationSelfCertifiedNetworkCapabilities object.
+     * @throws InvalidTagException    if the capabilities in xml config contains invalid tag.
+     * @throws XmlPullParserException if xml parsing failed.
+     * @throws IOException            if unable to read the xml file properly.
+     */
+    @NonNull
+    public static ApplicationSelfCertifiedNetworkCapabilities createFromXml(
+            @NonNull final XmlPullParser xmlParser)
+            throws InvalidTagException, XmlPullParserException, IOException {
+        return new ApplicationSelfCertifiedNetworkCapabilities(parseXml(xmlParser));
+    }
+
+    private static long parseXml(@NonNull final XmlPullParser xmlParser)
+            throws InvalidTagException, XmlPullParserException, IOException {
+        long requestedNetworkCapabilities = 0;
+        final ArrayDeque<String> openTags = new ArrayDeque<>();
+
+        while (checkedNextTag(xmlParser, openTags) != XmlPullParser.START_TAG) {
+            continue;
+        }
+
+        // Validates the tag is "network-capabilities-declaration"
+        if (!xmlParser.getName().equals(NETWORK_CAPABILITIES_DECLARATION_TAG)) {
+            throw new InvalidTagException("Invalid tag: " + xmlParser.getName());
+        }
+
+        checkedNextTag(xmlParser, openTags);
+        int eventType = xmlParser.getEventType();
+        while (eventType != XmlPullParser.END_DOCUMENT) {
+            switch (eventType) {
+                case XmlPullParser.START_TAG:
+                    // USES_NETWORK_CAPABILITY_TAG should directly be declared under
+                    // NETWORK_CAPABILITIES_DECLARATION_TAG.
+                    if (xmlParser.getName().equals(USES_NETWORK_CAPABILITY_TAG)
+                            && openTags.size() == 1) {
+                        int capability = parseDeclarationTag(xmlParser);
+                        if (capability >= 0) {
+                            requestedNetworkCapabilities |= 1L << capability;
+                        }
+                    } else {
+                        Log.w(TAG, "Unknown tag: " + xmlParser.getName() + " ,tags stack size: "
+                                + openTags.size());
+                    }
+                    break;
+                default:
+                    break;
+            }
+            eventType = checkedNextTag(xmlParser, openTags);
+        }
+        // Checks all the tags are parsed.
+        if (!openTags.isEmpty()) {
+            throw new InvalidTagException("Unbalanced tag: " + openTags.peek());
+        }
+        return requestedNetworkCapabilities;
+    }
+
+    private static int parseDeclarationTag(@NonNull final XmlPullParser xmlParser) {
+        String name = null;
+        for (int i = 0; i < xmlParser.getAttributeCount(); i++) {
+            final String attrName = xmlParser.getAttributeName(i);
+            if (attrName.equals(NAME_TAG)) {
+                name = xmlParser.getAttributeValue(i);
+            } else {
+                Log.w(TAG, "Unknown attribute name: " + attrName);
+            }
+        }
+        if (name != null) {
+            switch (name) {
+                case PRIORITIZE_BANDWIDTH:
+                    return NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH;
+                case PRIORITIZE_LATENCY:
+                    return NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY;
+                default:
+                    Log.w(TAG, "Unknown capability declaration name: " + name);
+            }
+        } else {
+            Log.w(TAG, "uses-network-capability name must be specified");
+        }
+        // Invalid capability
+        return -1;
+    }
+
+    private static int checkedNextTag(@NonNull final XmlPullParser xmlParser,
+            @NonNull final ArrayDeque<String> openTags)
+            throws XmlPullParserException, IOException, InvalidTagException {
+        if (xmlParser.getEventType() == XmlPullParser.START_TAG) {
+            openTags.addFirst(xmlParser.getName());
+        } else if (xmlParser.getEventType() == XmlPullParser.END_TAG) {
+            if (!openTags.isEmpty() && openTags.peekFirst().equals(xmlParser.getName())) {
+                openTags.removeFirst();
+            } else {
+                throw new InvalidTagException("Unbalanced tag: " + xmlParser.getName());
+            }
+        }
+        return xmlParser.next();
+    }
+
+    private ApplicationSelfCertifiedNetworkCapabilities(long requestedNetworkCapabilities) {
+        mRequestedNetworkCapabilities = requestedNetworkCapabilities;
+    }
+
+    /**
+     * Enforces self-certified capabilities are declared.
+     *
+     * @param networkCapabilities the input NetworkCapabilities to check against.
+     * @throws SecurityException if the capabilities are not properly self-declared.
+     */
+    public void enforceSelfCertifiedNetworkCapabilitiesDeclared(
+            @NonNull final NetworkCapabilities networkCapabilities) {
+        if (networkCapabilities.hasCapability(
+                NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
+                && !hasPrioritizeBandwidth()) {
+            throw new SecurityException(
+                    "Missing " + ApplicationSelfCertifiedNetworkCapabilities.PRIORITIZE_BANDWIDTH
+                            + " declaration");
+        }
+        if (networkCapabilities.hasCapability(
+                NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY)
+                && !hasPrioritizeLatency()) {
+            throw new SecurityException(
+                    "Missing " + ApplicationSelfCertifiedNetworkCapabilities.PRIORITIZE_LATENCY
+                            + " declaration");
+        }
+    }
+
+    /**
+     * Checks if NET_CAPABILITY_PRIORITIZE_LATENCY is declared.
+     */
+    private boolean hasPrioritizeLatency() {
+        return (mRequestedNetworkCapabilities & (1L
+                << NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY)) != 0;
+    }
+
+    /**
+     * Checks if NET_CAPABILITY_PRIORITIZE_BANDWIDTH is declared.
+     */
+    private boolean hasPrioritizeBandwidth() {
+        return (mRequestedNetworkCapabilities & (1L
+                << NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)) != 0;
+    }
+}
diff --git a/service/src/com/android/server/connectivity/InvalidTagException.java b/service/src/com/android/server/connectivity/InvalidTagException.java
new file mode 100644
index 0000000..b924d27
--- /dev/null
+++ b/service/src/com/android/server/connectivity/InvalidTagException.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.connectivity;
+
+
+/**
+ * An exception thrown when a Tag is not valid in self_certified_network_capabilities.xml.
+ */
+public class InvalidTagException extends Exception {
+
+    public InvalidTagException(String message) {
+        super(message);
+    }
+}