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