File: SSLEngineEmptyFragments.java

package info (click to toggle)
openjdk-21 21.0.8%2B9-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 823,976 kB
  • sloc: java: 5,613,338; xml: 1,643,607; cpp: 1,296,296; ansic: 420,291; asm: 404,850; objc: 20,994; sh: 15,271; javascript: 11,245; python: 6,895; makefile: 2,362; perl: 357; awk: 351; sed: 172; jsp: 24; csh: 3
file content (268 lines) | stat: -rw-r--r-- 10,367 bytes parent folder | download | duplicates (10)
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
/*
 * Copyright (c) 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 8182621
 * @summary Verify the SSLEngine rejects empty Handshake, Alert, and ChangeCipherSpec messages.
 * @library /javax/net/ssl/templates
 * @run main SSLEngineEmptyFragments
 */
import java.nio.ByteBuffer;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.*;

public class SSLEngineEmptyFragments extends SSLContextTemplate {
    private static final byte HANDSHAKE_TYPE = 22;
    private static final byte ALERT_TYPE = 21;
    private static final byte CHANGE_CIPHERSPEC_TYPE = 20;
    private static final String TLSv12 = "TLSv1.2";
    private static final String TLSv13 = "TLSv1.3";

    private SSLEngine serverEngine;
    private SSLEngine clientEngine;
    private ByteBuffer clientIn;
    private ByteBuffer serverIn;
    private ByteBuffer clientToServer;
    private ByteBuffer serverToClient;
    private ByteBuffer clientOut;
    private ByteBuffer serverOut;

    private final String protocol;

    public SSLEngineEmptyFragments(String protocol) {
        this.protocol = protocol;
    }

    private void initialize() throws Exception {
        initialize(null);
    }

    private void initialize(String [] protocols) throws Exception {
        serverEngine = createServerSSLContext().createSSLEngine();
        clientEngine = createClientSSLContext().createSSLEngine();

        serverEngine.setUseClientMode(false);
        clientEngine.setUseClientMode(true);

        if (protocols != null) {
            clientEngine.setEnabledProtocols(protocols);
            serverEngine.setEnabledProtocols(protocols);
        }

        // do one legitimate handshake packet, then send a zero-length alert.
        SSLSession session = clientEngine.getSession();
        int appBufferMax = session.getApplicationBufferSize();
        int netBufferMax = session.getPacketBufferSize();

        // We'll make the input buffers a bit bigger than the max needed
        // size, so that unwrap()s following a successful data transfer
        // won't generate BUFFER_OVERFLOWS.
        //
        // We'll use a mix of direct and indirect ByteBuffers for
        // tutorial purposes only.  In reality, only use direct
        // ByteBuffers when they give a clear performance enhancement.
        clientIn = ByteBuffer.allocate(appBufferMax + 50);
        serverIn = ByteBuffer.allocate(appBufferMax + 50);

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

        clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes());
        serverOut = ByteBuffer.wrap("Hello Client, I'm Server".getBytes());
    }

    private void testAlertPacketNotHandshaking() throws Exception {
        log("**** Empty alert packet/not handshaking");
        initialize();

        ByteBuffer alert = ByteBuffer.allocate(5);
        alert.put(new byte[]{ALERT_TYPE, 3, 3, 0, 0});
        alert.flip();

        try {
            unwrap(serverEngine, alert, serverIn);
            throw new RuntimeException("Expected exception was not thrown.");
        } catch (SSLHandshakeException exc) {
            log("Got the exception I wanted.");
        }
    }

    private void testAlertPacketMidHandshake() throws Exception {
        log("**** Empty alert packet during handshake.");
        initialize(new String[]{protocol});

        wrap(clientEngine, clientOut, clientToServer);
        runDelegatedTasks(clientEngine);
        clientToServer.flip();

        unwrap(serverEngine, clientToServer, serverIn);
        runDelegatedTasks(serverEngine);

        while(serverEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_WRAP) {
            wrap(serverEngine, serverOut, serverToClient);
            runDelegatedTasks(serverEngine);
            serverToClient.flip();
        }

        ByteBuffer alert = ByteBuffer.allocate(5);
        alert.put(new byte[]{ALERT_TYPE, 3, 3, 0, 0});
        alert.flip();

        try {
            unwrap(serverEngine, alert, serverIn);
            log("Server unwrap was successful when it should have failed.");
            throw new RuntimeException("Expected exception was not thrown.");
        } catch (SSLHandshakeException exc) {
            log("Got the exception I wanted.");
        }
    }

    private void testHandshakePacket() throws NoSuchAlgorithmException, SSLException {
        log("**** Empty handshake package.");
        SSLContext ctx = SSLContext.getDefault();
        SSLEngine engine = ctx.createSSLEngine();
        engine.setUseClientMode(false);

        try {
            ByteBuffer bb = ByteBuffer.allocate(5);
            bb.put(new byte[]{HANDSHAKE_TYPE, 3, 3, 0, 0});
            bb.flip();
            ByteBuffer out = ByteBuffer.allocate(engine.getSession().getPacketBufferSize());
            engine.unwrap(bb, out);
            throw new RuntimeException("SSLEngine did not throw an exception for a zero-length fragment.");
        } catch (SSLProtocolException exc) {
            log("Received expected exception");
        }
    }

    private void testEmptyChangeCipherSpec() throws Exception {
        initialize(new String[]{protocol});

        boolean foundCipherSpecMsg = false;
        do {
            log("Client wrap");
            wrap(clientEngine, clientOut, clientToServer);
            runDelegatedTasks(clientEngine);

            if(clientToServer.get(0) == CHANGE_CIPHERSPEC_TYPE) {
                foundCipherSpecMsg = true;
                break;
            }

            log("server wrap");
            wrap(serverEngine, serverOut, serverToClient);
            runDelegatedTasks(serverEngine);

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

            log("client unwrap");
            unwrap(clientEngine, serverToClient, clientIn);
            runDelegatedTasks(clientEngine);

            log("server unwrap");
            unwrap(serverEngine, clientToServer, serverIn);
            runDelegatedTasks(serverEngine);

            clientToServer.compact();
            serverToClient.compact();
        } while(clientEngine.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.FINISHED
            && serverEngine.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.FINISHED);

        if (!foundCipherSpecMsg) {
            // performed TLS handshaking but didn't catch change-cipherspec message.
            throw new RuntimeException("Did not intercept ChangeCipherSpec message.");
        }

        ByteBuffer changeCipher = ByteBuffer.allocate(5);
        changeCipher.put(new byte[]{CHANGE_CIPHERSPEC_TYPE, 3, 3, 0, 0});
        changeCipher.flip();
        try {
            unwrap(serverEngine, changeCipher, serverIn);
            throw new RuntimeException("Didn't get the expected SSL exception");
        } catch (SSLProtocolException exc) {
            log("Received expected exception.");
        }
    }

    private SSLEngineResult wrap(SSLEngine engine, ByteBuffer src, ByteBuffer dst) throws SSLException {
        SSLEngineResult result = engine.wrap(src, dst);
        logEngineStatus(engine, result);
        return result;
    }

    private SSLEngineResult unwrap(SSLEngine engine, ByteBuffer src, ByteBuffer dst) throws SSLException {
        SSLEngineResult result = engine.unwrap(src, dst);
        logEngineStatus(engine, result);
        return result;
    }

    protected void runDelegatedTasks(SSLEngine engine) throws Exception {
        if (engine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) {
            Runnable runnable;
            while ((runnable = engine.getDelegatedTask()) != null) {
                log("    running delegated task...");
                runnable.run();
            }
            SSLEngineResult.HandshakeStatus hsStatus = engine.getHandshakeStatus();
            if (hsStatus == SSLEngineResult.HandshakeStatus.NEED_TASK) {
                throw new Exception(
                        "handshake shouldn't need additional tasks");
            }
            logEngineStatus(engine);
        }
    }

    private void logEngineStatus(SSLEngine engine) {
        log("\tCurrent HS State: " + engine.getHandshakeStatus());
        log("\tisInboundDone() : " + engine.isInboundDone());
        log("\tisOutboundDone(): " + engine.isOutboundDone());
    }

    private void logEngineStatus(
            SSLEngine engine, SSLEngineResult result) {
        log("\tResult Status    : " + result.getStatus());
        log("\tResult HS Status : " + result.getHandshakeStatus());
        log("\tEngine HS Status : " + engine.getHandshakeStatus());
        log("\tisInboundDone()  : " + engine.isInboundDone());
        log("\tisOutboundDone() : " + engine.isOutboundDone());
        log("\tMore Result      : " + result);
    }

    private void log(String message) {
        System.err.println(message);
    }

    public static void main(String [] args) throws Exception {
        SSLEngineEmptyFragments tests = new SSLEngineEmptyFragments(TLSv12);
        tests.testHandshakePacket();
        tests.testAlertPacketNotHandshaking();
        tests.testAlertPacketMidHandshake();
        tests.testEmptyChangeCipherSpec();

        tests = new SSLEngineEmptyFragments(TLSv13);
        tests.testHandshakePacket();
        tests.testAlertPacketNotHandshaking();
    }
}