aboutsummaryrefslogtreecommitdiff
path: root/common/src/test/java/org/conscrypt/javax/net/ssl/SSLContextTest.java
blob: f24d8648b3f3de3ce364541a69699a29daa1a6d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
/*
 * Copyright (C) 2010 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 org.conscrypt.javax.net.ssl;

import static org.conscrypt.TestUtils.isWindows;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.security.AccessController;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivilegedAction;
import java.security.Provider;
import java.security.Security;
import java.security.UnrecoverableKeyException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.KeyManagerFactorySpi;
import javax.net.ssl.ManagerFactoryParameters;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.TrustManagerFactorySpi;
import javax.net.ssl.X509KeyManager;
import junit.framework.AssertionFailedError;
import org.conscrypt.TestUtils;
import org.conscrypt.java.security.StandardNames;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class SSLContextTest {

    @Test
    public void test_SSLContext_getDefault() throws Exception {
        SSLContext sslContext = SSLContext.getDefault();
        assertNotNull(sslContext);
        try {
            sslContext.init(null, null, null);
            fail();
        } catch (KeyManagementException expected) {
            // Ignored.
        }
    }

    @Test
    public void test_SSLContext_setDefault() throws Exception {
        try {
            SSLContext.setDefault(null);
            fail();
        } catch (NullPointerException expected) {
            // Ignored.
        }

        SSLContext defaultContext = SSLContext.getDefault();
        for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
            SSLContext oldContext = SSLContext.getDefault();
            assertNotNull(oldContext);
            SSLContext newContext = SSLContext.getInstance(protocol);
            assertNotNull(newContext);
            assertNotSame(oldContext, newContext);
            SSLContext.setDefault(newContext);
            assertSame(newContext, SSLContext.getDefault());
        }
        SSLContext.setDefault(defaultContext);
    }

    @Test
    public void test_SSLContext_defaultConfiguration() throws Exception {
        SSLConfigurationAsserts.assertSSLContextDefaultConfiguration(SSLContext.getDefault());

        for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS_WITH_DEFAULT_CONFIG) {
            SSLContext sslContext = SSLContext.getInstance(protocol);
            if (!protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
                sslContext.init(null, null, null);
            }
            SSLConfigurationAsserts.assertSSLContextDefaultConfiguration(sslContext);
        }
    }

    @Test
    public void test_SSLContext_allProtocols() throws Exception {
        SSLConfigurationAsserts.assertSSLContextDefaultConfiguration(SSLContext.getDefault());

        for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS_ALL) {
            SSLContext sslContext = SSLContext.getInstance(protocol);
            sslContext.init(null, null, null);
        }
    }

    @Test
    public void test_SSLContext_pskOnlyConfiguration_defaultProviderOnly() throws Exception {
        // Test the scenario where only a PSKKeyManager is provided and no TrustManagers are
        // provided.
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(new KeyManager[] { PSKKeyManagerProxy.getConscryptPSKKeyManager(
                                new PSKKeyManagerProxy())},
                new TrustManager[0], null);
        List<String> expectedCipherSuites =
                new ArrayList<String>(StandardNames.CIPHER_SUITES_TLS13);
        expectedCipherSuites.addAll(StandardNames.CIPHER_SUITES_DEFAULT_PSK);
        expectedCipherSuites.add(StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION);
        assertEnabledCipherSuites(expectedCipherSuites, sslContext);
    }

    @Test
    public void test_SSLContext_x509AndPskConfiguration_defaultProviderOnly() throws Exception {
        // Test the scenario where an X509TrustManager and PSKKeyManager are provided.
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(new KeyManager[] {PSKKeyManagerProxy.getConscryptPSKKeyManager(
                                new PSKKeyManagerProxy())},
                null, // Use default trust managers, one of which is an X.509 one.
                null);
        // The TLS 1.3 cipher suites appear before the PSK ones, so we need to dedup them
        Set<String> expectedCipherSuiteSet = new LinkedHashSet<String>();
        expectedCipherSuiteSet.addAll(StandardNames.CIPHER_SUITES_TLS13);
        expectedCipherSuiteSet.addAll(StandardNames.CIPHER_SUITES_DEFAULT_PSK);
        expectedCipherSuiteSet.addAll(StandardNames.CIPHER_SUITES_DEFAULT);
        List<String> expectedCipherSuites = new ArrayList<String>(expectedCipherSuiteSet);
        assertEnabledCipherSuites(expectedCipherSuites, sslContext);

        // Test the scenario where an X509KeyManager and PSKKeyManager are provided.
        sslContext = SSLContext.getInstance("TLS");
        // Just an arbitrary X509KeyManager -- it won't be invoked in this test.
        X509KeyManager x509KeyManager = new RandomPrivateKeyX509ExtendedKeyManager(null);
        sslContext.init(
                new KeyManager[] {x509KeyManager,
                        PSKKeyManagerProxy.getConscryptPSKKeyManager(new PSKKeyManagerProxy())},
                new TrustManager[0], null);
        assertEnabledCipherSuites(expectedCipherSuites, sslContext);
    }

    @Test
    public void test_SSLContext_emptyConfiguration_defaultProviderOnly() throws Exception {
        // Test the scenario where neither X.509 nor PSK KeyManagers or TrustManagers are provided.
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(new KeyManager[0], new TrustManager[0], null);
        // No TLS 1.2 cipher suites should be enabled, since neither PSK nor X.509 key exchange
        // can be done.  The TLS 1.3 cipher suites should be there, since key exchange isn't
        // part of the cipher suite in 1.3.
        List<String> expected = new ArrayList<String>(StandardNames.CIPHER_SUITES_TLS13);
        expected.add(StandardNames.CIPHER_SUITE_SECURE_RENEGOTIATION);
        assertEnabledCipherSuites(expected, sslContext);
    }

    @Test
    public void test_SSLContext_init_correctProtocolVersionsEnabled() throws Exception {
        for (String tlsVersion : StandardNames.SSL_CONTEXT_PROTOCOLS) {
            // Don't test the "Default" instance.
            if (StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT.equals(tlsVersion)) {
                continue;
            }

            SSLContext context = SSLContext.getInstance(tlsVersion);
            context.init(null, null, null);

            StandardNames.assertSSLContextEnabledProtocols(
                    tlsVersion, ((SSLSocket) context.getSocketFactory().createSocket())
                                        .getEnabledProtocols());
            StandardNames.assertSSLContextEnabledProtocols(tlsVersion,
                    ((SSLServerSocket) context.getServerSocketFactory().createServerSocket())
                            .getEnabledProtocols());
            StandardNames.assertSSLContextEnabledProtocols(
                    tlsVersion, context.getDefaultSSLParameters().getProtocols());
            StandardNames.assertSSLContextEnabledProtocols(
                    tlsVersion, context.createSSLEngine().getEnabledProtocols());
        }
    }

    private static void assertEnabledCipherSuites(
            List<String> expectedCipherSuites, SSLContext sslContext) throws Exception {
        TestUtils.assumeSetEndpointIdentificationAlgorithmAvailable();
        assertContentsInOrder(
                expectedCipherSuites, sslContext.createSSLEngine().getEnabledCipherSuites());
        assertContentsInOrder(expectedCipherSuites,
                sslContext.createSSLEngine().getSSLParameters().getCipherSuites());
        assertContentsInOrder(
                expectedCipherSuites, sslContext.getSocketFactory().getDefaultCipherSuites());
        assertContentsInOrder(
                expectedCipherSuites, sslContext.getServerSocketFactory().getDefaultCipherSuites());

        SSLSocket sslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket();
        try {
            assertContentsInOrder(expectedCipherSuites, sslSocket.getEnabledCipherSuites());
            assertContentsInOrder(
                    expectedCipherSuites, sslSocket.getSSLParameters().getCipherSuites());
        } finally {
            try {
                sslSocket.close();
            } catch (IOException ignored) {
            }
        }

        SSLServerSocket sslServerSocket =
                (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket();
        try {
            assertContentsInOrder(expectedCipherSuites, sslServerSocket.getEnabledCipherSuites());
        } finally {
            try {
                sslSocket.close();
            } catch (IOException ignored) {
            }
        }
    }

    @Test
    public void test_SSLContext_getInstance() throws Exception {
        try {
            SSLContext.getInstance(null);
            fail();
        } catch (NullPointerException expected) {
            // Ignored.
        }
        for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
            assertNotNull(SSLContext.getInstance(protocol));
            assertNotSame(SSLContext.getInstance(protocol), SSLContext.getInstance(protocol));
        }

        try {
            SSLContext.getInstance(null, (String) null);
            fail();
        } catch (Exception expected) {
            if (javaVersion() >= 9) {
                assertTrue("Expected NullPointerException on Java 9, was "
                                + expected.getClass().getName(),
                        expected instanceof NullPointerException);
            } else {
                assertTrue(
                        "Expected IllegalArgumentException, was " + expected.getClass().getName(),
                        expected instanceof IllegalArgumentException);
            }
        }
        try {
            SSLContext.getInstance(null, "");
            fail();
        } catch (Exception expected) {
            if (javaVersion() >= 9) {
                assertTrue("Expected NullPointerException on Java 9, was "
                        + expected.getClass().getName(),
                    expected instanceof NullPointerException);
            } else {
                assertTrue(
                    "Expected IllegalArgumentException, was " + expected.getClass().getName(),
                    expected instanceof IllegalArgumentException);
            }
        }
        for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
            try {
                SSLContext.getInstance(protocol, (String) null);
                fail();
            } catch (IllegalArgumentException expected) {
                // Ignored.
            }
        }
        try {
            SSLContext.getInstance(null, StandardNames.JSSE_PROVIDER_NAME);
            fail();
        } catch (NullPointerException expected) {
            // Ignored.
        }
    }

    @Test
    public void test_SSLContext_getProtocol() throws Exception {
        for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
            String protocolName = SSLContext.getInstance(protocol).getProtocol();
            assertNotNull(protocolName);
            assertTrue(protocol.startsWith(protocolName));
        }
    }

    @Test
    public void test_SSLContext_getProvider() throws Exception {
        Provider provider = SSLContext.getDefault().getProvider();
        assertNotNull(provider);
        assertEquals(StandardNames.JSSE_PROVIDER_NAME, provider.getName());
    }

    @Test
    public void test_SSLContext_init_Default() throws Exception {
        // Assert that initializing a default SSLContext fails because it's supposed to be
        // initialized already.
        SSLContext sslContext = SSLContext.getInstance(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT);
        try {
            sslContext.init(null, null, null);
            fail();
        } catch (KeyManagementException expected) {
            // Ignored.
        }
        try {
            sslContext.init(new KeyManager[0], new TrustManager[0], null);
            fail();
        } catch (KeyManagementException expected) {
            // Ignored.
        }
        try {
            sslContext.init(new KeyManager[] {new KeyManager(){}},
                    new TrustManager[] {new TrustManager(){}}, null);
            fail();
        } catch (KeyManagementException expected) {
            // Ignored.
        }
    }

    @Test
    public void test_SSLContext_init_withNullManagerArrays() throws Exception {
        // Assert that SSLContext.init works fine even when provided with null arrays of
        // KeyManagers and TrustManagers.
        // The contract of SSLContext.init is that it will for default X.509 KeyManager and
        // TrustManager from the highest priority KeyManagerFactory and TrustManagerFactory.
        for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
            if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
                // Default SSLContext is provided in an already initialized state
                continue;
            }
            SSLContext sslContext = SSLContext.getInstance(protocol);
            sslContext.init(null, null, null);
        }
    }

    @Test
    public void test_SSLContext_init_withEmptyManagerArrays() throws Exception {
        // Assert that SSLContext.init works fine even when provided with empty arrays of
        // KeyManagers and TrustManagers.
        // The contract of SSLContext.init is that it will not look for default X.509 KeyManager and
        // TrustManager.
        // This test thus installs a Provider of KeyManagerFactory and TrustManagerFactory whose
        // factories throw exceptions which will make this test fail if the factories are used.
        Provider provider = new ThrowExceptionKeyAndTrustManagerFactoryProvider();
        invokeWithHighestPrioritySecurityProvider(provider, new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                assertEquals(ThrowExceptionKeyAndTrustManagerFactoryProvider.class,
                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
                        .getProvider()
                        .getClass());
                assertEquals(ThrowExceptionKeyAndTrustManagerFactoryProvider.class,
                    KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
                        .getProvider()
                        .getClass());

                KeyManager[] keyManagers = new KeyManager[0];
                TrustManager[] trustManagers = new TrustManager[0];
                for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
                    if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
                        // Default SSLContext is provided in an already initialized state
                        continue;
                    }
                    SSLContext sslContext = SSLContext.getInstance(protocol);
                    sslContext.init(keyManagers, trustManagers, null);
                }

                return null;
            }
        });
    }

    @Test
    public void test_SSLContext_init_withoutX509() throws Exception {
        // Assert that SSLContext.init works fine even when provided with KeyManagers and
        // TrustManagers which don't include the X.509 ones.
        // The contract of SSLContext.init is that it will not look for default X.509 KeyManager and
        // TrustManager.
        // This test thus installs a Provider of KeyManagerFactory and TrustManagerFactory whose
        // factories throw exceptions which will make this test fail if the factories are used.
        Provider provider = new ThrowExceptionKeyAndTrustManagerFactoryProvider();
        invokeWithHighestPrioritySecurityProvider(provider, new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                assertEquals(ThrowExceptionKeyAndTrustManagerFactoryProvider.class,
                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
                        .getProvider()
                        .getClass());
                assertEquals(ThrowExceptionKeyAndTrustManagerFactoryProvider.class,
                    KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
                        .getProvider()
                        .getClass());

                KeyManager[] keyManagers = new KeyManager[]{new KeyManager() {
                }};
                TrustManager[] trustManagers = new TrustManager[]{new TrustManager() {
                }};
                for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
                    if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
                        // Default SSLContext is provided in an already initialized state
                        continue;
                    }
                    SSLContext sslContext = SSLContext.getInstance(protocol);
                    sslContext.init(keyManagers, trustManagers, null);
                }

                return null;
            }
        });
    }

    public static class ThrowExceptionKeyAndTrustManagerFactoryProvider extends Provider {
        public ThrowExceptionKeyAndTrustManagerFactoryProvider() {
            super("ThrowExceptionKeyAndTrustManagerProvider", 1.0,
                    "SSLContextTest fake KeyManagerFactory  and TrustManagerFactory provider");

            put("TrustManagerFactory." + TrustManagerFactory.getDefaultAlgorithm(),
                    ThrowExceptionTrustManagagerFactorySpi.class.getName());
            put("TrustManagerFactory.PKIX", ThrowExceptionTrustManagagerFactorySpi.class.getName());

            put("KeyManagerFactory." + KeyManagerFactory.getDefaultAlgorithm(),
                    ThrowExceptionKeyManagagerFactorySpi.class.getName());
            put("KeyManagerFactory.PKIX", ThrowExceptionKeyManagagerFactorySpi.class.getName());
        }
    }

    public static class ThrowExceptionTrustManagagerFactorySpi extends TrustManagerFactorySpi {
        @Override
        protected void engineInit(KeyStore ks) throws KeyStoreException {
            fail();
        }

        @Override
        protected void engineInit(ManagerFactoryParameters spec)
                throws InvalidAlgorithmParameterException {
            fail();
        }

        @Override
        protected TrustManager[] engineGetTrustManagers() {
            throw new AssertionFailedError();
        }
    }

    public static class ThrowExceptionKeyManagagerFactorySpi extends KeyManagerFactorySpi {
        @Override
        protected void engineInit(KeyStore ks, char[] password)
                throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
            fail();
        }

        @Override
        protected void engineInit(ManagerFactoryParameters spec)
                throws InvalidAlgorithmParameterException {
            fail();
        }

        @Override
        protected KeyManager[] engineGetKeyManagers() {
            throw new AssertionFailedError();
        }
    }

    /**
     * Installs the specified security provider as the highest provider, invokes the provided
     * {@link Callable}, and removes the provider.
     *
     * @return result returned by the {@code callable}.
     */
    private static <T> T invokeWithHighestPrioritySecurityProvider(
            Provider provider, Callable<T> callable) throws Exception {
        int providerPosition = -1;
        try {
            providerPosition = Security.insertProviderAt(provider, 1);
            assertEquals(1, providerPosition);
            return callable.call();
        } finally {
            if (providerPosition != -1) {
                Security.removeProvider(provider.getName());
            }
        }
    }

    @Test
    public void test_SSLContext_getSocketFactory() throws Exception {
        for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
            if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
                SSLContext.getInstance(protocol).getSocketFactory();
            } else {
                try {
                    SSLContext.getInstance(protocol).getSocketFactory();
                    fail();
                } catch (IllegalStateException expected) {
                    // Ignored.
                }
            }

            SSLContext sslContext = SSLContext.getInstance(protocol);
            if (!protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
                sslContext.init(null, null, null);
            }
            SocketFactory sf = sslContext.getSocketFactory();
            assertNotNull(sf);
            assertTrue(SSLSocketFactory.class.isAssignableFrom(sf.getClass()));
        }
    }

    @Test
    public void test_SSLContext_getServerSocketFactory() throws Exception {
        for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
            if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
                SSLContext.getInstance(protocol).getServerSocketFactory();
            } else {
                try {
                    SSLContext.getInstance(protocol).getServerSocketFactory();
                    fail();
                } catch (IllegalStateException expected) {
                    // Ignored.
                }
            }

            SSLContext sslContext = SSLContext.getInstance(protocol);
            if (!protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
                sslContext.init(null, null, null);
            }
            ServerSocketFactory ssf = sslContext.getServerSocketFactory();
            assertNotNull(ssf);
            assertTrue(SSLServerSocketFactory.class.isAssignableFrom(ssf.getClass()));
        }
    }

    @Test
    public void test_SSLContext_createSSLEngine() throws Exception {
        for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
            if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
                SSLContext.getInstance(protocol).createSSLEngine();
            } else {
                try {
                    SSLContext.getInstance(protocol).createSSLEngine();
                    fail();
                } catch (IllegalStateException expected) {
                    // Ignored.
                }
            }

            if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
                SSLContext.getInstance(protocol).createSSLEngine(null, -1);
            } else {
                try {
                    SSLContext.getInstance(protocol).createSSLEngine(null, -1);
                    fail();
                } catch (IllegalStateException expected) {
                    // Ignored.
                }
            }

            {
                SSLContext sslContext = SSLContext.getInstance(protocol);
                if (!protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
                    sslContext.init(null, null, null);
                }
                SSLEngine se = sslContext.createSSLEngine();
                assertNotNull(se);
            }

            {
                SSLContext sslContext = SSLContext.getInstance(protocol);
                if (!protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
                    sslContext.init(null, null, null);
                }
                SSLEngine se = sslContext.createSSLEngine(null, -1);
                assertNotNull(se);
            }
        }
    }

    @Test
    public void test_SSLContext_getServerSessionContext() throws Exception {
        for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
            SSLContext sslContext = SSLContext.getInstance(protocol);
            SSLSessionContext sessionContext = sslContext.getServerSessionContext();
            assertNotNull(sessionContext);

            if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
                assertSame(
                        SSLContext.getInstance(protocol).getServerSessionContext(), sessionContext);
            } else {
                assertNotSame(
                        SSLContext.getInstance(protocol).getServerSessionContext(), sessionContext);
            }
        }
    }

    @Test
    public void test_SSLContext_getClientSessionContext() throws Exception {
        for (String protocol : StandardNames.SSL_CONTEXT_PROTOCOLS) {
            SSLContext sslContext = SSLContext.getInstance(protocol);
            SSLSessionContext sessionContext = sslContext.getClientSessionContext();
            assertNotNull(sessionContext);

            if (protocol.equals(StandardNames.SSL_CONTEXT_PROTOCOLS_DEFAULT)) {
                assertSame(
                        SSLContext.getInstance(protocol).getClientSessionContext(), sessionContext);
            } else {
                assertNotSame(
                        SSLContext.getInstance(protocol).getClientSessionContext(), sessionContext);
            }
        }
    }

    @Test
    public void test_SSLContextTest_TestSSLContext_create() {
        TestSSLContext testContext = TestSSLContext.create();
        assertNotNull(testContext);
        assertNotNull(testContext.clientKeyStore);
        assertNull(testContext.clientStorePassword);
        assertNotNull(testContext.serverKeyStore);
        assertNotNull(testContext.clientKeyManagers);
        assertNotNull(testContext.serverKeyManagers);
        if (testContext.clientKeyManagers.length == 0) {
            fail("No client KeyManagers");
        }
        if (testContext.serverKeyManagers.length == 0) {
            fail("No server KeyManagers");
        }
        assertNotNull(testContext.clientKeyManagers[0]);
        assertNotNull(testContext.serverKeyManagers[0]);
        assertNotNull(testContext.clientTrustManager);
        assertNotNull(testContext.serverTrustManager);
        assertNotNull(testContext.clientContext);
        assertNotNull(testContext.serverContext);
        assertNotNull(testContext.serverSocket);
        assertNotNull(testContext.host);
        assertTrue(testContext.port != 0);
        testContext.close();
    }

    @Test
    public void test_SSLContext_SSLv3Unsupported() throws Exception {
        // Find the default provider for TLS and verify that it does NOT support SSLv3.
        Provider defaultTlsProvider = null;
        for (String protocol : new String[] {"SSLContext.TLSv1.2", "SSLContext.TLSv1"}) {
            for (Provider p : Security.getProviders()) {
                if (p.get(protocol) != null) {
                    defaultTlsProvider = p;
                    break;
                }
            }
        }
        assertNotNull(defaultTlsProvider);
        Provider finalDefaultTlsProvider = defaultTlsProvider;
        assertThrows(
            NoSuchAlgorithmException.class,
            () -> SSLContext.getInstance("SSLv3", finalDefaultTlsProvider));
    }

    private static void assertContentsInOrder(List<String> expected, String... actual) {
        List<String> actualList = Arrays.asList(actual);
        if (expected.size() != actual.length) {
            fail("Unexpected length. Expected len <" + expected.size() + ">, actual len <"
                    + actual.length + ">, expected <" + expected + ">, actual <"
                    + actualList + ">");
        }

        if (isWindows()) {
            // TODO(prbprbprb): CpuFeatures.isAESHardwareAccelerated is not reliable on windows
            Collections.sort(actualList);
            Collections.sort(expected);
        }

        if (!expected.equals(actualList)) {
            fail("Unexpected element(s). Expected <" + expected + ">, actual <" + actualList + ">");
        }
    }

    private static boolean isAndroid() {
        boolean android;
        try {
            Class.forName("android.app.Application", false, getSystemClassLoader());
            android = true;
        } catch (Throwable ignored) {
            // Failed to load the class uniquely available in Android.
            android = false;
        }
        return android;
    }

    private static int javaVersion() {
        final int majorVersion;

        if (isAndroid()) {
            majorVersion = 6;
        } else {
            majorVersion = majorVersionFromJavaSpecificationVersion();
        }

        return majorVersion;
    }

    private static int majorVersionFromJavaSpecificationVersion() {
        return majorVersion(System.getProperty("java.specification.version", "1.6"));
    }

    private static int majorVersion(final String javaSpecVersion) {
        final String[] components = javaSpecVersion.split("\\.", -1);
        final int[] version = new int[components.length];
        for (int i = 0; i < components.length; i++) {
            version[i] = Integer.parseInt(components[i]);
        }

        if (version[0] == 1) {
            assertTrue(version[1] >= 6);
            return version[1];
        } else {
            return version[0];
        }
    }

    private static ClassLoader getSystemClassLoader() {
        if (System.getSecurityManager() == null) {
            return ClassLoader.getSystemClassLoader();
        } else {
            return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
                @Override
                public ClassLoader run() {
                    return ClassLoader.getSystemClassLoader();
                }
            });
        }
    }
}