Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit c6351207 authored by Treehugger Robot's avatar Treehugger Robot Committed by Android (Google) Code Review
Browse files

Merge "Collect vpn connection metrics" into main

parents 0d08facd 113bef37
Loading
Loading
Loading
Loading
+16 −2
Original line number Diff line number Diff line
@@ -2288,6 +2288,15 @@ public class Vpn {
        return success;
    }

    private void setMtu(int mtu) {
        synchronized (Vpn.this) {
            mConfig.mtu = mtu;
            if (mVpnConnectivityMetrics != null) {
                mVpnConnectivityMetrics.setMtu(mtu);
            }
        }
    }

    /**
     * Updates underlying network set.
     */
@@ -3037,7 +3046,7 @@ public class Vpn {
                    if (mVpnRunner != this) return;

                    mInterface = interfaceName;
                    mConfig.mtu = vpnMtu;
                    setMtu(vpnMtu);
                    mConfig.interfaze = mInterface;

                    mConfig.addresses.clear();
@@ -3144,7 +3153,7 @@ public class Vpn {
                    final LinkProperties oldLp = makeLinkProperties();

                    mConfig.underlyingNetworks = new Network[] {network};
                    mConfig.mtu = calculateVpnMtu();
                    setMtu(calculateVpnMtu());

                    final LinkProperties newLp = makeLinkProperties();

@@ -4250,6 +4259,11 @@ public class Vpn {
            config.allowBypass = profile.isBypassable;
            config.disallowedApplications = getAppExclusionList(mPackage);
            mConfig = config;
            if (mVpnConnectivityMetrics != null) {
                mVpnConnectivityMetrics.setVpnType(VpnManager.TYPE_VPN_PLATFORM);
                mVpnConnectivityMetrics.setVpnProfileType(profile.type);
                mVpnConnectivityMetrics.setAllowedAlgorithms(profile.getAllowedAlgorithms());
            }

            switch (profile.type) {
                case VpnProfile.TYPE_IKEV2_IPSEC_USER_PASS:
+120 −0
Original line number Diff line number Diff line
@@ -16,14 +16,134 @@

package com.android.server.connectivity;

import static android.net.IpSecAlgorithm.AUTH_AES_CMAC;
import static android.net.IpSecAlgorithm.AUTH_AES_XCBC;
import static android.net.IpSecAlgorithm.AUTH_CRYPT_AES_GCM;
import static android.net.IpSecAlgorithm.AUTH_CRYPT_CHACHA20_POLY1305;
import static android.net.IpSecAlgorithm.AUTH_HMAC_MD5;
import static android.net.IpSecAlgorithm.AUTH_HMAC_SHA1;
import static android.net.IpSecAlgorithm.AUTH_HMAC_SHA256;
import static android.net.IpSecAlgorithm.AUTH_HMAC_SHA384;
import static android.net.IpSecAlgorithm.AUTH_HMAC_SHA512;
import static android.net.IpSecAlgorithm.CRYPT_AES_CBC;
import static android.net.IpSecAlgorithm.CRYPT_AES_CTR;

import android.annotation.NonNull;
import android.net.VpnManager;
import android.util.Log;
import android.util.SparseArray;

import androidx.annotation.VisibleForTesting;

import java.util.List;

/**
 * Class to record the VpnConnectionReported into statsd.
 */
public class VpnConnectivityMetrics {
    private static final String TAG = VpnConnectivityMetrics.class.getSimpleName();
    public static final int VPN_TYPE_UNKNOWN = 0;
    public static final int VPN_PROFILE_TYPE_UNKNOWN = 0;
    private static final SparseArray<String> sAlgorithms = new SparseArray<>();
    private final int mUserId;
    private int mVpnType = VPN_TYPE_UNKNOWN;
    private int mVpnProfileType = VPN_PROFILE_TYPE_UNKNOWN;
    private int mMtu = 0;
    /**
     * A bitmask representing the set of currently allowed algorithms.
     * Each bit in this integer corresponds to an algorithm defined in {@code sAlgorithms}.
     * If a bit at a certain position (index) is set, the algorithm corresponding to that
     * index in {@code sAlgorithms} is considered allowed.
     */
    private int mAllowedAlgorithms = 0;

    // Static initializer block to populate the sAlgorithms mapping. It associates integer keys
    // (which also serve as bit positions for the mAllowedAlgorithms bitmask) with their
    // respective algorithm string constants.
    static {
        sAlgorithms.put(0, AUTH_AES_CMAC);
        sAlgorithms.put(1, AUTH_AES_XCBC);
        sAlgorithms.put(2, AUTH_CRYPT_AES_GCM);
        sAlgorithms.put(3, AUTH_CRYPT_CHACHA20_POLY1305);
        sAlgorithms.put(4, AUTH_HMAC_MD5);
        sAlgorithms.put(5, AUTH_HMAC_SHA1);
        sAlgorithms.put(6, AUTH_HMAC_SHA256);
        sAlgorithms.put(7, AUTH_HMAC_SHA384);
        sAlgorithms.put(8, AUTH_HMAC_SHA512);
        sAlgorithms.put(9, CRYPT_AES_CBC);
        sAlgorithms.put(10, CRYPT_AES_CTR);
    }

    public VpnConnectivityMetrics(int userId) {
        mUserId = userId;
    }

    /**
     * Sets the VPN type.
     *
     * @param type The type of the VPN, as defined in {@link VpnManager.VpnType}.
     */
    public void setVpnType(@VpnManager.VpnType int type) {
        mVpnType = type;
    }

    /**
     * Sets the MTU for the VPN connection.
     *
     * @param mtu The MTU value in bytes.
     */
    public void setMtu(int mtu) {
        mMtu = mtu;
    }

    /**
     * Sets the VPN profile type.
     *
     * @param vpnProfile The integer value representing the VPN profile.
     */
    public void setVpnProfileType(int vpnProfile) {
        // There is a shift (+1) between VpnProfileType and VpnProfile.
        mVpnProfileType = vpnProfile + 1;
    }

    /**
     * Sets the allowed algorithms based on a provided list of algorithm names.
     * This method converts the list of string names into a bitmask representation
     * which is then stored in {@code mAllowedAlgorithms}.
     *
     * @param allowedAlgorithms A list of strings, where each string is the name of a algorithm to
     *                          be allowed.
     */
    public void setAllowedAlgorithms(@NonNull List<String> allowedAlgorithms) {
        mAllowedAlgorithms = buildAllowedAlgorithmsBitmask(allowedAlgorithms);
    }

    /**
     * Constructs a bitmask representing the set of allowed algorithms from a list of
     * algorithm names.
     * <p>
     * Each known algorithm name in the input list corresponds to a specific bit
     * in the returned integer. If an algorithm name from the list is found in
     * {@link #sAlgorithms}, the bit at the index of that algorithm in {@link #sAlgorithms}
     * is set in the bitmask.
     * </p>
     *
     * @param allowedAlgorithms A list of strings, where each string is the name of a algorithm.
     * @return An integer bitmask where each set bit indicates an allowed algorithm based on its
     *         index in {@link #sAlgorithms}. Returns 0 if the input list is empty, or contains only
     *         unknown algorithms.
     */
    @VisibleForTesting
    static int buildAllowedAlgorithmsBitmask(@NonNull List<String> allowedAlgorithms) {
        int bitmask = 0;
        for (String ac : allowedAlgorithms) {
            final int index = sAlgorithms.indexOfValue(ac);
            if (index < 0) {
                Log.wtf(TAG, "Unknown allowed algorithm: " + ac);
                continue;
            }
            bitmask |= 1 << index;
        }
        return bitmask;
    }
}
+74 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2025 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 static android.net.IpSecAlgorithm.AUTH_AES_CMAC;
import static android.net.IpSecAlgorithm.AUTH_AES_XCBC;
import static android.net.IpSecAlgorithm.AUTH_CRYPT_AES_GCM;
import static android.net.IpSecAlgorithm.AUTH_CRYPT_CHACHA20_POLY1305;
import static android.net.IpSecAlgorithm.AUTH_HMAC_MD5;
import static android.net.IpSecAlgorithm.AUTH_HMAC_SHA1;
import static android.net.IpSecAlgorithm.AUTH_HMAC_SHA256;
import static android.net.IpSecAlgorithm.AUTH_HMAC_SHA384;
import static android.net.IpSecAlgorithm.AUTH_HMAC_SHA512;
import static android.net.IpSecAlgorithm.CRYPT_AES_CBC;
import static android.net.IpSecAlgorithm.CRYPT_AES_CTR;

import static com.android.testutils.Cleanup.testAndCleanup;
import static com.android.server.connectivity.VpnConnectivityMetrics.buildAllowedAlgorithmsBitmask;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import android.net.Ikev2VpnProfile;
import android.util.Log;

import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;

import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@RunWith(AndroidJUnit4.class)
@SmallTest
public class VpnConnectivityMetricsTest {
    @Test
    public void testBuildAllowedAlgorithmsBitmask() {
        assertEquals(1536, buildAllowedAlgorithmsBitmask(List.of(CRYPT_AES_CBC, CRYPT_AES_CTR)));
        assertEquals(496, buildAllowedAlgorithmsBitmask(
                List.of(AUTH_HMAC_MD5, AUTH_HMAC_SHA1, AUTH_HMAC_SHA256, AUTH_HMAC_SHA384,
                        AUTH_HMAC_SHA512)));
        assertEquals(3, buildAllowedAlgorithmsBitmask(List.of(AUTH_AES_XCBC, AUTH_AES_CMAC)));
        assertEquals(12, buildAllowedAlgorithmsBitmask(
                List.of(AUTH_CRYPT_AES_GCM, AUTH_CRYPT_CHACHA20_POLY1305)));
        assertEquals(1999, buildAllowedAlgorithmsBitmask(Ikev2VpnProfile.DEFAULT_ALGORITHMS));
    }

    @Test
    public void testBuildAllowedAlgorithmsBitmask_UnknownAlgorithm() {
        final AtomicBoolean hasFailed = new AtomicBoolean(false);
        final Log.TerribleFailureHandler originalHandler =
                Log.setWtfHandler((tag, what, system) -> hasFailed.set(true));
        testAndCleanup(() -> {
            buildAllowedAlgorithmsBitmask(List.of("unknown"));
            assertTrue(hasFailed.get());
        }, () -> Log.setWtfHandler(originalHandler));
    }
}
+15 −0
Original line number Diff line number Diff line
@@ -49,6 +49,7 @@ import static android.telephony.CarrierConfigManager.KEY_MIN_UDP_PORT_4500_NAT_T
import static android.telephony.CarrierConfigManager.KEY_PREFERRED_IKE_PROTOCOL_INT;

import static com.android.net.module.util.NetworkStackConstants.IPV6_MIN_MTU;
import static com.android.server.connectivity.Flags.FLAG_COLLECT_VPN_METRICS;
import static com.android.server.connectivity.Vpn.AUTOMATIC_KEEPALIVE_DELAY_SECONDS;
import static com.android.server.connectivity.Vpn.DEFAULT_LONG_LIVED_TCP_CONNS_EXPENSIVE_TIMEOUT_SEC;
import static com.android.server.connectivity.Vpn.DEFAULT_UDP_PORT_4500_NAT_TIMEOUT_SEC_INT;
@@ -157,6 +158,8 @@ import android.os.Process;
import android.os.UserHandle;
import android.os.UserManager;
import android.os.test.TestLooper;
import android.platform.test.annotations.EnableFlags;
import android.platform.test.flag.junit.SetFlagsRule;
import android.provider.Settings;
import android.security.Credentials;
import android.telephony.CarrierConfigManager;
@@ -182,6 +185,7 @@ import com.android.server.IpSecService;
import com.android.server.VpnTestBase;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.AdditionalAnswers;
@@ -222,9 +226,13 @@ import java.util.regex.Pattern;
 */
@RunWith(AndroidJUnit4.class)
@SmallTest
@EnableFlags(FLAG_COLLECT_VPN_METRICS)
public class VpnTest extends VpnTestBase {
    private static final String TAG = "VpnTest";

    @Rule
    public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();

    static final Network EGRESS_NETWORK = new Network(101);
    static final String EGRESS_IFACE = "wlan0";
    private static final String TEST_VPN_CLIENT = "2.4.6.8";
@@ -2054,6 +2062,13 @@ public class VpnTest extends VpnTestBase {
    private Vpn startLegacyVpn(final Vpn vpn, final VpnProfile vpnProfile) throws Exception {
        setMockedUsers(PRIMARY_USER);
        vpn.startLegacyVpn(vpnProfile);
        if (vpnProfile.type == VpnProfile.TYPE_IKEV2_IPSEC_USER_PASS
                || vpnProfile.type == VpnProfile.TYPE_IKEV2_IPSEC_PSK) {
            verify(mVpnConnectivityMetrics).setAllowedAlgorithms(
                    Ikev2VpnProfile.DEFAULT_ALGORITHMS);
        }
        verify(mVpnConnectivityMetrics).setVpnType(VpnManager.TYPE_VPN_PLATFORM);
        verify(mVpnConnectivityMetrics).setVpnProfileType(vpnProfile.type);
        return vpn;
    }