ShortRSAKey512.java revision 14757:8e78ddac0b20
1/*
2 * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26// This test case relies on updated static security property, no way to re-use
27// security property in samevm/agentvm mode.
28
29/*
30 * @test
31 * @bug 7106773
32 * @summary 512 bits RSA key cannot work with SHA384 and SHA512
33 *
34 *     SunJSSE does not support dynamic system properties, no way to re-use
35 *     system properties in samevm/agentvm mode.
36 * @key intermittent
37 * @run main/othervm ShortRSAKey512 PKIX
38 * @run main/othervm ShortRSAKey512 SunX509
39 */
40
41import java.net.*;
42import java.util.*;
43import java.io.*;
44import javax.net.ssl.*;
45import java.security.Security;
46import java.security.KeyStore;
47import java.security.KeyFactory;
48import java.security.cert.Certificate;
49import java.security.cert.CertificateFactory;
50import java.security.spec.*;
51import java.security.interfaces.*;
52import java.util.Base64;
53
54
55public class ShortRSAKey512 {
56
57    /*
58     * =============================================================
59     * Set the various variables needed for the tests, then
60     * specify what tests to run on each side.
61     */
62
63    /*
64     * Should we run the client or server in a separate thread?
65     * Both sides can throw exceptions, but do you have a preference
66     * as to which side should be the main thread.
67     */
68    static boolean separateServerThread = false;
69
70    /*
71     * Where do we find the keystores?
72     */
73    // Certificates and key used in the test.
74    static String trustedCertStr =
75        "-----BEGIN CERTIFICATE-----\n" +
76        "MIICkjCCAfugAwIBAgIBADANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" +
77        "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" +
78        "MTEwODE5MDE1MjE5WhcNMzIwNzI5MDE1MjE5WjA7MQswCQYDVQQGEwJVUzENMAsG\n" +
79        "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwgZ8wDQYJ\n" +
80        "KoZIhvcNAQEBBQADgY0AMIGJAoGBAM8orG08DtF98TMSscjGsidd1ZoN4jiDpi8U\n" +
81        "ICz+9dMm1qM1d7O2T+KH3/mxyox7Rc2ZVSCaUD0a3CkhPMnlAx8V4u0H+E9sqso6\n" +
82        "iDW3JpOyzMExvZiRgRG/3nvp55RMIUV4vEHOZ1QbhuqG4ebN0Vz2DkRft7+flthf\n" +
83        "vDld6f5JAgMBAAGjgaUwgaIwHQYDVR0OBBYEFLl81dnfp0wDrv0OJ1sxlWzH83Xh\n" +
84        "MGMGA1UdIwRcMFqAFLl81dnfp0wDrv0OJ1sxlWzH83XhoT+kPTA7MQswCQYDVQQG\n" +
85        "EwJVUzENMAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2\n" +
86        "Y2WCAQAwDwYDVR0TAQH/BAUwAwEB/zALBgNVHQ8EBAMCAQYwDQYJKoZIhvcNAQEE\n" +
87        "BQADgYEALlgaH1gWtoBZ84EW8Hu6YtGLQ/L9zIFmHonUPZwn3Pr//icR9Sqhc3/l\n" +
88        "pVTxOINuFHLRz4BBtEylzRIOPzK3tg8XwuLb1zd0db90x3KBCiAL6E6cklGEPwLe\n" +
89        "XYMHDn9eDsaq861Tzn6ZwzMgw04zotPMoZN0mVd/3Qca8UJFucE=\n" +
90        "-----END CERTIFICATE-----";
91
92    static String targetCertStr =
93        "-----BEGIN CERTIFICATE-----\n" +
94        "MIICNDCCAZ2gAwIBAgIBDDANBgkqhkiG9w0BAQQFADA7MQswCQYDVQQGEwJVUzEN\n" +
95        "MAsGA1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UwHhcN\n" +
96        "MTExMTA3MTM1NTUyWhcNMzEwNzI1MTM1NTUyWjBPMQswCQYDVQQGEwJVUzENMAsG\n" +
97        "A1UEChMESmF2YTEdMBsGA1UECxMUU3VuSlNTRSBUZXN0IFNlcml2Y2UxEjAQBgNV\n" +
98        "BAMTCWxvY2FsaG9zdDBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQC3Pb49OSPfOD2G\n" +
99        "HSXFCFx1GJEZfqG9ZUf7xuIi/ra5dLjPGAaoY5QF2QOa8VnOriQCXDfyXHxsuRnE\n" +
100        "OomxL7EVAgMBAAGjeDB2MAsGA1UdDwQEAwID6DAdBgNVHQ4EFgQUXNCJK3/dtCIc\n" +
101        "xb+zlA/JINlvs/MwHwYDVR0jBBgwFoAUuXzV2d+nTAOu/Q4nWzGVbMfzdeEwJwYD\n" +
102        "VR0lBCAwHgYIKwYBBQUHAwEGCCsGAQUFBwMCBggrBgEFBQcDAzANBgkqhkiG9w0B\n" +
103        "AQQFAAOBgQB2qIDUxA2caMPpGtUACZAPRUtrGssCINIfItETXJZCx/cRuZ5sP4D9\n" +
104        "N1acoNDn0hCULe3lhXAeTC9NZ97680yJzregQMV5wATjo1FGsKY30Ma+sc/nfzQW\n" +
105        "+h/7RhYtoG0OTsiaDCvyhI6swkNJzSzrAccPY4+ZgU8HiDLzZTmM3Q==\n" +
106        "-----END CERTIFICATE-----";
107
108    // Private key in the format of PKCS#8, key size is 512 bits.
109    static String targetPrivateKey =
110        "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAtz2+PTkj3zg9hh0l\n" +
111        "xQhcdRiRGX6hvWVH+8biIv62uXS4zxgGqGOUBdkDmvFZzq4kAlw38lx8bLkZxDqJ\n" +
112        "sS+xFQIDAQABAkByx/5Oo2hQ/w2q4L8z+NTRlJ3vdl8iIDtC/4XPnfYfnGptnpG6\n" +
113        "ZThQRvbMZiai0xHQPQMszvAHjZVme1eDl3EBAiEA3aKJHynPVCEJhpfCLWuMwX5J\n" +
114        "1LntwJO7NTOyU5m8rPECIQDTpzn5X44r2rzWBDna/Sx7HW9IWCxNgUD2Eyi2nA7W\n" +
115        "ZQIgJerEorw4aCAuzQPxiGu57PB6GRamAihEAtoRTBQlH0ECIQDN08FgTtnesgCU\n" +
116        "DFYLLcw1CiHvc7fZw4neBDHCrC8NtQIgA8TOUkGnpCZlQ0KaI8KfKWI+vxFcgFnH\n" +
117        "3fnqsTgaUs4=";
118
119    static char passphrase[] = "passphrase".toCharArray();
120
121    /*
122     * Is the server ready to serve?
123     */
124    volatile static boolean serverReady = false;
125
126    /*
127     * Turn on SSL debugging?
128     */
129    static boolean debug = false;
130
131    /*
132     * Define the server side of the test.
133     *
134     * If the server prematurely exits, serverReady will be set to true
135     * to avoid infinite hangs.
136     */
137    void doServerSide() throws Exception {
138        SSLContext context = generateSSLContext(null, targetCertStr,
139                                            targetPrivateKey);
140        SSLServerSocketFactory sslssf = context.getServerSocketFactory();
141        SSLServerSocket sslServerSocket =
142            (SSLServerSocket)sslssf.createServerSocket(serverPort);
143        serverPort = sslServerSocket.getLocalPort();
144
145        /*
146         * Signal Client, we're ready for his connect.
147         */
148        serverReady = true;
149
150        SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept();
151        InputStream sslIS = sslSocket.getInputStream();
152        OutputStream sslOS = sslSocket.getOutputStream();
153
154        sslIS.read();
155        sslOS.write('A');
156        sslOS.flush();
157
158        sslSocket.close();
159    }
160
161    /*
162     * Define the client side of the test.
163     *
164     * If the server prematurely exits, serverReady will be set to true
165     * to avoid infinite hangs.
166     */
167    void doClientSide() throws Exception {
168
169        /*
170         * Wait for server to get started.
171         */
172        while (!serverReady) {
173            Thread.sleep(50);
174        }
175
176        SSLContext context = generateSSLContext(trustedCertStr, null, null);
177        SSLSocketFactory sslsf = context.getSocketFactory();
178
179        SSLSocket sslSocket =
180            (SSLSocket)sslsf.createSocket("localhost", serverPort);
181
182        // enable TLSv1.2 only
183        sslSocket.setEnabledProtocols(new String[] {"TLSv1.2"});
184
185        // enable a block cipher
186        sslSocket.setEnabledCipherSuites(
187            new String[] {"TLS_DHE_RSA_WITH_AES_128_CBC_SHA"});
188
189        InputStream sslIS = sslSocket.getInputStream();
190        OutputStream sslOS = sslSocket.getOutputStream();
191
192        sslOS.write('B');
193        sslOS.flush();
194        sslIS.read();
195
196        sslSocket.close();
197    }
198
199    /*
200     * =============================================================
201     * The remainder is just support stuff
202     */
203    private static String tmAlgorithm;        // trust manager
204
205    private static void parseArguments(String[] args) {
206        tmAlgorithm = args[0];
207    }
208
209    private static SSLContext generateSSLContext(String trustedCertStr,
210            String keyCertStr, String keySpecStr) throws Exception {
211
212        // generate certificate from cert string
213        CertificateFactory cf = CertificateFactory.getInstance("X.509");
214
215        // create a key store
216        KeyStore ks = KeyStore.getInstance("JKS");
217        ks.load(null, null);
218
219        // import the trused cert
220        Certificate trusedCert = null;
221        ByteArrayInputStream is = null;
222        if (trustedCertStr != null) {
223            is = new ByteArrayInputStream(trustedCertStr.getBytes());
224            trusedCert = cf.generateCertificate(is);
225            is.close();
226
227            ks.setCertificateEntry("RSA Export Signer", trusedCert);
228        }
229
230        if (keyCertStr != null) {
231            // generate the private key.
232            PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
233                                Base64.getMimeDecoder().decode(keySpecStr));
234            KeyFactory kf = KeyFactory.getInstance("RSA");
235            RSAPrivateKey priKey =
236                    (RSAPrivateKey)kf.generatePrivate(priKeySpec);
237
238            // generate certificate chain
239            is = new ByteArrayInputStream(keyCertStr.getBytes());
240            Certificate keyCert = cf.generateCertificate(is);
241            is.close();
242
243            Certificate[] chain = null;
244            if (trusedCert != null) {
245                chain = new Certificate[2];
246                chain[0] = keyCert;
247                chain[1] = trusedCert;
248            } else {
249                chain = new Certificate[1];
250                chain[0] = keyCert;
251            }
252
253            // import the key entry.
254            ks.setKeyEntry("Whatever", priKey, passphrase, chain);
255        }
256
257        // create SSL context
258        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
259        tmf.init(ks);
260
261        SSLContext ctx = SSLContext.getInstance("TLS");
262        if (keyCertStr != null && !keyCertStr.isEmpty()) {
263            KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
264            kmf.init(ks, passphrase);
265
266            ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
267            ks = null;
268        } else {
269            ctx.init(null, tmf.getTrustManagers(), null);
270        }
271
272        return ctx;
273    }
274
275
276    // use any free port by default
277    volatile int serverPort = 0;
278
279    volatile Exception serverException = null;
280    volatile Exception clientException = null;
281
282    public static void main(String[] args) throws Exception {
283        // reset the security property to make sure that the algorithms
284        // and keys used in this test are not disabled.
285        Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");
286        Security.setProperty("jdk.tls.disabledAlgorithms",
287                "SSLv3, RC4, DH keySize < 768");
288
289        if (debug)
290            System.setProperty("javax.net.debug", "all");
291
292        /*
293         * Get the customized arguments.
294         */
295        parseArguments(args);
296
297        /*
298         * Start the tests.
299         */
300        new ShortRSAKey512();
301    }
302
303    Thread clientThread = null;
304    Thread serverThread = null;
305
306    /*
307     * Primary constructor, used to drive remainder of the test.
308     *
309     * Fork off the other side, then do your work.
310     */
311    ShortRSAKey512() throws Exception {
312        try {
313            if (separateServerThread) {
314                startServer(true);
315                startClient(false);
316            } else {
317                startClient(true);
318                startServer(false);
319            }
320        } catch (Exception e) {
321            // swallow for now.  Show later
322        }
323
324        /*
325         * Wait for other side to close down.
326         */
327        if (separateServerThread) {
328            serverThread.join();
329        } else {
330            clientThread.join();
331        }
332
333        /*
334         * When we get here, the test is pretty much over.
335         * Which side threw the error?
336         */
337        Exception local;
338        Exception remote;
339        String whichRemote;
340
341        if (separateServerThread) {
342            remote = serverException;
343            local = clientException;
344            whichRemote = "server";
345        } else {
346            remote = clientException;
347            local = serverException;
348            whichRemote = "client";
349        }
350
351        /*
352         * If both failed, return the curthread's exception, but also
353         * print the remote side Exception
354         */
355        if ((local != null) && (remote != null)) {
356            System.out.println(whichRemote + " also threw:");
357            remote.printStackTrace();
358            System.out.println();
359            throw local;
360        }
361
362        if (remote != null) {
363            throw remote;
364        }
365
366        if (local != null) {
367            throw local;
368        }
369    }
370
371    void startServer(boolean newThread) throws Exception {
372        if (newThread) {
373            serverThread = new Thread() {
374                public void run() {
375                    try {
376                        doServerSide();
377                    } catch (Exception e) {
378                        /*
379                         * Our server thread just died.
380                         *
381                         * Release the client, if not active already...
382                         */
383                        System.err.println("Server died...");
384                        serverReady = true;
385                        serverException = e;
386                    }
387                }
388            };
389            serverThread.start();
390        } else {
391            try {
392                doServerSide();
393            } catch (Exception e) {
394                serverException = e;
395            } finally {
396                serverReady = true;
397            }
398        }
399    }
400
401    void startClient(boolean newThread) throws Exception {
402        if (newThread) {
403            clientThread = new Thread() {
404                public void run() {
405                    try {
406                        doClientSide();
407                    } catch (Exception e) {
408                        /*
409                         * Our client thread just died.
410                         */
411                        System.err.println("Client died...");
412                        clientException = e;
413                    }
414                }
415            };
416            clientThread.start();
417        } else {
418            try {
419                doClientSide();
420            } catch (Exception e) {
421                clientException = e;
422            }
423        }
424    }
425}
426