File: ConnectionTest.java

package info (click to toggle)
openjdk-24 24.0.2%2B12-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 831,900 kB
  • sloc: java: 5,677,020; cpp: 1,323,154; xml: 1,320,524; ansic: 486,889; asm: 405,131; objc: 21,025; sh: 15,221; javascript: 11,049; python: 8,222; makefile: 2,504; perl: 357; awk: 351; sed: 172; pascal: 103; exp: 54; jsp: 24; csh: 3
file content (606 lines) | stat: -rw-r--r-- 21,575 bytes parent folder | download | duplicates (12)
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
/*
 * Copyright (c) 2003, 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.
 *
 * 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.
 */

/*
 * @test
 * @bug 4495742
 * @summary Add non-blocking SSL/TLS functionality, usable with any
 *      I/O abstraction
 * @author Brad Wetmore
 *
 * @run main/othervm ConnectionTest TLSv1.2 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
 * @run main/othervm ConnectionTest TLSv1.3 TLS_AES_256_GCM_SHA384
 */

/*
 * This is a bit hacky, meant to test various conditions.  The main
 * thing I wanted to do with this was to do buffer reads/writes
 * when buffers were not empty.  (buffer.position() = 10)
 * The code could certainly be tightened up a lot.
 */
import javax.net.ssl.*;
import javax.net.ssl.SSLEngineResult.*;
import java.io.*;
import java.security.*;
import java.nio.*;

public class ConnectionTest {

    private final SSLEngine clientEngine;
    private final SSLEngine serverEngine;

    private static final String PATH_TO_STORES = "../etc";
    private static final String KEYSTORE_FILE = "keystore";
    private static final String TRUSTSTORE_FILE = "truststore";

    private static final String KEYSTORE_PATH =
            System.getProperty("test.src", "./") + "/" + PATH_TO_STORES +
                "/" + KEYSTORE_FILE;
    private static final String TRUSTSTORE_PATH =
            System.getProperty("test.src", "./") + "/" + PATH_TO_STORES +
                "/" + TRUSTSTORE_FILE;

    private ByteBuffer clientIn, clientOut;
    private ByteBuffer serverIn, serverOut;
    private ByteBuffer clientToServer, serverToClient;
    private ByteBuffer emptyBuffer;

    private ByteBuffer clientToServerShifter, serverToClientShifter;

    private final String HOSTNAME = "hostname";

    private final int PORT_NUMBER = 77;

    public ConnectionTest(String enabledProtocol, String enabledCipherSuite)
            throws Exception {

        SSLContext sslContext = getSSLContext();
        clientEngine = sslContext.createSSLEngine(HOSTNAME, PORT_NUMBER);
        serverEngine = sslContext.createSSLEngine();

        clientEngine.setEnabledCipherSuites(new String [] {
            enabledCipherSuite});
        clientEngine.setEnabledProtocols(new String[]{enabledProtocol});

        serverEngine.setEnabledCipherSuites(new String [] {
                enabledCipherSuite});
        serverEngine.setEnabledProtocols(new String[]{enabledProtocol});


        createBuffers();
    }

    private SSLContext getSSLContext() throws Exception {
        KeyStore ks = KeyStore.getInstance("JKS");
        KeyStore ts = KeyStore.getInstance("JKS");
        char[] passphrase = "passphrase".toCharArray();

        ks.load(new FileInputStream(KEYSTORE_PATH), passphrase);
        ts.load(new FileInputStream(TRUSTSTORE_PATH), passphrase);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(ts);

        SSLContext sslCtx = SSLContext.getInstance("TLS");

        sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        return sslCtx;
    }

    private void createBuffers() {
        // Size the buffers as appropriate.
        SSLSession session = clientEngine.getSession();
        int appBufferMax = session.getApplicationBufferSize();
        int netBufferMax = session.getPacketBufferSize();

        clientIn = ByteBuffer.allocateDirect(appBufferMax + 10);
        serverIn = ByteBuffer.allocateDirect(appBufferMax + 10);

        clientIn.position(10);
        serverIn.position(10);

        clientToServer = ByteBuffer.allocateDirect(netBufferMax + 10);
        serverToClient = ByteBuffer.allocateDirect(netBufferMax + 10);

        clientToServer.position(10);
        serverToClient.position(10);
        clientToServerShifter = clientToServer.slice();
        serverToClientShifter = serverToClient.slice();

        clientOut = ByteBuffer.wrap("Hi Engine2, I'm SSLEngine1".getBytes());
        serverOut = ByteBuffer.wrap("Hello Engine1, I'm SSLEngine2".getBytes());

        emptyBuffer = ByteBuffer.allocate(10);
        emptyBuffer.limit(5);
        emptyBuffer.position(emptyBuffer.limit());

        log("clientOut = " + clientOut);
        log("serverOut = " + serverOut);
        log("");
    }

    private void checkResult(SSLEngineResult result, Status status,
            HandshakeStatus hsStatus, int consumed, int produced,
            boolean done) {

        if ((status != null) && (result.getStatus() != status)) {
            throw new RuntimeException("Unexpected Status: need = " + status +
                " got = " + result.getStatus());
        }

        if ((hsStatus != null) && (result.getHandshakeStatus() != hsStatus)) {
            throw new RuntimeException("Unexpected hsStatus: need = " + hsStatus +
                " got = " + result.getHandshakeStatus());
        }

        if ((consumed != -1) && (consumed != result.bytesConsumed())) {
            throw new RuntimeException("Unexpected consumed: need = " + consumed +
                " got = " + result.bytesConsumed());
        }

        if ((produced != -1) && (produced != result.bytesProduced())) {
            throw new RuntimeException("Unexpected produced: need = " + produced +
                " got = " + result.bytesProduced());
        }

        if (done && (hsStatus == HandshakeStatus.FINISHED)) {
            throw new RuntimeException(
                "Handshake already reported finished");
        }

    }

    private boolean isHandshaking(SSLEngine e) {
        return (e.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING);
    }

    private void test() throws Exception {
        clientEngine.setUseClientMode(true);
        serverEngine.setUseClientMode(false);
        serverEngine.setNeedClientAuth(true);

        log("Testing for early unwrap/wrap");
        SSLEngineResult result1 = clientEngine.unwrap(serverToClient, clientIn);
        SSLEngineResult result2 = serverEngine.wrap(serverOut, clientToServer);

        /*
         * These should not consume/produce data, because they
         * are client and server, respectively, and don't
         * start handshaking this way.
         */
        checkResult(result1, Status.OK, HandshakeStatus.NEED_WRAP,
            0, 0, false);
        checkResult(result2, Status.OK, HandshakeStatus.NEED_UNWRAP,
            0, 0, false);

        log("Doing Initial Handshake");

        /*
         * Do initial handshaking
         */
        handshake();

        checkEngineAndSession();

        SSLSession clientSession1 = clientEngine.getSession();
        SSLSession serverSession1 = serverEngine.getSession();

        /*
         * Should be able to write/read a small buffer like this.
         */
        int appOut1Len = clientOut.remaining();
        int appOut2Len = serverOut.remaining();
        int net1Len;
        int net2Len;

        result1 = clientEngine.wrap(clientOut, clientToServer);
        checkResult(result1, Status.OK, HandshakeStatus.NOT_HANDSHAKING,
            appOut1Len, -1, false);
        result2 = serverEngine.wrap(serverOut, serverToClient);
        checkResult(result2, Status.OK, HandshakeStatus.NOT_HANDSHAKING,
            appOut2Len, -1, false);
        net1Len = result1.bytesProduced();
        net2Len = result2.bytesProduced();

        log("wrap1 = " + result1);
        log("wrap2 = " + result2);

        clientToServer.flip();
        serverToClient.flip();

        clientToServer.position(10);
        serverToClient.position(10);

        log("----");

        result1 = clientEngine.unwrap(serverToClient, clientIn);
        checkResult(result1, Status.OK, HandshakeStatus.NOT_HANDSHAKING,
            net2Len, appOut2Len, false);
        result2 = serverEngine.unwrap(clientToServer, serverIn);
        checkResult(result2, Status.OK, HandshakeStatus.NOT_HANDSHAKING,
            net1Len, appOut1Len, false);

        log("unwrap1 = " + result1);
        log("unwrap2 = " + result2);

        updateByteBuffers();

        serverSession1.invalidate();
        serverEngine.beginHandshake();

        log("\nRENEGOTIATING");
        log("=============");

        clientIn.clear();
        serverIn.clear();

        /*
         * Do a quick test to see if this can do a switch
         * into client mode, at this point, you shouldn't be able
         * to switch back.
         */
        try {
            log("Try to change client mode");
            serverEngine.setUseClientMode(true);
            throw new RuntimeException("Should have thrown IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            log("Caught correct IllegalArgumentException");
        }

        handshake();

        SSLSession clientSession2 = clientEngine.getSession();
        SSLSession serverSession2 = serverEngine.getSession();


        log("\nDoing close");
        log("===========");

        clientEngine.closeOutbound();
        serverEngine.closeOutbound();

        clientToServer.flip();
        serverToClient.flip();
        clientToServer.position(10);
        serverToClient.position(10);

        clientIn.clear();
        serverIn.clear();

        log("LAST UNWRAP");
        result1 = clientEngine.unwrap(serverToClient, clientIn);
        checkResult(result1, Status.BUFFER_UNDERFLOW,
            HandshakeStatus.NEED_WRAP, 0, 0, false);
        result2 = serverEngine.unwrap(clientToServer, serverIn);
        checkResult(result2, Status.BUFFER_UNDERFLOW,
            HandshakeStatus.NEED_WRAP, 0, 0, false);

        log("unwrap1 = " + result1);
        log("unwrap2 = " + result2);

        updateByteBuffers();

        log("LAST WRAP");
        result1 = clientEngine.wrap(clientOut, clientToServer);
        checkResult(result1, Status.CLOSED, HandshakeStatus.NOT_HANDSHAKING,
            0, -1, false);
        result2 = serverEngine.wrap(serverOut, serverToClient);
        checkResult(result2, Status.CLOSED, HandshakeStatus.NOT_HANDSHAKING,
            0, -1, false);

        log("wrap1 = " + result1);
        log("wrap2 = " + result2);

        net1Len = result1.bytesProduced();
        net2Len = result2.bytesProduced();

        clientToServer.flip();
        serverToClient.flip();

        clientToServer.position(10);
        serverToClient.position(10);

        result1 = clientEngine.unwrap(serverToClient, clientIn);
        checkResult(result1, Status.CLOSED, HandshakeStatus.NOT_HANDSHAKING,
            net1Len, 0, false);
        result2 = serverEngine.unwrap(clientToServer, serverIn);
        checkResult(result2, Status.CLOSED, HandshakeStatus.NOT_HANDSHAKING,
            net2Len, 0, false);

        log("unwrap1 = " + result1);
        log("unwrap2 = " + result2);

        updateByteBuffers();

        log("EXTRA WRAP");
        result1 = clientEngine.wrap(clientOut, clientToServer);
        checkResult(result1, Status.CLOSED, HandshakeStatus.NOT_HANDSHAKING,
            0, 0, false);
        result2 = serverEngine.wrap(serverOut, serverToClient);
        checkResult(result2, Status.CLOSED, HandshakeStatus.NOT_HANDSHAKING,
            0, 0, false);

        log("wrap1 = " + result1);
        log("wrap2 = " + result2);

        clientToServer.flip();
        serverToClient.flip();
        clientToServer.position(10);
        serverToClient.position(10);

        log("EXTRA UNWRAP");
        result1 = clientEngine.unwrap(serverToClient, clientIn);
        checkResult(result1, Status.CLOSED, HandshakeStatus.NOT_HANDSHAKING,
            0, 0, false);
        result2 = serverEngine.unwrap(clientToServer, serverIn);
        checkResult(result2, Status.CLOSED, HandshakeStatus.NOT_HANDSHAKING,
            0, 0, false);

        log("unwrap1 = " + result1);
        log("unwrap2 = " + result2);

        checkSession(clientSession1, serverSession1, clientSession2, serverSession2);
        log(clientEngine);
        log(serverEngine);
    }

    private void handshake() throws Exception {
        boolean clientDone = false;
        boolean serverDone = false;
        SSLEngineResult result2;
        SSLEngineResult result1;
        while (isHandshaking(clientEngine) ||
                isHandshaking(serverEngine)) {

            log("================");

            result1 = clientEngine.wrap(emptyBuffer, clientToServer);
            checkResult(result1, null, null, 0, -1, clientDone);
            result2 = serverEngine.wrap(emptyBuffer, serverToClient);
            checkResult(result2, null, null, 0, -1, serverDone);

            if (result1.getHandshakeStatus() == HandshakeStatus.FINISHED) {
                clientDone = true;
            }

            if (result2.getHandshakeStatus() == HandshakeStatus.FINISHED) {
                serverDone = true;
            }

            log("wrap1 = " + result1);
            log("wrap2 = " + result2);

            if (result1.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
                Runnable runnable;
                while ((runnable = clientEngine.getDelegatedTask()) != null) {
                    runnable.run();
                }
            }

            if (result2.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
                Runnable runnable;
                while ((runnable = serverEngine.getDelegatedTask()) != null) {
                    runnable.run();
                }
            }

            clientToServer.flip();
            serverToClient.flip();

            clientToServer.position(10);
            serverToClient.position(10);

            log("----");

            result1 = clientEngine.unwrap(serverToClient, clientIn);
            checkResult(result1, null, null, -1, 0, clientDone);
            result2 = serverEngine.unwrap(clientToServer, serverIn);
            checkResult(result2, null, null, -1, 0, serverDone);

            if (result1.getHandshakeStatus() == HandshakeStatus.FINISHED) {
                clientDone = true;
            }

            if (result2.getHandshakeStatus() == HandshakeStatus.FINISHED) {
                serverDone = true;
            }

            log("unwrap1 = " + result1);
            log("unwrap2 = " + result2);

            if (result1.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
                Runnable runnable;
                while ((runnable = clientEngine.getDelegatedTask()) != null) {
                    runnable.run();
                }
            }

            if (result2.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
                Runnable runnable;
                while ((runnable = serverEngine.getDelegatedTask()) != null) {
                    runnable.run();
                }
            }

            updateByteBuffers();
        }


        log("\nDONE HANDSHAKING");
        log("================");

        if (!clientDone || !serverDone) {
            throw new RuntimeException("Both should be true:\n" +
                    " clientDone = " + clientDone + " serverDone = " + serverDone);
        }
    }

    private void updateByteBuffers() {
        clientToServerShifter.position(clientToServer.position() - 10);
        clientToServerShifter.limit(clientToServer.limit() - 10);
        serverToClientShifter.position(serverToClient.position() - 10);
        serverToClientShifter.limit(serverToClient.limit() - 10);
        clientToServerShifter.compact();
        serverToClientShifter.compact();
        clientToServer.position(clientToServerShifter.position() + 10);
        clientToServer.limit(clientToServerShifter.limit() + 10);
        serverToClient.position(serverToClientShifter.position() + 10);
        serverToClient.limit(serverToClientShifter.limit() + 10);
    }

    private static void checkSession(SSLSession clientSession1, SSLSession serverSession1,
            SSLSession clientSession2, SSLSession serverSession2) {
        log("\nSession Info for client SSLEngine 1");
        log(clientSession1);
        log(clientSession1.getCreationTime());

        String peer1 = clientSession1.getPeerHost();
        log(peer1);

        String protocol1 = clientSession1.getProtocol();
        log(protocol1);

        String ciphersuite1 = clientSession1.getCipherSuite();
        log(ciphersuite1);
        log("");

        log("\nSession Info for server SSLEngine 1");
        log(serverSession1);
        log(serverSession1.getCreationTime());

        String peer2 = serverSession1.getPeerHost();
        log(peer2);

        String protocol2 = serverSession1.getProtocol();
        log(protocol2);

        String ciphersuite2 = serverSession1.getCipherSuite();
        log(ciphersuite2);
        log("");

        if (peer1.equals(peer2)) {
            throw new RuntimeException("peer hostnames not equal");
        }

        if (!protocol1.equals(protocol2)) {
            throw new RuntimeException("protocols not equal");
        }

        compareCertificates(clientSession1, serverSession1);
        compareCertificates(clientSession2, serverSession2);

        if (!ciphersuite1.equals(ciphersuite2)) {
            throw new RuntimeException("ciphersuites not equal");
        }

        log("\nSession Info for client SSLEngine 2");
        log(clientSession2);
        log("\nSession Info for server SSLEngine 2");
        log(serverSession2);
    }


    private static void compareCertificates(SSLSession client, SSLSession server) {
        try {
            java.security.cert.Certificate clientLocal = client.getLocalCertificates()[0];
            java.security.cert.Certificate clientPeer = client.getPeerCertificates()[0];
            java.security.cert.Certificate serverLocal = server.getLocalCertificates()[0];
            java.security.cert.Certificate serverPeer = server.getPeerCertificates()[0];

            log(String.format("Client local cert: %s%nClient peer cert: %s%n"
                    + "Server local cert: %s%nServer peer cert: %s%n",
                    clientLocal, clientPeer, serverLocal, serverPeer));

            if (!clientLocal.equals(serverPeer)) {
                throw new RuntimeException("Client's local certificate does "
                        + "not match server's peer certificate");
            }

            if (!clientPeer.equals(serverLocal)) {
                throw new RuntimeException("Client's peer certificate does "
                        + "not match server's local certificate");
            }

        } catch (SSLPeerUnverifiedException e) {
            throw new RuntimeException("Could not get peer certificate!", e);
        }
    }

    private void checkEngineAndSession()
            throws Exception {
        String host = clientEngine.getPeerHost();
        int port = clientEngine.getPeerPort();
        if (!host.equals(HOSTNAME) || (port != PORT_NUMBER)) {
            throw new Exception("Unexpected host/port from client engine."
                    + " Expected " + HOSTNAME + ":" + PORT_NUMBER
                    + " Received " +host + ":" + port);
        }

        host = serverEngine.getPeerHost();
        port = serverEngine.getPeerPort();
        if ((host != null) || (port != -1)) {
            throw new Exception("Unexpected host/port from server engine."
                    + " Expected null:-1"
                    + " Received " + host + ":" + port);
        }

        SSLSession clientSession = clientEngine.getSession();

        host = clientSession.getPeerHost();
        port = clientSession.getPeerPort();
        if (!host.equals(HOSTNAME) || (port != PORT_NUMBER)) {
            throw new Exception("Unexpected host/port from client session."
                    + " Expected " + HOSTNAME + ":" + PORT_NUMBER
                    + " Received " + host + ":" + port);
        }

        SSLSession serverSession = serverEngine.getSession();

        host = serverSession.getPeerHost();
        port = serverSession.getPeerPort();
        if ((host != null) || (port != -1)) {
            throw new Exception("Unexpected host/port from server session."
                    + " Expected null:-1"
                    + " Received " + host + ":" + port);
        }

    }

    private static void log(Object msg) {
        System.out.println(msg);
    }

    public static void main(String args[]) throws Exception {
        // reset the security property to make sure that the algorithms
        // and keys used in this test are not disabled.
        Security.setProperty("jdk.tls.disabledAlgorithms", "");

        log(String.format("Running with %s and %s%n", args[0], args[1]));
        ConnectionTest ct = new ConnectionTest(args[0], args[1]);
        ct.test();
    }
}