1 /* 2 * Copyright (C) 2020 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 17 package android.net.cts; 18 19 import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET; 20 import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED; 21 import static android.net.NetworkCapabilities.TRANSPORT_VPN; 22 import static android.net.cts.util.CtsNetUtils.TestNetworkCallback; 23 24 import static com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity; 25 import static com.android.modules.utils.build.SdkLevel.isAtLeastU; 26 import static com.android.modules.utils.build.SdkLevel.isAtLeastT; 27 import static com.android.testutils.DevSdkIgnoreRuleKt.SC_V2; 28 29 import static org.junit.Assert.assertArrayEquals; 30 import static org.junit.Assert.assertEquals; 31 import static org.junit.Assert.assertFalse; 32 import static org.junit.Assert.assertNotNull; 33 import static org.junit.Assert.assertNull; 34 import static org.junit.Assert.assertThrows; 35 import static org.junit.Assert.assertTrue; 36 import static org.junit.Assert.fail; 37 import static org.junit.Assume.assumeTrue; 38 import static org.junit.Assume.assumeFalse; 39 40 import android.Manifest; 41 import android.annotation.NonNull; 42 import android.app.AppOpsManager; 43 import android.content.Context; 44 import android.content.Intent; 45 import android.content.pm.PackageManager; 46 import android.net.ConnectivityManager; 47 import android.net.Ikev2VpnProfile; 48 import android.net.IpSecAlgorithm; 49 import android.net.Network; 50 import android.net.NetworkRequest; 51 import android.net.ProxyInfo; 52 import android.net.TestNetworkInterface; 53 import android.net.VpnManager; 54 import android.net.cts.util.CtsNetUtils; 55 import android.net.cts.util.IkeSessionTestUtils; 56 import android.net.ipsec.ike.IkeTunnelConnectionParams; 57 import android.os.Build; 58 import android.os.Process; 59 import android.platform.test.annotations.AppModeFull; 60 import android.text.TextUtils; 61 62 import androidx.test.InstrumentationRegistry; 63 64 import com.android.internal.util.HexDump; 65 import com.android.networkstack.apishim.ConstantsShim; 66 import com.android.networkstack.apishim.VpnManagerShimImpl; 67 import com.android.networkstack.apishim.common.VpnManagerShim; 68 import com.android.networkstack.apishim.common.VpnProfileStateShim; 69 import com.android.testutils.DevSdkIgnoreRule; 70 import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo; 71 import com.android.testutils.DevSdkIgnoreRunner; 72 import com.android.testutils.RecorderCallback.CallbackEntry; 73 import com.android.testutils.TestableNetworkCallback; 74 75 import org.bouncycastle.x509.X509V1CertificateGenerator; 76 import org.junit.After; 77 import org.junit.Before; 78 import org.junit.Rule; 79 import org.junit.Test; 80 import org.junit.runner.RunWith; 81 82 import java.math.BigInteger; 83 import java.net.InetAddress; 84 import java.security.KeyPair; 85 import java.security.KeyPairGenerator; 86 import java.security.PrivateKey; 87 import java.security.cert.X509Certificate; 88 import java.util.ArrayList; 89 import java.util.Arrays; 90 import java.util.Date; 91 import java.util.List; 92 import java.util.concurrent.TimeUnit; 93 94 import javax.security.auth.x500.X500Principal; 95 96 @RunWith(DevSdkIgnoreRunner.class) 97 @IgnoreUpTo(Build.VERSION_CODES.Q) 98 @AppModeFull(reason = "Appops state changes disallowed for instant apps (OP_ACTIVATE_PLATFORM_VPN)") 99 public class Ikev2VpnTest { 100 private static final String TAG = Ikev2VpnTest.class.getSimpleName(); 101 102 @Rule 103 public final DevSdkIgnoreRule ignoreRule = new DevSdkIgnoreRule(); 104 105 // Test vectors for IKE negotiation in test mode. 106 private static final String SUCCESSFUL_IKE_INIT_RESP_V4 = 107 "46b8eca1e0d72a18b2b5d9006d47a0022120222000000000000002d0220000300000002c01010004030000" 108 + "0c0100000c800e0100030000080300000c030000080200000400000008040000102800020800" 109 + "100000b8070f159fe5141d8754ca86f72ecc28d66f514927e96cbe9eec0adb42bf2c276a0ab7" 110 + "a97fa93555f4be9218c14e7f286bb28c6b4fb13825a420f2ffc165854f200bab37d69c8963d4" 111 + "0acb831d983163aa50622fd35c182efe882cf54d6106222abcfaa597255d302f1b95ab71c142" 112 + "c279ea5839a180070bff73f9d03fab815f0d5ee2adec7e409d1e35979f8bd92ffd8aab13d1a0" 113 + "0657d816643ae767e9ae84d2ccfa2bcce1a50572be8d3748ae4863c41ae90da16271e014270f" 114 + "77edd5cd2e3299f3ab27d7203f93d770bacf816041cdcecd0f9af249033979da4369cb242dd9" 115 + "6d172e60513ff3db02de63e50eb7d7f596ada55d7946cad0af0669d1f3e2804846ab3f2a930d" 116 + "df56f7f025f25c25ada694e6231abbb87ee8cfd072c8481dc0b0f6b083fdc3bd89b080e49feb" 117 + "0288eef6fdf8a26ee2fc564a11e7385215cf2deaf2a9965638fc279c908ccdf04094988d91a2" 118 + "464b4a8c0326533aff5119ed79ecbd9d99a218b44f506a5eb09351e67da86698b4c58718db25" 119 + "d55f426fb4c76471b27a41fbce00777bc233c7f6e842e39146f466826de94f564cad8b92bfbe" 120 + "87c99c4c7973ec5f1eea8795e7da82819753aa7c4fcfdab77066c56b939330c4b0d354c23f83" 121 + "ea82fa7a64c4b108f1188379ea0eb4918ee009d804100e6bf118771b9058d42141c847d5ec37" 122 + "6e5ec591c71fc9dac01063c2bd31f9c783b28bf1182900002430f3d5de3449462b31dd28bc27" 123 + "297b6ad169bccce4f66c5399c6e0be9120166f2900001c0000400428b8df2e66f69c8584a186" 124 + "c5eac66783551d49b72900001c000040054e7a622e802d5cbfb96d5f30a6e433994370173529" 125 + "0000080000402e290000100000402f00020003000400050000000800004014"; 126 private static final String SUCCESSFUL_IKE_INIT_RESP_V6 = 127 "46b8eca1e0d72a1800d9ea1babce26bf2120222000000000000002d0220000300000002c01010004030000" 128 + "0c0100000c800e0100030000080300000c030000080200000400000008040000102800020800" 129 + "100000ea0e6dd9ca5930a9a45c323a41f64bfd8cdef7730f5fbff37d7c377da427f489a42aa8" 130 + "c89233380e6e925990d49de35c2cdcf63a61302c731a4b3569df1ee1bf2457e55a6751838ede" 131 + "abb75cc63ba5c9e4355e8e784f383a5efe8a44727dc14aeaf8dacc2620fb1c8875416dc07739" 132 + "7fe4decc1bd514a9c7d270cf21fd734c63a25c34b30b68686e54e8a198f37f27cb491fe27235" 133 + "fab5476b036d875ccab9a68d65fbf3006197f9bebbf94de0d3802b4fafe1d48d931ce3a1a346" 134 + "2d65bd639e9bd7fa46299650a9dbaf9b324e40b466942d91a59f41ef8042f8474c4850ed0f63" 135 + "e9238949d41cd8bbaea9aefdb65443a6405792839563aa5dc5c36b5ce8326ccf8a94d9622b85" 136 + "038d390d5fc0299e14e1f022966d4ac66515f6108ca04faec44821fe5bbf2ed4f84ff5671219" 137 + "608cb4c36b44a31ba010c9088f8d5ff943bb9ff857f74be1755f57a5783874adc57f42bb174e" 138 + "4ad3215de628707014dbcb1707bd214658118fdd7a42b3e1638b991ce5b812a667f1145be811" 139 + "685e3cd3baf9b18d062657b64c206a4d19a531c252a6a51a04aeaf42c618620cdbab65baca23" 140 + "82c57ed888422aeaacf7f1bc3fe2247ff7e7eaca218b74d7b31d02f2b0afa123f802529e7e6c" 141 + "3259d418290740ddbf55686e26998d7edcbbf895664972fed666f2f20af40503aa2af436ec6d" 142 + "4ec981ab19b9088755d94ae7a7c2066ea331d4e56e290000243fefe5555fce552d57a84e682c" 143 + "d4a6dfb3f2f94a94464d5bec3d88b88e9559642900001c00004004eb4afff764e7b79bca78b1" 144 + "3a89100d36d678ae982900001c00004005d177216a3c26f782076e12570d40bfaaa148822929" 145 + "0000080000402e290000100000402f00020003000400050000000800004014"; 146 private static final String SUCCESSFUL_IKE_AUTH_RESP_V4 = 147 "46b8eca1e0d72a18b2b5d9006d47a0022e20232000000001000000e0240000c420a2500a3da4c66fa6929e" 148 + "600f36349ba0e38de14f78a3ad0416cba8c058735712a3d3f9a0a6ed36de09b5e9e02697e7c4" 149 + "2d210ac86cfbd709503cfa51e2eab8cfdc6427d136313c072968f6506a546eb5927164200592" 150 + "6e36a16ee994e63f029432a67bc7d37ca619e1bd6e1678df14853067ecf816b48b81e8746069" 151 + "406363e5aa55f13cb2afda9dbebee94256c29d630b17dd7f1ee52351f92b6e1c3d8551c513f1" 152 + "d74ac52a80b2041397e109fe0aeb3c105b0d4be0ae343a943398764281"; 153 private static final String SUCCESSFUL_IKE_AUTH_RESP_V6 = 154 "46b8eca1e0d72a1800d9ea1babce26bf2e20232000000001000000f0240000d4aaf6eaa6c06b50447e6f54" 155 + "827fd8a9d9d6ac8015c1ebb3e8cb03fc6e54b49a107441f50004027cc5021600828026367f03" 156 + "bc425821cd7772ee98637361300c9b76056e874fea2bd4a17212370b291894264d8c023a01d1" 157 + "c3b691fd4b7c0b534e8c95af4c4638e2d125cb21c6267e2507cd745d72e8da109c47b9259c6c" 158 + "57a26f6bc5b337b9b9496d54bdde0333d7a32e6e1335c9ee730c3ecd607a8689aa7b0577b74f" 159 + "3bf437696a9fd5fc0aee3ed346cd9e15d1dda293df89eb388a8719388a60ca7625754de12cdb" 160 + "efe4c886c5c401"; 161 private static final long IKE_INITIATOR_SPI = Long.parseLong("46B8ECA1E0D72A18", 16); 162 163 private static final InetAddress LOCAL_OUTER_4 = InetAddress.parseNumericAddress("192.0.2.1"); 164 private static final InetAddress LOCAL_OUTER_6 = 165 InetAddress.parseNumericAddress("2001:db8::1"); 166 167 private static final int IP4_PREFIX_LEN = 32; 168 private static final int IP6_PREFIX_LEN = 128; 169 170 // TODO: Use IPv6 address when we can generate test vectors (GCE does not allow IPv6 yet). 171 private static final String TEST_SERVER_ADDR_V4 = "192.0.2.2"; 172 private static final String TEST_SERVER_ADDR_V6 = "2001:db8::2"; 173 private static final String TEST_IDENTITY = "client.cts.android.com"; 174 private static final List<String> TEST_ALLOWED_ALGORITHMS = 175 Arrays.asList(IpSecAlgorithm.AUTH_CRYPT_AES_GCM); 176 177 private static final ProxyInfo TEST_PROXY_INFO = 178 ProxyInfo.buildDirectProxy("proxy.cts.android.com", 1234); 179 private static final int TEST_MTU = 1300; 180 181 private static final byte[] TEST_PSK = "ikeAndroidPsk".getBytes(); 182 private static final String TEST_USER = "username"; 183 private static final String TEST_PASSWORD = "pa55w0rd"; 184 185 // Static state to reduce setup/teardown 186 private static final Context sContext = InstrumentationRegistry.getContext(); 187 private static boolean sIsWatch = 188 sContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH); 189 private static final ConnectivityManager sCM = 190 (ConnectivityManager) sContext.getSystemService(Context.CONNECTIVITY_SERVICE); 191 private static final VpnManager sVpnMgr = 192 (VpnManager) sContext.getSystemService(Context.VPN_MANAGEMENT_SERVICE); 193 private static final CtsNetUtils mCtsNetUtils = new CtsNetUtils(sContext); 194 private static final long TIMEOUT_MS = 15_000; 195 196 private VpnManagerShim mVmShim = VpnManagerShimImpl.newInstance(sContext); 197 198 private final X509Certificate mServerRootCa; 199 private final CertificateAndKey mUserCertKey; 200 private final List<TestableNetworkCallback> mCallbacksToUnregister = new ArrayList<>(); 201 Ikev2VpnTest()202 public Ikev2VpnTest() throws Exception { 203 // Build certificates 204 mServerRootCa = generateRandomCertAndKeyPair().cert; 205 mUserCertKey = generateRandomCertAndKeyPair(); 206 } 207 208 @Before setUp()209 public void setUp() { 210 assumeFalse("Skipping test because watches don't support VPN", sIsWatch); 211 } 212 213 @After tearDown()214 public void tearDown() { 215 if (sIsWatch) { 216 return; // Tests are skipped for watches. 217 } 218 219 for (TestableNetworkCallback callback : mCallbacksToUnregister) { 220 sCM.unregisterNetworkCallback(callback); 221 } 222 setAppop(AppOpsManager.OP_ACTIVATE_VPN, false); 223 setAppop(AppOpsManager.OP_ACTIVATE_PLATFORM_VPN, false); 224 225 // Make sure the VpnProfile is not provisioned already. 226 sVpnMgr.stopProvisionedVpnProfile(); 227 228 try { 229 sVpnMgr.startProvisionedVpnProfile(); 230 fail("Expected SecurityException for missing consent"); 231 } catch (SecurityException expected) { 232 } 233 } 234 235 /** 236 * Sets the given appop using shell commands 237 * 238 * <p>This method must NEVER be called from within a shell permission, as it will attempt to 239 * acquire, and then drop the shell permission identity. This results in the caller losing the 240 * shell permission identity due to these calls not being reference counted. 241 */ setAppop(int appop, boolean allow)242 public void setAppop(int appop, boolean allow) { 243 // Requires shell permission to update appops. 244 runWithShellPermissionIdentity(() -> { 245 mCtsNetUtils.setAppopPrivileged(appop, allow); 246 }, Manifest.permission.MANAGE_TEST_NETWORKS); 247 } 248 buildIkev2VpnProfileCommon( @onNull Ikev2VpnProfile.Builder builder, boolean isRestrictedToTestNetworks, boolean requiresValidation, boolean automaticIpVersionSelectionEnabled, boolean automaticNattKeepaliveTimerEnabled)249 private Ikev2VpnProfile buildIkev2VpnProfileCommon( 250 @NonNull Ikev2VpnProfile.Builder builder, boolean isRestrictedToTestNetworks, 251 boolean requiresValidation, boolean automaticIpVersionSelectionEnabled, 252 boolean automaticNattKeepaliveTimerEnabled) throws Exception { 253 254 builder.setBypassable(true) 255 .setAllowedAlgorithms(TEST_ALLOWED_ALGORITHMS) 256 .setProxy(TEST_PROXY_INFO) 257 .setMaxMtu(TEST_MTU) 258 .setMetered(false); 259 if (isAtLeastT()) { 260 builder.setRequiresInternetValidation(requiresValidation); 261 } 262 263 if (isAtLeastU()) { 264 builder.setAutomaticIpVersionSelectionEnabled(automaticIpVersionSelectionEnabled); 265 builder.setAutomaticNattKeepaliveTimerEnabled(automaticNattKeepaliveTimerEnabled); 266 } 267 268 // TODO: replace it in alternative way to remove the hidden method usage 269 if (isRestrictedToTestNetworks) { 270 builder.restrictToTestNetworks(); 271 } 272 273 return builder.build(); 274 } 275 buildIkev2VpnProfileIkeTunConnParams( final boolean isRestrictedToTestNetworks, final boolean requiresValidation, final boolean testIpv6)276 private Ikev2VpnProfile buildIkev2VpnProfileIkeTunConnParams( 277 final boolean isRestrictedToTestNetworks, final boolean requiresValidation, 278 final boolean testIpv6) throws Exception { 279 final IkeTunnelConnectionParams params = 280 new IkeTunnelConnectionParams(testIpv6 281 ? IkeSessionTestUtils.IKE_PARAMS_V6 : IkeSessionTestUtils.IKE_PARAMS_V4, 282 IkeSessionTestUtils.CHILD_PARAMS); 283 284 final Ikev2VpnProfile.Builder builder = 285 new Ikev2VpnProfile.Builder(params) 286 .setRequiresInternetValidation(requiresValidation) 287 .setProxy(TEST_PROXY_INFO) 288 .setMaxMtu(TEST_MTU) 289 .setMetered(false); 290 291 // TODO: replace it in alternative way to remove the hidden method usage 292 if (isRestrictedToTestNetworks) { 293 builder.restrictToTestNetworks(); 294 } 295 return builder.build(); 296 } 297 buildIkev2VpnProfilePsk(@onNull String remote, boolean isRestrictedToTestNetworks, boolean requiresValidation)298 private Ikev2VpnProfile buildIkev2VpnProfilePsk(@NonNull String remote, 299 boolean isRestrictedToTestNetworks, boolean requiresValidation) 300 throws Exception { 301 final Ikev2VpnProfile.Builder builder = 302 new Ikev2VpnProfile.Builder(remote, TEST_IDENTITY) 303 .setAuthPsk(TEST_PSK); 304 return buildIkev2VpnProfileCommon(builder, isRestrictedToTestNetworks, 305 requiresValidation, false /* automaticIpVersionSelectionEnabled */, 306 false /* automaticNattKeepaliveTimerEnabled */); 307 } 308 buildIkev2VpnProfileUsernamePassword(boolean isRestrictedToTestNetworks)309 private Ikev2VpnProfile buildIkev2VpnProfileUsernamePassword(boolean isRestrictedToTestNetworks) 310 throws Exception { 311 final Ikev2VpnProfile.Builder builder = 312 new Ikev2VpnProfile.Builder(TEST_SERVER_ADDR_V6, TEST_IDENTITY) 313 .setAuthUsernamePassword(TEST_USER, TEST_PASSWORD, mServerRootCa); 314 return buildIkev2VpnProfileCommon(builder, isRestrictedToTestNetworks, 315 false /* requiresValidation */, false /* automaticIpVersionSelectionEnabled */, 316 false /* automaticNattKeepaliveTimerEnabled */); 317 } 318 buildIkev2VpnProfileDigitalSignature(boolean isRestrictedToTestNetworks)319 private Ikev2VpnProfile buildIkev2VpnProfileDigitalSignature(boolean isRestrictedToTestNetworks) 320 throws Exception { 321 final Ikev2VpnProfile.Builder builder = 322 new Ikev2VpnProfile.Builder(TEST_SERVER_ADDR_V6, TEST_IDENTITY) 323 .setAuthDigitalSignature( 324 mUserCertKey.cert, mUserCertKey.key, mServerRootCa); 325 return buildIkev2VpnProfileCommon(builder, isRestrictedToTestNetworks, 326 false /* requiresValidation */, false /* automaticIpVersionSelectionEnabled */, 327 false /* automaticNattKeepaliveTimerEnabled */); 328 } 329 checkBasicIkev2VpnProfile(@onNull Ikev2VpnProfile profile)330 private void checkBasicIkev2VpnProfile(@NonNull Ikev2VpnProfile profile) throws Exception { 331 assertEquals(TEST_SERVER_ADDR_V6, profile.getServerAddr()); 332 assertEquals(TEST_IDENTITY, profile.getUserIdentity()); 333 assertEquals(TEST_PROXY_INFO, profile.getProxyInfo()); 334 assertEquals(TEST_ALLOWED_ALGORITHMS, profile.getAllowedAlgorithms()); 335 assertTrue(profile.isBypassable()); 336 assertFalse(profile.isMetered()); 337 assertEquals(TEST_MTU, profile.getMaxMtu()); 338 assertFalse(profile.isRestrictedToTestNetworks()); 339 } 340 doTestBuildIkev2VpnProfilePsk(final boolean requiresValidation)341 public void doTestBuildIkev2VpnProfilePsk(final boolean requiresValidation) throws Exception { 342 assumeTrue(mCtsNetUtils.hasIpsecTunnelsFeature()); 343 344 final Ikev2VpnProfile profile = buildIkev2VpnProfilePsk(TEST_SERVER_ADDR_V6, 345 false /* isRestrictedToTestNetworks */, requiresValidation); 346 347 checkBasicIkev2VpnProfile(profile); 348 assertArrayEquals(TEST_PSK, profile.getPresharedKey()); 349 350 // Verify nothing else is set. 351 assertNull(profile.getUsername()); 352 assertNull(profile.getPassword()); 353 assertNull(profile.getServerRootCaCert()); 354 assertNull(profile.getRsaPrivateKey()); 355 assertNull(profile.getUserCert()); 356 if (isAtLeastT()) { 357 assertEquals(requiresValidation, profile.isInternetValidationRequired()); 358 } 359 } 360 361 @IgnoreUpTo(SC_V2) 362 @Test testBuildIkev2VpnProfileWithIkeTunnelConnectionParams()363 public void testBuildIkev2VpnProfileWithIkeTunnelConnectionParams() throws Exception { 364 assumeTrue(mCtsNetUtils.hasIpsecTunnelsFeature()); 365 366 final IkeTunnelConnectionParams expectedParams = new IkeTunnelConnectionParams( 367 IkeSessionTestUtils.IKE_PARAMS_V6, IkeSessionTestUtils.CHILD_PARAMS); 368 final Ikev2VpnProfile.Builder ikeProfileBuilder = 369 new Ikev2VpnProfile.Builder(expectedParams); 370 // Verify the other Ike options could not be set with IkeTunnelConnectionParams. 371 final Class<IllegalArgumentException> expected = IllegalArgumentException.class; 372 assertThrows(expected, () -> ikeProfileBuilder.setAuthPsk(TEST_PSK)); 373 assertThrows(expected, () -> 374 ikeProfileBuilder.setAuthUsernamePassword(TEST_USER, TEST_PASSWORD, mServerRootCa)); 375 assertThrows(expected, () -> ikeProfileBuilder.setAuthDigitalSignature( 376 mUserCertKey.cert, mUserCertKey.key, mServerRootCa)); 377 378 final Ikev2VpnProfile profile = ikeProfileBuilder.build(); 379 380 assertEquals(expectedParams, profile.getIkeTunnelConnectionParams()); 381 } 382 383 @Test testBuildIkev2VpnProfilePsk()384 public void testBuildIkev2VpnProfilePsk() throws Exception { 385 doTestBuildIkev2VpnProfilePsk(true /* requiresValidation */); 386 doTestBuildIkev2VpnProfilePsk(false /* requiresValidation */); 387 } 388 389 @Test testBuildIkev2VpnProfileUsernamePassword()390 public void testBuildIkev2VpnProfileUsernamePassword() throws Exception { 391 assumeTrue(mCtsNetUtils.hasIpsecTunnelsFeature()); 392 393 final Ikev2VpnProfile profile = 394 buildIkev2VpnProfileUsernamePassword(false /* isRestrictedToTestNetworks */); 395 396 checkBasicIkev2VpnProfile(profile); 397 assertEquals(TEST_USER, profile.getUsername()); 398 assertEquals(TEST_PASSWORD, profile.getPassword()); 399 assertEquals(mServerRootCa, profile.getServerRootCaCert()); 400 401 // Verify nothing else is set. 402 assertNull(profile.getPresharedKey()); 403 assertNull(profile.getRsaPrivateKey()); 404 assertNull(profile.getUserCert()); 405 } 406 407 @Test testBuildIkev2VpnProfileDigitalSignature()408 public void testBuildIkev2VpnProfileDigitalSignature() throws Exception { 409 assumeTrue(mCtsNetUtils.hasIpsecTunnelsFeature()); 410 411 final Ikev2VpnProfile profile = 412 buildIkev2VpnProfileDigitalSignature(false /* isRestrictedToTestNetworks */); 413 414 checkBasicIkev2VpnProfile(profile); 415 assertEquals(mUserCertKey.cert, profile.getUserCert()); 416 assertEquals(mUserCertKey.key, profile.getRsaPrivateKey()); 417 assertEquals(mServerRootCa, profile.getServerRootCaCert()); 418 419 // Verify nothing else is set. 420 assertNull(profile.getUsername()); 421 assertNull(profile.getPassword()); 422 assertNull(profile.getPresharedKey()); 423 } 424 verifyProvisionVpnProfile( boolean hasActivateVpn, boolean hasActivatePlatformVpn, boolean expectIntent)425 private void verifyProvisionVpnProfile( 426 boolean hasActivateVpn, boolean hasActivatePlatformVpn, boolean expectIntent) 427 throws Exception { 428 assumeTrue(mCtsNetUtils.hasIpsecTunnelsFeature()); 429 430 setAppop(AppOpsManager.OP_ACTIVATE_VPN, hasActivateVpn); 431 setAppop(AppOpsManager.OP_ACTIVATE_PLATFORM_VPN, hasActivatePlatformVpn); 432 433 final Ikev2VpnProfile profile = buildIkev2VpnProfilePsk(TEST_SERVER_ADDR_V6, 434 false /* isRestrictedToTestNetworks */, false /* requiresValidation */); 435 final Intent intent = sVpnMgr.provisionVpnProfile(profile); 436 assertEquals(expectIntent, intent != null); 437 } 438 439 @Test testProvisionVpnProfileNoPreviousConsent()440 public void testProvisionVpnProfileNoPreviousConsent() throws Exception { 441 assumeTrue(mCtsNetUtils.hasIpsecTunnelsFeature()); 442 443 verifyProvisionVpnProfile(false /* hasActivateVpn */, 444 false /* hasActivatePlatformVpn */, true /* expectIntent */); 445 } 446 447 @Test testProvisionVpnProfilePlatformVpnConsented()448 public void testProvisionVpnProfilePlatformVpnConsented() throws Exception { 449 assumeTrue(mCtsNetUtils.hasIpsecTunnelsFeature()); 450 451 verifyProvisionVpnProfile(false /* hasActivateVpn */, 452 true /* hasActivatePlatformVpn */, false /* expectIntent */); 453 } 454 455 @Test testProvisionVpnProfileVpnServiceConsented()456 public void testProvisionVpnProfileVpnServiceConsented() throws Exception { 457 assumeTrue(mCtsNetUtils.hasIpsecTunnelsFeature()); 458 459 verifyProvisionVpnProfile(true /* hasActivateVpn */, 460 false /* hasActivatePlatformVpn */, false /* expectIntent */); 461 } 462 463 @Test testProvisionVpnProfileAllPreConsented()464 public void testProvisionVpnProfileAllPreConsented() throws Exception { 465 assumeTrue(mCtsNetUtils.hasIpsecTunnelsFeature()); 466 467 verifyProvisionVpnProfile(true /* hasActivateVpn */, 468 true /* hasActivatePlatformVpn */, false /* expectIntent */); 469 } 470 471 @Test testDeleteVpnProfile()472 public void testDeleteVpnProfile() throws Exception { 473 assumeTrue(mCtsNetUtils.hasIpsecTunnelsFeature()); 474 475 setAppop(AppOpsManager.OP_ACTIVATE_PLATFORM_VPN, true); 476 477 final Ikev2VpnProfile profile = buildIkev2VpnProfilePsk(TEST_SERVER_ADDR_V6, 478 false /* isRestrictedToTestNetworks */, false /* requiresValidation */); 479 assertNull(sVpnMgr.provisionVpnProfile(profile)); 480 481 // Verify that deleting the profile works (even without the appop) 482 setAppop(AppOpsManager.OP_ACTIVATE_PLATFORM_VPN, false); 483 sVpnMgr.deleteProvisionedVpnProfile(); 484 485 // Test that the profile was deleted - starting it should throw an IAE. 486 try { 487 setAppop(AppOpsManager.OP_ACTIVATE_PLATFORM_VPN, true); 488 sVpnMgr.startProvisionedVpnProfile(); 489 fail("Expected IllegalArgumentException due to missing profile"); 490 } catch (IllegalArgumentException expected) { 491 } 492 } 493 494 @Test testStartVpnProfileNoPreviousConsent()495 public void testStartVpnProfileNoPreviousConsent() throws Exception { 496 assumeTrue(mCtsNetUtils.hasIpsecTunnelsFeature()); 497 498 setAppop(AppOpsManager.OP_ACTIVATE_VPN, false); 499 setAppop(AppOpsManager.OP_ACTIVATE_PLATFORM_VPN, false); 500 501 // Make sure the VpnProfile is not provisioned already. 502 sVpnMgr.stopProvisionedVpnProfile(); 503 504 try { 505 sVpnMgr.startProvisionedVpnProfile(); 506 fail("Expected SecurityException for missing consent"); 507 } catch (SecurityException expected) { 508 } 509 } 510 checkStartStopVpnProfileBuildsNetworks(@onNull IkeTunUtils tunUtils, boolean testIpv6, boolean requiresValidation, boolean testSessionKey, boolean testIkeTunConnParams)511 private void checkStartStopVpnProfileBuildsNetworks(@NonNull IkeTunUtils tunUtils, 512 boolean testIpv6, boolean requiresValidation, boolean testSessionKey, 513 boolean testIkeTunConnParams) 514 throws Exception { 515 String serverAddr = testIpv6 ? TEST_SERVER_ADDR_V6 : TEST_SERVER_ADDR_V4; 516 String initResp = testIpv6 ? SUCCESSFUL_IKE_INIT_RESP_V6 : SUCCESSFUL_IKE_INIT_RESP_V4; 517 String authResp = testIpv6 ? SUCCESSFUL_IKE_AUTH_RESP_V6 : SUCCESSFUL_IKE_AUTH_RESP_V4; 518 boolean hasNat = !testIpv6; 519 520 // Requires MANAGE_TEST_NETWORKS to provision a test-mode profile. 521 mCtsNetUtils.setAppopPrivileged(AppOpsManager.OP_ACTIVATE_PLATFORM_VPN, true); 522 523 final Ikev2VpnProfile profile = testIkeTunConnParams 524 ? buildIkev2VpnProfileIkeTunConnParams(true /* isRestrictedToTestNetworks */, 525 requiresValidation, testIpv6) 526 : buildIkev2VpnProfilePsk(serverAddr, true /* isRestrictedToTestNetworks */, 527 requiresValidation); 528 assertNull(sVpnMgr.provisionVpnProfile(profile)); 529 530 final TestableNetworkCallback cb = new TestableNetworkCallback(TIMEOUT_MS); 531 final NetworkRequest nr = new NetworkRequest.Builder() 532 .clearCapabilities().addTransportType(TRANSPORT_VPN).build(); 533 registerNetworkCallback(nr, cb); 534 535 if (testSessionKey) { 536 // testSessionKey will never be true if running on <T 537 // startProvisionedVpnProfileSession() should return a non-null & non-empty random UUID. 538 final String sessionId = mVmShim.startProvisionedVpnProfileSession(); 539 assertFalse(TextUtils.isEmpty(sessionId)); 540 final VpnProfileStateShim profileState = mVmShim.getProvisionedVpnProfileState(); 541 assertNotNull(profileState); 542 assertEquals(ConstantsShim.VPN_PROFILE_STATE_CONNECTING, profileState.getState()); 543 assertEquals(sessionId, profileState.getSessionId()); 544 assertFalse(profileState.isAlwaysOn()); 545 assertFalse(profileState.isLockdownEnabled()); 546 } else { 547 sVpnMgr.startProvisionedVpnProfile(); 548 } 549 550 // Inject IKE negotiation 551 int expectedMsgId = 0; 552 tunUtils.awaitReqAndInjectResp(IKE_INITIATOR_SPI, expectedMsgId++, false /* isEncap */, 553 HexDump.hexStringToByteArray(initResp)); 554 tunUtils.awaitReqAndInjectResp(IKE_INITIATOR_SPI, expectedMsgId++, hasNat /* isEncap */, 555 HexDump.hexStringToByteArray(authResp)); 556 557 // Verify the VPN network came up 558 final Network vpnNetwork = cb.expect(CallbackEntry.AVAILABLE).getNetwork(); 559 560 if (testSessionKey) { 561 final VpnProfileStateShim profileState = mVmShim.getProvisionedVpnProfileState(); 562 assertNotNull(profileState); 563 assertEquals(ConstantsShim.VPN_PROFILE_STATE_CONNECTED, profileState.getState()); 564 assertFalse(profileState.isAlwaysOn()); 565 assertFalse(profileState.isLockdownEnabled()); 566 } 567 568 cb.expectCaps(vpnNetwork, TIMEOUT_MS, c -> c.hasTransport(TRANSPORT_VPN) 569 && c.hasCapability(NET_CAPABILITY_INTERNET) 570 && !c.hasCapability(NET_CAPABILITY_VALIDATED) 571 && Process.myUid() == c.getOwnerUid()); 572 cb.expect(CallbackEntry.LINK_PROPERTIES_CHANGED, vpnNetwork); 573 cb.expect(CallbackEntry.BLOCKED_STATUS, vpnNetwork); 574 575 // A VPN that requires validation is initially not validated, while one that doesn't 576 // immediately validate automatically. Because this VPN can't actually access Internet, 577 // the VPN only validates if it doesn't require validation. If the VPN requires validation 578 // but unexpectedly sends this callback, expecting LOST below will fail because the next 579 // callback will be the validated capabilities instead. 580 // In S and below, |requiresValidation| is ignored, so this callback is always sent 581 // regardless of its value. However, there is a race in Vpn(see b/228574221) that VPN may 582 // misuse VPN network itself as the underlying network. The fix is not available without 583 // SDK > T platform. Thus, verify this only on T+ platform. 584 if (!requiresValidation && isAtLeastT()) { 585 cb.eventuallyExpect(CallbackEntry.NETWORK_CAPS_UPDATED, TIMEOUT_MS, 586 entry -> ((CallbackEntry.CapabilitiesChanged) entry).getCaps() 587 .hasCapability(NET_CAPABILITY_VALIDATED)); 588 } 589 590 sVpnMgr.stopProvisionedVpnProfile(); 591 // Using expectCallback may cause the test to be flaky since test may receive other 592 // callbacks such as linkproperties change. 593 cb.eventuallyExpect(CallbackEntry.LOST, TIMEOUT_MS, 594 lost -> vpnNetwork.equals(lost.getNetwork())); 595 } 596 registerNetworkCallback(NetworkRequest request, TestableNetworkCallback callback)597 private void registerNetworkCallback(NetworkRequest request, TestableNetworkCallback callback) { 598 sCM.registerNetworkCallback(request, callback); 599 mCallbacksToUnregister.add(callback); 600 } 601 602 private class VerifyStartStopVpnProfileTest implements TestNetworkRunnable.Test { 603 private final boolean mTestIpv6Only; 604 private final boolean mRequiresValidation; 605 private final boolean mTestSessionKey; 606 private final boolean mTestIkeTunConnParams; 607 608 /** 609 * Constructs the test 610 * 611 * @param testIpv6Only if true, builds a IPv6-only test; otherwise builds a IPv4-only test 612 * @param requiresValidation whether this VPN should request platform validation 613 * @param testSessionKey if true, start VPN by calling startProvisionedVpnProfileSession() 614 */ VerifyStartStopVpnProfileTest(boolean testIpv6Only, boolean requiresValidation, boolean testSessionKey, boolean testIkeTunConnParams)615 VerifyStartStopVpnProfileTest(boolean testIpv6Only, boolean requiresValidation, 616 boolean testSessionKey, boolean testIkeTunConnParams) { 617 mTestIpv6Only = testIpv6Only; 618 mRequiresValidation = requiresValidation; 619 mTestSessionKey = testSessionKey; 620 mTestIkeTunConnParams = testIkeTunConnParams; 621 } 622 623 @Override runTest(TestNetworkInterface testIface, TestNetworkCallback tunNetworkCallback)624 public void runTest(TestNetworkInterface testIface, TestNetworkCallback tunNetworkCallback) 625 throws Exception { 626 final IkeTunUtils tunUtils = new IkeTunUtils(testIface.getFileDescriptor()); 627 628 checkStartStopVpnProfileBuildsNetworks(tunUtils, mTestIpv6Only, mRequiresValidation, 629 mTestSessionKey, mTestIkeTunConnParams); 630 } 631 632 @Override cleanupTest()633 public void cleanupTest() { 634 sVpnMgr.stopProvisionedVpnProfile(); 635 } 636 637 @Override getTestNetworkAddresses()638 public InetAddress[] getTestNetworkAddresses() { 639 if (mTestIpv6Only) { 640 return new InetAddress[] {LOCAL_OUTER_6}; 641 } else { 642 return new InetAddress[] {LOCAL_OUTER_4}; 643 } 644 } 645 } 646 doTestStartStopVpnProfile(boolean testIpv6Only, boolean requiresValidation, boolean testSessionKey, boolean testIkeTunConnParams)647 private void doTestStartStopVpnProfile(boolean testIpv6Only, boolean requiresValidation, 648 boolean testSessionKey, boolean testIkeTunConnParams) throws Exception { 649 assumeTrue(mCtsNetUtils.hasIpsecTunnelsFeature()); 650 // Requires shell permission to update appops. 651 runWithShellPermissionIdentity( 652 new TestNetworkRunnable(new VerifyStartStopVpnProfileTest( 653 testIpv6Only, requiresValidation, testSessionKey , testIkeTunConnParams))); 654 } 655 656 @Test @IgnoreUpTo(SC_V2) testStartStopVpnProfileV4()657 public void testStartStopVpnProfileV4() throws Exception { 658 doTestStartStopVpnProfile(false /* testIpv6Only */, false /* requiresValidation */, 659 false /* testSessionKey */, false /* testIkeTunConnParams */); 660 } 661 662 @Test @IgnoreUpTo(SC_V2) testStartStopVpnProfileV4WithValidation()663 public void testStartStopVpnProfileV4WithValidation() throws Exception { 664 doTestStartStopVpnProfile(false /* testIpv6Only */, true /* requiresValidation */, 665 false /* testSessionKey */, false /* testIkeTunConnParams */); 666 } 667 668 @Test @IgnoreUpTo(SC_V2) testStartStopVpnProfileV6()669 public void testStartStopVpnProfileV6() throws Exception { 670 doTestStartStopVpnProfile(true /* testIpv6Only */, false /* requiresValidation */, 671 false /* testSessionKey */, false /* testIkeTunConnParams */); 672 } 673 674 @Test @IgnoreUpTo(SC_V2) testStartStopVpnProfileV6WithValidation()675 public void testStartStopVpnProfileV6WithValidation() throws Exception { 676 doTestStartStopVpnProfile(true /* testIpv6Only */, true /* requiresValidation */, 677 false /* testSessionKey */, false /* testIkeTunConnParams */); 678 } 679 680 @Test @IgnoreUpTo(SC_V2) testStartStopVpnProfileIkeTunConnParamsV4()681 public void testStartStopVpnProfileIkeTunConnParamsV4() throws Exception { 682 doTestStartStopVpnProfile(false /* testIpv6Only */, false /* requiresValidation */, 683 false /* testSessionKey */, true /* testIkeTunConnParams */); 684 } 685 686 @Test @IgnoreUpTo(SC_V2) testStartStopVpnProfileIkeTunConnParamsV4WithValidation()687 public void testStartStopVpnProfileIkeTunConnParamsV4WithValidation() throws Exception { 688 doTestStartStopVpnProfile(false /* testIpv6Only */, true /* requiresValidation */, 689 false /* testSessionKey */, true /* testIkeTunConnParams */); 690 } 691 692 @Test @IgnoreUpTo(SC_V2) testStartStopVpnProfileIkeTunConnParamsV6()693 public void testStartStopVpnProfileIkeTunConnParamsV6() throws Exception { 694 doTestStartStopVpnProfile(true /* testIpv6Only */, false /* requiresValidation */, 695 false /* testSessionKey */, true /* testIkeTunConnParams */); 696 } 697 698 @Test @IgnoreUpTo(SC_V2) testStartStopVpnProfileIkeTunConnParamsV6WithValidation()699 public void testStartStopVpnProfileIkeTunConnParamsV6WithValidation() throws Exception { 700 doTestStartStopVpnProfile(true /* testIpv6Only */, true /* requiresValidation */, 701 false /* testSessionKey */, true /* testIkeTunConnParams */); 702 } 703 704 @IgnoreUpTo(SC_V2) 705 @Test testStartProvisionedVpnV4ProfileSession()706 public void testStartProvisionedVpnV4ProfileSession() throws Exception { 707 doTestStartStopVpnProfile(false /* testIpv6Only */, false /* requiresValidation */, 708 true /* testSessionKey */, false /* testIkeTunConnParams */); 709 } 710 711 @IgnoreUpTo(SC_V2) 712 @Test testStartProvisionedVpnV6ProfileSession()713 public void testStartProvisionedVpnV6ProfileSession() throws Exception { 714 doTestStartStopVpnProfile(true /* testIpv6Only */, false /* requiresValidation */, 715 true /* testSessionKey */, false /* testIkeTunConnParams */); 716 } 717 718 @IgnoreUpTo(Build.VERSION_CODES.TIRAMISU) 719 @Test testBuildIkev2VpnProfileWithAutomaticNattKeepaliveTimerEnabled()720 public void testBuildIkev2VpnProfileWithAutomaticNattKeepaliveTimerEnabled() throws Exception { 721 final Ikev2VpnProfile profileWithDefaultValue = buildIkev2VpnProfilePsk(TEST_SERVER_ADDR_V6, 722 false /* isRestrictedToTestNetworks */, false /* requiresValidation */); 723 assertFalse(profileWithDefaultValue.isAutomaticNattKeepaliveTimerEnabled()); 724 725 final Ikev2VpnProfile.Builder builder = 726 new Ikev2VpnProfile.Builder(TEST_SERVER_ADDR_V6, TEST_IDENTITY) 727 .setAuthPsk(TEST_PSK); 728 final Ikev2VpnProfile profile = buildIkev2VpnProfileCommon(builder, 729 false /* isRestrictedToTestNetworks */, 730 false /* requiresValidation */, 731 false /* automaticIpVersionSelectionEnabled */, 732 true /* automaticNattKeepaliveTimerEnabled */); 733 assertTrue(profile.isAutomaticNattKeepaliveTimerEnabled()); 734 } 735 736 @IgnoreUpTo(Build.VERSION_CODES.TIRAMISU) 737 @Test testBuildIkev2VpnProfileWithAutomaticIpVersionSelectionEnabled()738 public void testBuildIkev2VpnProfileWithAutomaticIpVersionSelectionEnabled() throws Exception { 739 final Ikev2VpnProfile profileWithDefaultValue = buildIkev2VpnProfilePsk(TEST_SERVER_ADDR_V6, 740 false /* isRestrictedToTestNetworks */, false /* requiresValidation */); 741 assertFalse(profileWithDefaultValue.isAutomaticIpVersionSelectionEnabled()); 742 743 final Ikev2VpnProfile.Builder builder = 744 new Ikev2VpnProfile.Builder(TEST_SERVER_ADDR_V6, TEST_IDENTITY) 745 .setAuthPsk(TEST_PSK); 746 final Ikev2VpnProfile profile = buildIkev2VpnProfileCommon(builder, 747 false /* isRestrictedToTestNetworks */, 748 false /* requiresValidation */, 749 true /* automaticIpVersionSelectionEnabled */, 750 false /* automaticNattKeepaliveTimerEnabled */); 751 assertTrue(profile.isAutomaticIpVersionSelectionEnabled()); 752 } 753 754 private static class CertificateAndKey { 755 public final X509Certificate cert; 756 public final PrivateKey key; 757 CertificateAndKey(X509Certificate cert, PrivateKey key)758 CertificateAndKey(X509Certificate cert, PrivateKey key) { 759 this.cert = cert; 760 this.key = key; 761 } 762 } 763 generateRandomCertAndKeyPair()764 private static CertificateAndKey generateRandomCertAndKeyPair() throws Exception { 765 final Date validityBeginDate = 766 new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1L)); 767 final Date validityEndDate = 768 new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1L)); 769 770 // Generate a keypair 771 final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); 772 keyPairGenerator.initialize(512); 773 final KeyPair keyPair = keyPairGenerator.generateKeyPair(); 774 775 final X500Principal dnName = new X500Principal("CN=test.android.com"); 776 final X509V1CertificateGenerator certGen = new X509V1CertificateGenerator(); 777 certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); 778 certGen.setSubjectDN(dnName); 779 certGen.setIssuerDN(dnName); 780 certGen.setNotBefore(validityBeginDate); 781 certGen.setNotAfter(validityEndDate); 782 certGen.setPublicKey(keyPair.getPublic()); 783 certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); 784 785 final X509Certificate cert = certGen.generate(keyPair.getPrivate(), "AndroidOpenSSL"); 786 return new CertificateAndKey(cert, keyPair.getPrivate()); 787 } 788 } 789