summaryrefslogtreecommitdiff
path: root/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java
blob: 0f336dbeac3077f9ea4477ee515775d973980ce4 (plain) (blame)
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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
/*
 * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package sun.security.ssl;

import java.io.FileInputStream;
import java.net.Socket;
import java.security.*;
import java.security.cert.*;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import javax.net.ssl.*;
import sun.security.action.GetPropertyAction;
import sun.security.provider.certpath.AlgorithmChecker;
import sun.security.validator.Validator;

/**
 * Implementation of an SSLContext.
 *
 * Implementation note: Instances of this class and the child classes are
 * immutable, except that the context initialization (SSLContext.init()) may
 * reset the key, trust managers and source of secure random.
 */

public abstract class SSLContextImpl extends SSLContextSpi {

    private final EphemeralKeyManager ephemeralKeyManager;
    private final SSLSessionContextImpl clientCache;
    private final SSLSessionContextImpl serverCache;

    private boolean isInitialized;

    private X509ExtendedKeyManager keyManager;
    private X509TrustManager trustManager;
    private SecureRandom secureRandom;

    // DTLS cookie exchange manager
    private volatile HelloCookieManager.Builder helloCookieManagerBuilder;

    private final boolean clientEnableStapling = Utilities.getBooleanProperty(
            "jdk.tls.client.enableStatusRequestExtension", true);
    private final boolean serverEnableStapling = Utilities.getBooleanProperty(
            "jdk.tls.server.enableStatusRequestExtension", false);
    private static final Collection<CipherSuite> clientCustomizedCipherSuites =
            getCustomizedCipherSuites("jdk.tls.client.cipherSuites");
    private static final Collection<CipherSuite> serverCustomizedCipherSuites =
            getCustomizedCipherSuites("jdk.tls.server.cipherSuites");

    private volatile StatusResponseManager statusResponseManager;

    private final ReentrantLock contextLock = new ReentrantLock();

    SSLContextImpl() {
        ephemeralKeyManager = new EphemeralKeyManager();
        clientCache = new SSLSessionContextImpl(false);
        serverCache = new SSLSessionContextImpl(true);
    }

    @Override
    protected void engineInit(KeyManager[] km, TrustManager[] tm,
                                SecureRandom sr) throws KeyManagementException {
        isInitialized = false;
        keyManager = chooseKeyManager(km);

        if (tm == null) {
            try {
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(
                        TrustManagerFactory.getDefaultAlgorithm());
                tmf.init((KeyStore)null);
                tm = tmf.getTrustManagers();
            } catch (Exception e) {
                // eat
            }
        }
        trustManager = chooseTrustManager(tm);

        if (sr == null) {
            secureRandom = new SecureRandom();
        } else {
            secureRandom = sr;
        }

        /*
         * The initial delay of seeding the random number generator
         * could be long enough to cause the initial handshake on our
         * first connection to timeout and fail. Make sure it is
         * primed and ready by getting some initial output from it.
         */
        if (SSLLogger.isOn && SSLLogger.isOn("ssl,sslctx")) {
            SSLLogger.finest("trigger seeding of SecureRandom");
        }
        secureRandom.nextInt();
        if (SSLLogger.isOn && SSLLogger.isOn("ssl,sslctx")) {
            SSLLogger.finest("done seeding of SecureRandom");
        }

        isInitialized = true;
    }

    private X509TrustManager chooseTrustManager(TrustManager[] tm)
            throws KeyManagementException {
        // We only use the first instance of X509TrustManager passed to us.
        for (int i = 0; tm != null && i < tm.length; i++) {
            if (tm[i] instanceof X509TrustManager) {
                if (tm[i] instanceof X509ExtendedTrustManager) {
                    return (X509TrustManager)tm[i];
                } else {
                    return new AbstractTrustManagerWrapper(
                                        (X509TrustManager)tm[i]);
                }
            }
        }

        // nothing found, return a dummy X509TrustManager.
        return DummyX509TrustManager.INSTANCE;
    }

    private X509ExtendedKeyManager chooseKeyManager(KeyManager[] kms)
            throws KeyManagementException {
        for (int i = 0; kms != null && i < kms.length; i++) {
            KeyManager km = kms[i];
            if (!(km instanceof X509KeyManager)) {
                continue;
            }

            if (km instanceof X509ExtendedKeyManager) {
                return (X509ExtendedKeyManager)km;
            }

            if (SSLLogger.isOn && SSLLogger.isOn("ssl,sslctx")) {
                SSLLogger.warning(
                    "X509KeyManager passed to SSLContext.init():  need an " +
                    "X509ExtendedKeyManager for SSLEngine use");
            }
            return new AbstractKeyManagerWrapper((X509KeyManager)km);
        }

        // nothing found, return a dummy X509ExtendedKeyManager
        return DummyX509KeyManager.INSTANCE;
    }

    abstract SSLEngine createSSLEngineImpl();
    abstract SSLEngine createSSLEngineImpl(String host, int port);

    @Override
    protected SSLEngine engineCreateSSLEngine() {
        if (!isInitialized) {
            throw new IllegalStateException("SSLContext is not initialized");
        }
        return createSSLEngineImpl();
    }

    @Override
    protected SSLEngine engineCreateSSLEngine(String host, int port) {
        if (!isInitialized) {
            throw new IllegalStateException("SSLContext is not initialized");
        }
        return createSSLEngineImpl(host, port);
    }

    @Override
    protected SSLSocketFactory engineGetSocketFactory() {
        if (!isInitialized) {
            throw new IllegalStateException("SSLContext is not initialized");
        }
        if (isDTLS()) {
            throw new UnsupportedOperationException(
                    "DTLS not supported with SSLSocket");
        }
       return new SSLSocketFactoryImpl(this);
    }

    @Override
    protected SSLServerSocketFactory engineGetServerSocketFactory() {
        if (!isInitialized) {
            throw new IllegalStateException("SSLContext is not initialized");
        }
        if (isDTLS()) {
            throw new UnsupportedOperationException(
                    "DTLS not supported with SSLServerSocket");
        }
        return new SSLServerSocketFactoryImpl(this);
    }

    @Override
    protected SSLSessionContext engineGetClientSessionContext() {
        return clientCache;
    }

    @Override
    protected SSLSessionContext engineGetServerSessionContext() {
        return serverCache;
    }

    SecureRandom getSecureRandom() {
        return secureRandom;
    }

    X509ExtendedKeyManager getX509KeyManager() {
        return keyManager;
    }

    X509TrustManager getX509TrustManager() {
        return trustManager;
    }

    EphemeralKeyManager getEphemeralKeyManager() {
        return ephemeralKeyManager;
    }

    // Used for DTLS in server mode only.
    HelloCookieManager getHelloCookieManager(ProtocolVersion protocolVersion) {
        if (helloCookieManagerBuilder == null) {
            contextLock.lock();
            try {
                if (helloCookieManagerBuilder == null) {
                    helloCookieManagerBuilder =
                            new HelloCookieManager.Builder(secureRandom);
                }
            } finally {
                contextLock.unlock();
            }
        }

        return helloCookieManagerBuilder.valueOf(protocolVersion);
    }

    StatusResponseManager getStatusResponseManager() {
        if (serverEnableStapling && statusResponseManager == null) {
            contextLock.lock();
            try {
                if (statusResponseManager == null) {
                    if (SSLLogger.isOn && SSLLogger.isOn("ssl,sslctx")) {
                        SSLLogger.finest(
                                "Initializing StatusResponseManager");
                    }
                    statusResponseManager = new StatusResponseManager();
                }
            } finally {
                contextLock.unlock();
            }
        }

        return statusResponseManager;
    }

    // Get supported protocols.
    abstract List<ProtocolVersion> getSupportedProtocolVersions();

    // Get default protocols for server mode.
    abstract List<ProtocolVersion> getServerDefaultProtocolVersions();

    // Get default protocols for client mode.
    abstract List<ProtocolVersion> getClientDefaultProtocolVersions();

    // Get supported CipherSuite list.
    abstract List<CipherSuite> getSupportedCipherSuites();

    // Get default CipherSuite list for server mode.
    abstract List<CipherSuite> getServerDefaultCipherSuites();

    // Get default CipherSuite list for client mode.
    abstract List<CipherSuite> getClientDefaultCipherSuites();

    // Is the context for DTLS protocols?
    abstract boolean isDTLS();

    // Get default protocols.
    List<ProtocolVersion> getDefaultProtocolVersions(boolean roleIsServer) {
        return roleIsServer ? getServerDefaultProtocolVersions()
                            : getClientDefaultProtocolVersions();
    }

    // Get default CipherSuite list.
    List<CipherSuite> getDefaultCipherSuites(boolean roleIsServer) {
        return roleIsServer ? getServerDefaultCipherSuites()
                            : getClientDefaultCipherSuites();
    }

    /**
     * Return whether a protocol list is the original default enabled
     * protocols.  See: SSLSocket/SSLEngine.setEnabledProtocols()
     */
    boolean isDefaultProtocolVesions(List<ProtocolVersion> protocols) {
        return (protocols == getServerDefaultProtocolVersions()) ||
               (protocols == getClientDefaultProtocolVersions());
    }

    /**
     * Return whether a protocol list is the original default enabled
     * protocols.  See: SSLSocket/SSLEngine.setEnabledProtocols()
     */
    boolean isDefaultCipherSuiteList(List<CipherSuite> cipherSuites) {
        return (cipherSuites == getServerDefaultCipherSuites()) ||
               (cipherSuites == getClientDefaultCipherSuites());
    }

    /**
     * Return whether client or server side stapling has been enabled
     * for this SSLContextImpl
     * @param isClient true if the caller is operating in a client side role,
     * false if acting as a server.
     * @return true if stapling has been enabled for the specified role, false
     * otherwise.
     */
    boolean isStaplingEnabled(boolean isClient) {
        return isClient ? clientEnableStapling : serverEnableStapling;
    }

    /*
     * Return the list of all available CipherSuites that are supported
     * using currently installed providers.
     */
    private static List<CipherSuite> getApplicableSupportedCipherSuites(
            List<ProtocolVersion> protocols) {

        return getApplicableCipherSuites(
                CipherSuite.allowedCipherSuites(), protocols);
    }

    /*
     * Return the list of all available CipherSuites that are default enabled
     * in client or server side.
     */
    private static List<CipherSuite> getApplicableEnabledCipherSuites(
            List<ProtocolVersion> protocols, boolean isClient) {

        if (isClient) {
            if (!clientCustomizedCipherSuites.isEmpty()) {
                return getApplicableCipherSuites(
                        clientCustomizedCipherSuites, protocols);
            }
        } else {
            if (!serverCustomizedCipherSuites.isEmpty()) {
                return getApplicableCipherSuites(
                        serverCustomizedCipherSuites, protocols);
            }
        }

        return getApplicableCipherSuites(
                CipherSuite.defaultCipherSuites(), protocols);
    }

    /*
     * Return the list of available CipherSuites which are applicable to
     * the specified protocols.
     */
    private static List<CipherSuite> getApplicableCipherSuites(
            Collection<CipherSuite> allowedCipherSuites,
            List<ProtocolVersion> protocols) {
        LinkedHashSet<CipherSuite> suites = new LinkedHashSet<>();
        if (protocols != null && (!protocols.isEmpty())) {
            for (CipherSuite suite : allowedCipherSuites) {
                if (!suite.isAvailable()) {
                    continue;
                }

                boolean isSupported = false;
                for (ProtocolVersion protocol : protocols) {
                    if (!suite.supports(protocol) ||
                            !suite.bulkCipher.isAvailable()) {
                        continue;
                    }

                    if (SSLAlgorithmConstraints.DEFAULT.permits(
                            EnumSet.of(CryptoPrimitive.KEY_AGREEMENT),
                            suite.name, null)) {
                        suites.add(suite);
                        isSupported = true;
                    } else if (SSLLogger.isOn &&
                            SSLLogger.isOn("ssl,sslctx,verbose")) {
                        SSLLogger.fine(
                                "Ignore disabled cipher suite: " + suite.name);
                    }

                    break;
                }

                if (!isSupported && SSLLogger.isOn &&
                        SSLLogger.isOn("ssl,sslctx,verbose")) {
                    SSLLogger.finest(
                            "Ignore unsupported cipher suite: " + suite);
                }
            }
        }

        return new ArrayList<>(suites);
    }

    /*
     * Get the customized cipher suites specified by the given system property.
     */
    private static Collection<CipherSuite> getCustomizedCipherSuites(
            String propertyName) {

        String property = GetPropertyAction.privilegedGetProperty(propertyName);
        if (SSLLogger.isOn && SSLLogger.isOn("ssl,sslctx")) {
            SSLLogger.fine(
                    "System property " + propertyName + " is set to '" +
                    property + "'");
        }
        if (property != null && !property.isEmpty()) {
            // remove double quote marks from beginning/end of the property
            if (property.length() > 1 && property.charAt(0) == '"' &&
                    property.charAt(property.length() - 1) == '"') {
                property = property.substring(1, property.length() - 1);
            }
        }

        if (property != null && !property.isEmpty()) {
            String[] cipherSuiteNames = property.split(",");
            Collection<CipherSuite> cipherSuites =
                        new ArrayList<>(cipherSuiteNames.length);
            for (int i = 0; i < cipherSuiteNames.length; i++) {
                cipherSuiteNames[i] = cipherSuiteNames[i].trim();
                if (cipherSuiteNames[i].isEmpty()) {
                    continue;
                }

                CipherSuite suite;
                try {
                    suite = CipherSuite.nameOf(cipherSuiteNames[i]);
                } catch (IllegalArgumentException iae) {
                    if (SSLLogger.isOn && SSLLogger.isOn("ssl,sslctx")) {
                        SSLLogger.fine(
                                "Unknown or unsupported cipher suite name: " +
                                cipherSuiteNames[i]);
                    }

                    continue;
                }

                if (suite != null && suite.isAvailable()) {
                    cipherSuites.add(suite);
                } else {
                    if (SSLLogger.isOn && SSLLogger.isOn("ssl,sslctx")) {
                        SSLLogger.fine(
                                "The current installed providers do not " +
                                "support cipher suite: " + cipherSuiteNames[i]);
                    }
                }
            }

            return cipherSuites;
        }

        return Collections.emptyList();
    }


    private static List<ProtocolVersion> getAvailableProtocols(
            ProtocolVersion[] protocolCandidates) {

        List<ProtocolVersion> availableProtocols =
                Collections.<ProtocolVersion>emptyList();
        if (protocolCandidates != null && protocolCandidates.length != 0) {
            availableProtocols = new ArrayList<>(protocolCandidates.length);
            for (ProtocolVersion p : protocolCandidates) {
                if (p.isAvailable) {
                    availableProtocols.add(p);
                }
            }
        }

        return availableProtocols;
    }

    /*
     * The SSLContext implementation for SSL/(D)TLS algorithm
     *
     * SSL/TLS protocols specify the forward compatibility and version
     * roll-back attack protections, however, a number of SSL/TLS server
     * vendors did not implement these aspects properly, and some current
     * SSL/TLS servers may refuse to talk to a TLS 1.1 or later client.
     *
     * Considering above interoperability issues, SunJSSE will not set
     * TLS 1.1 and TLS 1.2 as the enabled protocols for client by default.
     *
     * For SSL/TLS servers, there is no such interoperability issues as
     * SSL/TLS clients. In SunJSSE, TLS 1.1 or later version will be the
     * enabled protocols for server by default.
     *
     * We may change the behavior when popular TLS/SSL vendors support TLS
     * forward compatibility properly.
     *
     * SSLv2Hello is no longer necessary.  This interoperability option was
     * put in place in the late 90's when SSLv3/TLS1.0 were relatively new
     * and there were a fair number of SSLv2-only servers deployed.  Because
     * of the security issues in SSLv2, it is rarely (if ever) used, as
     * deployments should now be using SSLv3 and TLSv1.
     *
     * Considering the issues of SSLv2Hello, we should not enable SSLv2Hello
     * by default. Applications still can use it by enabling SSLv2Hello with
     * the series of setEnabledProtocols APIs.
     */

    /*
     * The base abstract SSLContext implementation for the Transport Layer
     * Security (TLS) protocols.
     *
     * This abstract class encapsulates supported and the default server
     * SSL/TLS parameters.
     *
     * @see SSLContext
     */
    private abstract static class AbstractTLSContext extends SSLContextImpl {
        private static final List<ProtocolVersion> supportedProtocols;
        private static final List<ProtocolVersion> serverDefaultProtocols;

        private static final List<CipherSuite> supportedCipherSuites;
        private static final List<CipherSuite> serverDefaultCipherSuites;

        static {
            supportedProtocols = Arrays.asList(
                ProtocolVersion.TLS13,
                ProtocolVersion.TLS12,
                ProtocolVersion.TLS11,
                ProtocolVersion.TLS10,
                ProtocolVersion.SSL30,
                ProtocolVersion.SSL20Hello
            );

            serverDefaultProtocols = getAvailableProtocols(
                    new ProtocolVersion[] {
                ProtocolVersion.TLS13,
                ProtocolVersion.TLS12,
                ProtocolVersion.TLS11,
                ProtocolVersion.TLS10
            });

            supportedCipherSuites = getApplicableSupportedCipherSuites(
                    supportedProtocols);
            serverDefaultCipherSuites = getApplicableEnabledCipherSuites(
                    serverDefaultProtocols, false);
        }

        @Override
        List<ProtocolVersion> getSupportedProtocolVersions() {
            return supportedProtocols;
        }

        @Override
        List<CipherSuite> getSupportedCipherSuites() {
            return supportedCipherSuites;
        }

        @Override
        List<ProtocolVersion> getServerDefaultProtocolVersions() {
            return serverDefaultProtocols;
        }

        @Override
        List<CipherSuite> getServerDefaultCipherSuites() {
            return serverDefaultCipherSuites;
        }

        @Override
        SSLEngine createSSLEngineImpl() {
            return new SSLEngineImpl(this);
        }

        @Override
        SSLEngine createSSLEngineImpl(String host, int port) {
            return new SSLEngineImpl(this, host, port);
        }

        @Override
        boolean isDTLS() {
            return false;
        }
    }

    /*
     * The SSLContext implementation for SSLv3 and TLS10 algorithm
     *
     * @see SSLContext
     */
    public static final class TLS10Context extends AbstractTLSContext {
        private static final List<ProtocolVersion> clientDefaultProtocols;
        private static final List<CipherSuite> clientDefaultCipherSuites;

        static {
            clientDefaultProtocols = getAvailableProtocols(
                    new ProtocolVersion[] {
                ProtocolVersion.TLS10
            });

            clientDefaultCipherSuites = getApplicableEnabledCipherSuites(
                    clientDefaultProtocols, true);
        }

        @Override
        List<ProtocolVersion> getClientDefaultProtocolVersions() {
            return clientDefaultProtocols;
        }

        @Override
        List<CipherSuite> getClientDefaultCipherSuites() {
            return clientDefaultCipherSuites;
        }
    }

    /*
     * The SSLContext implementation for TLS11 algorithm
     *
     * @see SSLContext
     */
    public static final class TLS11Context extends AbstractTLSContext {
        private static final List<ProtocolVersion> clientDefaultProtocols;
        private static final List<CipherSuite> clientDefaultCipherSuites;

        static {
            clientDefaultProtocols = getAvailableProtocols(
                    new ProtocolVersion[] {
                ProtocolVersion.TLS11,
                ProtocolVersion.TLS10
            });

            clientDefaultCipherSuites = getApplicableEnabledCipherSuites(
                    clientDefaultProtocols, true);

        }

        @Override
        List<ProtocolVersion> getClientDefaultProtocolVersions() {
            return clientDefaultProtocols;
        }

        @Override
        List<CipherSuite> getClientDefaultCipherSuites() {
            return clientDefaultCipherSuites;
        }
    }

    /*
     * The SSLContext implementation for TLS12 algorithm
     *
     * @see SSLContext
     */
    public static final class TLS12Context extends AbstractTLSContext {
        private static final List<ProtocolVersion> clientDefaultProtocols;
        private static final List<CipherSuite> clientDefaultCipherSuites;

        static {
            clientDefaultProtocols = getAvailableProtocols(
                    new ProtocolVersion[] {
                ProtocolVersion.TLS12,
                ProtocolVersion.TLS11,
                ProtocolVersion.TLS10
            });

            clientDefaultCipherSuites = getApplicableEnabledCipherSuites(
                    clientDefaultProtocols, true);
        }

        @Override
        List<ProtocolVersion> getClientDefaultProtocolVersions() {
            return clientDefaultProtocols;
        }

        @Override
        List<CipherSuite> getClientDefaultCipherSuites() {
            return clientDefaultCipherSuites;
        }
    }

    /*
     * The SSLContext implementation for TLS1.3 algorithm
     *
     * @see SSLContext
     */
    public static final class TLS13Context extends AbstractTLSContext {
        private static final List<ProtocolVersion> clientDefaultProtocols;
        private static final List<CipherSuite> clientDefaultCipherSuites;

        static {
            clientDefaultProtocols = getAvailableProtocols(
                    new ProtocolVersion[] {
                ProtocolVersion.TLS13,
                ProtocolVersion.TLS12,
                ProtocolVersion.TLS11,
                ProtocolVersion.TLS10
            });

            clientDefaultCipherSuites = getApplicableEnabledCipherSuites(
                    clientDefaultProtocols, true);
        }

        @Override
        List<ProtocolVersion> getClientDefaultProtocolVersions() {
            return clientDefaultProtocols;
        }

        @Override
        List<CipherSuite> getClientDefaultCipherSuites() {
            return clientDefaultCipherSuites;
        }
    }

    /*
     * The interface for the customized SSL/(D)TLS SSLContext.
     *
     * @see SSLContext
     */
    private static class CustomizedSSLProtocols {
        private static final String JDK_TLS_CLIENT_PROTOCOLS =
                "jdk.tls.client.protocols";
        private static final String JDK_TLS_SERVER_PROTOCOLS =
                "jdk.tls.server.protocols";
        static IllegalArgumentException reservedException = null;
        static final ArrayList<ProtocolVersion> customizedClientProtocols =
                new ArrayList<>();
        static final ArrayList<ProtocolVersion> customizedServerProtocols =
                new ArrayList<>();

        // Don't want a java.lang.LinkageError for illegal system property.
        //
        // Please don't throw exception in this static block.  Otherwise,
        // java.lang.LinkageError may be thrown during the instantiation of
        // the provider service. Instead, please handle the initialization
        // exception in the caller's constructor.
        static {
            populate(JDK_TLS_CLIENT_PROTOCOLS, customizedClientProtocols);
            populate(JDK_TLS_SERVER_PROTOCOLS, customizedServerProtocols);
        }

        private static void populate(String propname,
                ArrayList<ProtocolVersion> arrayList) {
            String property = GetPropertyAction.privilegedGetProperty(propname);
            if (property == null) {
                return;
            }

            if (!property.isEmpty()) {
                // remove double quote marks from beginning/end of the property
                if (property.length() > 1 && property.charAt(0) == '"' &&
                        property.charAt(property.length() - 1) == '"') {
                    property = property.substring(1, property.length() - 1);
                }
            }

            if (!property.isEmpty()) {
                String[] protocols = property.split(",");
                for (int i = 0; i < protocols.length; i++) {
                    protocols[i] = protocols[i].trim();
                    // Is it a supported protocol name?
                    ProtocolVersion pv =
                            ProtocolVersion.nameOf(protocols[i]);
                    if (pv == null) {
                        reservedException = new IllegalArgumentException(
                            propname + ": " + protocols[i] +
                            " is not a supported SSL protocol name");
                    }

                    // ignore duplicated protocols
                    if (!arrayList.contains(pv)) {
                        arrayList.add(pv);
                    }
                }
            }
        }
    }

    /*
     * The SSLContext implementation for customized TLS protocols
     *
     * @see SSLContext
     */
    private static class CustomizedTLSContext extends AbstractTLSContext {

        private static final List<ProtocolVersion> clientDefaultProtocols;
        private static final List<ProtocolVersion> serverDefaultProtocols;
        private static final List<CipherSuite> clientDefaultCipherSuites;
        private static final List<CipherSuite> serverDefaultCipherSuites;
        private static final IllegalArgumentException reservedException;

        // Don't want a java.lang.LinkageError for illegal system property.
        //
        // Please don't throw exception in this static block.  Otherwise,
        // java.lang.LinkageError may be thrown during the instantiation of
        // the provider service. Instead, let's handle the initialization
        // exception in constructor.
        static {
            reservedException = CustomizedSSLProtocols.reservedException;
            if (reservedException == null) {
                clientDefaultProtocols = customizedProtocols(true,
                        CustomizedSSLProtocols.customizedClientProtocols);
                serverDefaultProtocols = customizedProtocols(false,
                        CustomizedSSLProtocols.customizedServerProtocols);

                clientDefaultCipherSuites =
                        getApplicableEnabledCipherSuites(
                                clientDefaultProtocols, true);
                serverDefaultCipherSuites =
                        getApplicableEnabledCipherSuites(
                                serverDefaultProtocols, false);

            } else {
                // unlikely to be used
                clientDefaultProtocols = null;
                serverDefaultProtocols = null;
                clientDefaultCipherSuites = null;
                serverDefaultCipherSuites = null;
            }
        }

        private static List<ProtocolVersion> customizedProtocols(
                boolean client, List<ProtocolVersion> customized) {
            List<ProtocolVersion> refactored = new ArrayList<>();
            for (ProtocolVersion pv : customized) {
                if (!pv.isDTLS) {
                    refactored.add(pv);
                }
            }

            // Use the default enabled protocols if no customization
            ProtocolVersion[] candidates;
            if (refactored.isEmpty()) {
                // Client and server use the same default protocols.
                candidates = new ProtocolVersion[] {
                        ProtocolVersion.TLS13,
                        ProtocolVersion.TLS12,
                        ProtocolVersion.TLS11,
                        ProtocolVersion.TLS10
                    };
            } else {
                // Use the customized TLS protocols.
                candidates =
                    refactored.toArray(new ProtocolVersion[0]);
            }

            return getAvailableProtocols(candidates);
        }

        protected CustomizedTLSContext() {
            if (reservedException != null) {
                throw reservedException;
            }
        }

        @Override
        List<ProtocolVersion> getClientDefaultProtocolVersions() {
            return clientDefaultProtocols;
        }

        @Override
        List<ProtocolVersion> getServerDefaultProtocolVersions() {
            return serverDefaultProtocols;
        }

        @Override
        List<CipherSuite> getClientDefaultCipherSuites() {
            return clientDefaultCipherSuites;
        }

        @Override
        List<CipherSuite> getServerDefaultCipherSuites() {
            return serverDefaultCipherSuites;
        }
    }

    /*
     * The SSLContext implementation for default "TLS" algorithm
     *
     * @see SSLContext
     */
    public static final class TLSContext extends CustomizedTLSContext {
        // use the default constructor and methods
    }

    // lazy initialization holder class idiom for static default parameters
    //
    // See Effective Java Second Edition: Item 71.
    private static final class DefaultManagersHolder {
        private static final String NONE = "NONE";
        private static final String P11KEYSTORE = "PKCS11";

        private static final TrustManager[] trustManagers;
        private static final KeyManager[] keyManagers;

        private static final Exception reservedException;

        static {
            Exception reserved = null;
            TrustManager[] tmMediator = null;
            try {
                tmMediator = getTrustManagers();
            } catch (Exception e) {
                reserved = e;
                if (SSLLogger.isOn && SSLLogger.isOn("ssl,defaultctx")) {
                    SSLLogger.warning(
                            "Failed to load default trust managers", e);
                }
            }

            KeyManager[] kmMediator = null;
            if (reserved == null) {
                try {
                    kmMediator = getKeyManagers();
                } catch (Exception e) {
                    reserved = e;
                    if (SSLLogger.isOn && SSLLogger.isOn("ssl,defaultctx")) {
                        SSLLogger.warning(
                                "Failed to load default key managers", e);
                    }
                }
            }

            if (reserved != null) {
                trustManagers = new TrustManager[0];
                keyManagers = new KeyManager[0];

                // Important note: please don't reserve the original exception
                // object, which may be not garbage collection friendly as
                // 'reservedException' is a static filed.
                reservedException =
                        new KeyManagementException(reserved.getMessage());
            } else {
                trustManagers = tmMediator;
                keyManagers = kmMediator;

                reservedException = null;
            }
        }

        private static TrustManager[] getTrustManagers() throws Exception {
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(
                    TrustManagerFactory.getDefaultAlgorithm());
            if ("SunJSSE".equals(tmf.getProvider().getName())) {
                // The implementation will load the default KeyStore
                // automatically.  Cached trust materials may be used
                // for performance improvement.
                tmf.init((KeyStore)null);
            } else {
                // Use the explicitly specified KeyStore for third party's
                // TrustManagerFactory implementation.
                KeyStore ks = TrustStoreManager.getTrustedKeyStore();
                tmf.init(ks);
            }

            return tmf.getTrustManagers();
        }

        @SuppressWarnings("removal")
        private static KeyManager[] getKeyManagers() throws Exception {

            final Map<String,String> props = new HashMap<>();
            AccessController.doPrivileged(
                        new PrivilegedExceptionAction<Object>() {
                @Override
                public Object run() throws Exception {
                    props.put("keyStore",  System.getProperty(
                                "javax.net.ssl.keyStore", ""));
                    props.put("keyStoreType", System.getProperty(
                                "javax.net.ssl.keyStoreType",
                                KeyStore.getDefaultType()));
                    props.put("keyStoreProvider", System.getProperty(
                                "javax.net.ssl.keyStoreProvider", ""));
                    props.put("keyStorePasswd", System.getProperty(
                                "javax.net.ssl.keyStorePassword", ""));
                    return null;
                }
            });

            final String defaultKeyStore = props.get("keyStore");
            String defaultKeyStoreType = props.get("keyStoreType");
            String defaultKeyStoreProvider = props.get("keyStoreProvider");
            if (SSLLogger.isOn && SSLLogger.isOn("ssl,defaultctx")) {
                SSLLogger.fine("keyStore is : " + defaultKeyStore);
                SSLLogger.fine("keyStore type is : " +
                                        defaultKeyStoreType);
                SSLLogger.fine("keyStore provider is : " +
                                        defaultKeyStoreProvider);
            }

            if (P11KEYSTORE.equals(defaultKeyStoreType) &&
                    !NONE.equals(defaultKeyStore)) {
                throw new IllegalArgumentException("if keyStoreType is "
                    + P11KEYSTORE + ", then keyStore must be " + NONE);
            }

            FileInputStream fs = null;
            KeyStore ks = null;
            char[] passwd = null;
            try {
                if (!defaultKeyStore.isEmpty() &&
                        !NONE.equals(defaultKeyStore)) {
                    fs = AccessController.doPrivileged(
                            new PrivilegedExceptionAction<FileInputStream>() {
                        @Override
                        public FileInputStream run() throws Exception {
                            return new FileInputStream(defaultKeyStore);
                        }
                    });
                }

                String defaultKeyStorePassword = props.get("keyStorePasswd");
                if (!defaultKeyStorePassword.isEmpty()) {
                    passwd = defaultKeyStorePassword.toCharArray();
                }

                // Try to initialize key store.
                if ((defaultKeyStoreType.length()) != 0) {
                    if (SSLLogger.isOn && SSLLogger.isOn("ssl,defaultctx")) {
                        SSLLogger.finest("init keystore");
                    }
                    if (defaultKeyStoreProvider.isEmpty()) {
                        ks = KeyStore.getInstance(defaultKeyStoreType);
                    } else {
                        ks = KeyStore.getInstance(defaultKeyStoreType,
                                            defaultKeyStoreProvider);
                    }

                    // if defaultKeyStore is NONE, fs will be null
                    ks.load(fs, passwd);
                }
            } finally {
                if (fs != null) {
                    fs.close();
                    fs = null;
                }
            }

            /*
             * Try to initialize key manager.
             */
            if (SSLLogger.isOn && SSLLogger.isOn("ssl,defaultctx")) {
                SSLLogger.fine("init keymanager of type " +
                    KeyManagerFactory.getDefaultAlgorithm());
            }
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(
                KeyManagerFactory.getDefaultAlgorithm());

            if (P11KEYSTORE.equals(defaultKeyStoreType)) {
                kmf.init(ks, null); // do not pass key passwd if using token
            } else {
                kmf.init(ks, passwd);
            }

            return kmf.getKeyManagers();
        }
    }

    // lazy initialization holder class idiom for static default parameters
    //
    // See Effective Java Second Edition: Item 71.
    private static final class DefaultSSLContextHolder {

        private static final SSLContextImpl sslContext;
        private static final Exception reservedException;

        static {
            Exception reserved = null;
            SSLContextImpl mediator = null;
            if (DefaultManagersHolder.reservedException != null) {
                reserved = DefaultManagersHolder.reservedException;
            } else {
                try {
                    mediator = new DefaultSSLContext();
                } catch (Exception e) {
                    // Important note: please don't reserve the original
                    // exception object, which may be not garbage collection
                    // friendly as 'reservedException' is a static filed.
                    reserved = new KeyManagementException(e.getMessage());
                    if (SSLLogger.isOn && SSLLogger.isOn("ssl,defaultctx")) {
                        SSLLogger.warning(
                                "Failed to load default SSLContext", e);
                    }
                }
            }

            sslContext = mediator;
            reservedException = reserved;
        }
    }

    /*
     * The SSLContext implementation for default "Default" algorithm
     *
     * @see SSLContext
     */
    public static final class DefaultSSLContext extends CustomizedTLSContext {

        // public constructor for SSLContext.getInstance("Default")
        public DefaultSSLContext() throws Exception {
            if (DefaultManagersHolder.reservedException != null) {
                throw DefaultManagersHolder.reservedException;
            }

            try {
                super.engineInit(DefaultManagersHolder.keyManagers,
                        DefaultManagersHolder.trustManagers, null);
            } catch (Exception e) {
                if (SSLLogger.isOn && SSLLogger.isOn("ssl,defaultctx")) {
                    SSLLogger.fine("default context init failed: ", e);
                }
                throw e;
            }
        }

        @Override
        protected void engineInit(KeyManager[] km, TrustManager[] tm,
            SecureRandom sr) throws KeyManagementException {
            throw new KeyManagementException
                ("Default SSLContext is initialized automatically");
        }

        static SSLContextImpl getDefaultImpl() throws Exception {
            if (DefaultSSLContextHolder.reservedException != null) {
                throw DefaultSSLContextHolder.reservedException;
            }

            return DefaultSSLContextHolder.sslContext;
        }
    }

    /*
     * The base abstract SSLContext implementation for the Datagram Transport
     * Layer Security (DTLS) protocols.
     *
     * This abstract class encapsulates supported and the default server DTLS
     * parameters.
     *
     * @see SSLContext
     */
    private abstract static class AbstractDTLSContext extends SSLContextImpl {
        private static final List<ProtocolVersion> supportedProtocols;
        private static final List<ProtocolVersion> serverDefaultProtocols;

        private static final List<CipherSuite> supportedCipherSuites;
        private static final List<CipherSuite> serverDefaultCipherSuites;

        static {
            supportedProtocols = Arrays.asList(
                ProtocolVersion.DTLS12,
                ProtocolVersion.DTLS10
            );

            // available protocols for server mode
            serverDefaultProtocols = getAvailableProtocols(
                    new ProtocolVersion[] {
                ProtocolVersion.DTLS12,
                ProtocolVersion.DTLS10
            });

            supportedCipherSuites = getApplicableSupportedCipherSuites(
                    supportedProtocols);
            serverDefaultCipherSuites = getApplicableEnabledCipherSuites(
                    serverDefaultProtocols, false);
        }

        @Override
        protected SSLParameters engineGetDefaultSSLParameters() {
            SSLEngine engine = createSSLEngineImpl();
            // Note: The TLSContext defaults to client side SSLParameters.
            // We can do the same here. Please don't change the behavior
            // for compatibility.
            engine.setUseClientMode(true);
            return engine.getSSLParameters();
        }

        @Override
        protected SSLParameters engineGetSupportedSSLParameters() {
            SSLEngine engine = createSSLEngineImpl();
            SSLParameters params = new SSLParameters();
            params.setCipherSuites(engine.getSupportedCipherSuites());
            params.setProtocols(engine.getSupportedProtocols());
            return params;
        }

        @Override
        List<ProtocolVersion> getSupportedProtocolVersions() {
            return supportedProtocols;
        }

        @Override
        List<CipherSuite> getSupportedCipherSuites() {
            return supportedCipherSuites;
        }

        @Override
        List<ProtocolVersion> getServerDefaultProtocolVersions() {
            return serverDefaultProtocols;
        }

        @Override
        List<CipherSuite> getServerDefaultCipherSuites() {
            return serverDefaultCipherSuites;
        }

        @Override
        SSLEngine createSSLEngineImpl() {
            return new SSLEngineImpl(this);
        }

        @Override
        SSLEngine createSSLEngineImpl(String host, int port) {
            return new SSLEngineImpl(this, host, port);
        }

        @Override
        boolean isDTLS() {
            return true;
        }
    }

    /*
     * The SSLContext implementation for DTLSv1.0 algorithm.
     *
     * @see SSLContext
     */
    public static final class DTLS10Context extends AbstractDTLSContext {
        private static final List<ProtocolVersion> clientDefaultProtocols;
        private static final List<CipherSuite> clientDefaultCipherSuites;

        static {
            // available protocols for client mode
            clientDefaultProtocols = getAvailableProtocols(
                    new ProtocolVersion[] {
                ProtocolVersion.DTLS10
            });

            clientDefaultCipherSuites = getApplicableEnabledCipherSuites(
                    clientDefaultProtocols, true);
        }

        @Override
        List<ProtocolVersion> getClientDefaultProtocolVersions() {
            return clientDefaultProtocols;
        }

        @Override
        List<CipherSuite> getClientDefaultCipherSuites() {
            return clientDefaultCipherSuites;
        }
    }

    /*
     * The SSLContext implementation for DTLSv1.2 algorithm.
     *
     * @see SSLContext
     */
    public static final class DTLS12Context extends AbstractDTLSContext {
        private static final List<ProtocolVersion> clientDefaultProtocols;
        private static final List<CipherSuite> clientDefaultCipherSuites;

        static {
            // available protocols for client mode
            clientDefaultProtocols = getAvailableProtocols(
                    new ProtocolVersion[] {
                ProtocolVersion.DTLS12,
                ProtocolVersion.DTLS10
            });

            clientDefaultCipherSuites = getApplicableEnabledCipherSuites(
                    clientDefaultProtocols, true);
        }

        @Override
        List<ProtocolVersion> getClientDefaultProtocolVersions() {
            return clientDefaultProtocols;
        }

        @Override
        List<CipherSuite> getClientDefaultCipherSuites() {
            return clientDefaultCipherSuites;
        }
    }

    /*
     * The SSLContext implementation for customized DTLS protocols
     *
     * @see SSLContext
     */
    private static class CustomizedDTLSContext extends AbstractDTLSContext {
        private static final List<ProtocolVersion> clientDefaultProtocols;
        private static final List<ProtocolVersion> serverDefaultProtocols;
        private static final List<CipherSuite> clientDefaultCipherSuites;
        private static final List<CipherSuite> serverDefaultCipherSuites;

        private static IllegalArgumentException reservedException;

        // Don't want a java.lang.LinkageError for illegal system property.
        //
        // Please don't throw exception in this static block.  Otherwise,
        // java.lang.LinkageError may be thrown during the instantiation of
        // the provider service. Instead, let's handle the initialization
        // exception in constructor.
        static {
            reservedException = CustomizedSSLProtocols.reservedException;
            if (reservedException == null) {
                clientDefaultProtocols = customizedProtocols(true,
                        CustomizedSSLProtocols.customizedClientProtocols);
                serverDefaultProtocols = customizedProtocols(false,
                        CustomizedSSLProtocols.customizedServerProtocols);

                clientDefaultCipherSuites =
                        getApplicableEnabledCipherSuites(
                                clientDefaultProtocols, true);
                serverDefaultCipherSuites =
                        getApplicableEnabledCipherSuites(
                                serverDefaultProtocols, false);

            } else {
                // unlikely to be used
                clientDefaultProtocols = null;
                serverDefaultProtocols = null;
                clientDefaultCipherSuites = null;
                serverDefaultCipherSuites = null;
            }
        }

        private static List<ProtocolVersion> customizedProtocols(boolean client,
                List<ProtocolVersion> customized) {
            List<ProtocolVersion> refactored = new ArrayList<>();
            for (ProtocolVersion pv : customized) {
                if (pv.isDTLS) {
                    refactored.add(pv);
                }
            }

            ProtocolVersion[] candidates;
            // Use the default enabled protocols if no customization
            if (refactored.isEmpty()) {
                candidates = new ProtocolVersion[]{
                        ProtocolVersion.DTLS12,
                        ProtocolVersion.DTLS10
                };
            } else {
                // Use the customized TLS protocols.
                candidates =
                        new ProtocolVersion[customized.size()];
                candidates = refactored.toArray(candidates);
            }

            return getAvailableProtocols(candidates);
        }

        protected CustomizedDTLSContext() {
            if (reservedException != null) {
                throw reservedException;
            }
        }

        @Override
        List<ProtocolVersion> getClientDefaultProtocolVersions() {
            return clientDefaultProtocols;
        }

        @Override
        List<ProtocolVersion> getServerDefaultProtocolVersions() {
            return serverDefaultProtocols;
        }

        @Override
        List<CipherSuite> getClientDefaultCipherSuites() {
            return clientDefaultCipherSuites;
        }

        @Override
        List<CipherSuite> getServerDefaultCipherSuites() {
            return serverDefaultCipherSuites;
        }
    }

    /*
     * The SSLContext implementation for default "DTLS" algorithm
     *
     * @see SSLContext
     */
    public static final class DTLSContext extends CustomizedDTLSContext {
        // use the default constructor and methods
    }

}

final class AbstractTrustManagerWrapper extends X509ExtendedTrustManager
            implements X509TrustManager {

    // the delegated trust manager
    private final X509TrustManager tm;

    AbstractTrustManagerWrapper(X509TrustManager tm) {
        this.tm = tm;
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
        tm.checkClientTrusted(chain, authType);
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
        tm.checkServerTrusted(chain, authType);
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return tm.getAcceptedIssuers();
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType,
                Socket socket) throws CertificateException {
        tm.checkClientTrusted(chain, authType);
        checkAdditionalTrust(chain, authType, socket, true);
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType,
            Socket socket) throws CertificateException {
        tm.checkServerTrusted(chain, authType);
        checkAdditionalTrust(chain, authType, socket, false);
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType,
            SSLEngine engine) throws CertificateException {
        tm.checkClientTrusted(chain, authType);
        checkAdditionalTrust(chain, authType, engine, true);
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType,
            SSLEngine engine) throws CertificateException {
        tm.checkServerTrusted(chain, authType);
        checkAdditionalTrust(chain, authType, engine, false);
    }

    private void checkAdditionalTrust(X509Certificate[] chain,
            String authType, Socket socket,
            boolean checkClientTrusted) throws CertificateException {
        if (socket != null && socket.isConnected() &&
                                    socket instanceof SSLSocket) {

            SSLSocket sslSocket = (SSLSocket)socket;
            SSLSession session = sslSocket.getHandshakeSession();
            if (session == null) {
                throw new CertificateException("No handshake session");
            }

            // check endpoint identity
            String identityAlg = sslSocket.getSSLParameters().
                                        getEndpointIdentificationAlgorithm();
            if (identityAlg != null && !identityAlg.isEmpty()) {
                X509TrustManagerImpl.checkIdentity(session, chain,
                                    identityAlg, checkClientTrusted);
            }

            // try the best to check the algorithm constraints
            AlgorithmConstraints constraints;
            if (ProtocolVersion.useTLS12PlusSpec(session.getProtocol())) {
                if (session instanceof ExtendedSSLSession) {
                    ExtendedSSLSession extSession =
                                    (ExtendedSSLSession)session;
                    String[] peerSupportedSignAlgs =
                            extSession.getLocalSupportedSignatureAlgorithms();

                    constraints = SSLAlgorithmConstraints.forSocket(
                                    sslSocket, peerSupportedSignAlgs, true);
                } else {
                    constraints =
                            SSLAlgorithmConstraints.forSocket(sslSocket, true);
                }
            } else {
                constraints = SSLAlgorithmConstraints.forSocket(sslSocket, true);
            }

            checkAlgorithmConstraints(chain, constraints, checkClientTrusted);
        }
    }

    private void checkAdditionalTrust(X509Certificate[] chain,
            String authType, SSLEngine engine,
            boolean checkClientTrusted) throws CertificateException {
        if (engine != null) {
            SSLSession session = engine.getHandshakeSession();
            if (session == null) {
                throw new CertificateException("No handshake session");
            }

            // check endpoint identity
            String identityAlg = engine.getSSLParameters().
                                        getEndpointIdentificationAlgorithm();
            if (identityAlg != null && !identityAlg.isEmpty()) {
                X509TrustManagerImpl.checkIdentity(session, chain,
                                    identityAlg, checkClientTrusted);
            }

            // try the best to check the algorithm constraints
            AlgorithmConstraints constraints;
            if (ProtocolVersion.useTLS12PlusSpec(session.getProtocol())) {
                if (session instanceof ExtendedSSLSession) {
                    ExtendedSSLSession extSession =
                                    (ExtendedSSLSession)session;
                    String[] peerSupportedSignAlgs =
                            extSession.getLocalSupportedSignatureAlgorithms();

                    constraints = SSLAlgorithmConstraints.forEngine(
                                    engine, peerSupportedSignAlgs, true);
                } else {
                    constraints =
                            SSLAlgorithmConstraints.forEngine(engine, true);
                }
            } else {
                constraints = SSLAlgorithmConstraints.forEngine(engine, true);
            }

            checkAlgorithmConstraints(chain, constraints, checkClientTrusted);
        }
    }

    private void checkAlgorithmConstraints(X509Certificate[] chain,
            AlgorithmConstraints constraints,
            boolean checkClientTrusted) throws CertificateException {
        try {
            // Does the certificate chain end with a trusted certificate?
            int checkedLength = chain.length - 1;

            Collection<X509Certificate> trustedCerts = new HashSet<>();
            X509Certificate[] certs = tm.getAcceptedIssuers();
            if ((certs != null) && (certs.length > 0)){
                Collections.addAll(trustedCerts, certs);
            }

            if (trustedCerts.contains(chain[checkedLength])) {
                    checkedLength--;
            }

            // A forward checker, need to check from trust to target
            if (checkedLength >= 0) {
                AlgorithmChecker checker =
                    new AlgorithmChecker(constraints,
                            (checkClientTrusted ? Validator.VAR_TLS_CLIENT :
                                        Validator.VAR_TLS_SERVER));
                checker.init(false);
                for (int i = checkedLength; i >= 0; i--) {
                    X509Certificate cert = chain[i];
                    // We don't care about the unresolved critical extensions.
                    checker.check(cert, Collections.<String>emptySet());
                }
            }
        } catch (CertPathValidatorException cpve) {
            throw new CertificateException(
                "Certificates do not conform to algorithm constraints", cpve);
        }
    }
}

// Dummy X509TrustManager implementation, rejects all peer certificates.
// Used if the application did not specify a proper X509TrustManager.
final class DummyX509TrustManager extends X509ExtendedTrustManager
            implements X509TrustManager {

    static final X509TrustManager INSTANCE = new DummyX509TrustManager();

    private DummyX509TrustManager() {
        // empty
    }

    /*
     * Given the partial or complete certificate chain
     * provided by the peer, build a certificate path
     * to a trusted root and return if it can be
     * validated and is trusted for client SSL authentication.
     * If not, it throws an exception.
     */
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
        throw new CertificateException(
            "No X509TrustManager implementation avaiable");
    }

    /*
     * Given the partial or complete certificate chain
     * provided by the peer, build a certificate path
     * to a trusted root and return if it can be
     * validated and is trusted for server SSL authentication.
     * If not, it throws an exception.
     */
    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
        throw new CertificateException(
            "No X509TrustManager implementation available");
    }

    /*
     * Return an array of issuer certificates which are trusted
     * for authenticating peers.
     */
    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType,
                Socket socket) throws CertificateException {
        throw new CertificateException(
            "No X509TrustManager implementation available");
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType,
            Socket socket) throws CertificateException {
        throw new CertificateException(
            "No X509TrustManager implementation available");
    }

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType,
            SSLEngine engine) throws CertificateException {
        throw new CertificateException(
            "No X509TrustManager implementation available");
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType,
            SSLEngine engine) throws CertificateException {
        throw new CertificateException(
            "No X509TrustManager implementation available");
    }
}

/*
 * A wrapper class to turn a X509KeyManager into an X509ExtendedKeyManager
 */
final class AbstractKeyManagerWrapper extends X509ExtendedKeyManager {

    private final X509KeyManager km;

    AbstractKeyManagerWrapper(X509KeyManager km) {
        this.km = km;
    }

    @Override
    public String[] getClientAliases(String keyType, Principal[] issuers) {
        return km.getClientAliases(keyType, issuers);
    }

    @Override
    public String chooseClientAlias(String[] keyType, Principal[] issuers,
            Socket socket) {
        return km.chooseClientAlias(keyType, issuers, socket);
    }

    @Override
    public String[] getServerAliases(String keyType, Principal[] issuers) {
        return km.getServerAliases(keyType, issuers);
    }

    @Override
    public String chooseServerAlias(String keyType, Principal[] issuers,
            Socket socket) {
        return km.chooseServerAlias(keyType, issuers, socket);
    }

    @Override
    public X509Certificate[] getCertificateChain(String alias) {
        return km.getCertificateChain(alias);
    }

    @Override
    public PrivateKey getPrivateKey(String alias) {
        return km.getPrivateKey(alias);
    }

    // Inherit chooseEngineClientAlias() and chooseEngineServerAlias() from
    // X509ExtendedKeymanager. It defines them to return null;
}


// Dummy X509KeyManager implementation, never returns any certificates/keys.
// Used if the application did not specify a proper X509TrustManager.
final class DummyX509KeyManager extends X509ExtendedKeyManager {

    static final X509ExtendedKeyManager INSTANCE = new DummyX509KeyManager();

    private DummyX509KeyManager() {
        // empty
    }

    /*
     * Get the matching aliases for authenticating the client side of a secure
     * socket given the public key type and the list of
     * certificate issuer authorities recognized by the peer (if any).
     */
    @Override
    public String[] getClientAliases(String keyType, Principal[] issuers) {
        return null;
    }

    /*
     * Choose an alias to authenticate the client side of a secure
     * socket given the public key type and the list of
     * certificate issuer authorities recognized by the peer (if any).
     */
    @Override
    public String chooseClientAlias(String[] keyTypes, Principal[] issuers,
            Socket socket) {
        return null;
    }

    /*
     * Choose an alias to authenticate the client side of an
     * engine given the public key type and the list of
     * certificate issuer authorities recognized by the peer (if any).
     */
    @Override
    public String chooseEngineClientAlias(
            String[] keyTypes, Principal[] issuers, SSLEngine engine) {
        return null;
    }

    /*
     * Get the matching aliases for authenticating the server side of a secure
     * socket given the public key type and the list of
     * certificate issuer authorities recognized by the peer (if any).
     */
    @Override
    public String[] getServerAliases(String keyType, Principal[] issuers) {
        return null;
    }

    /*
     * Choose an alias to authenticate the server side of a secure
     * socket given the public key type and the list of
     * certificate issuer authorities recognized by the peer (if any).
     */
    @Override
    public String chooseServerAlias(String keyType, Principal[] issuers,
            Socket socket) {
        return null;
    }

    /*
     * Choose an alias to authenticate the server side of an engine
     * given the public key type and the list of
     * certificate issuer authorities recognized by the peer (if any).
     */
    @Override
    public String chooseEngineServerAlias(
            String keyType, Principal[] issuers, SSLEngine engine) {
        return null;
    }

    /**
     * Returns the certificate chain associated with the given alias.
     *
     * @param alias the alias name
     *
     * @return the certificate chain (ordered with the user's certificate first
     * and the root certificate authority last)
     */
    @Override
    public X509Certificate[] getCertificateChain(String alias) {
        return null;
    }

    /*
     * Returns the key associated with the given alias, using the given
     * password to recover it.
     *
     * @param alias the alias name
     *
     * @return the requested key
     */
    @Override
    public PrivateKey getPrivateKey(String alias) {
        return null;
    }
}