File: SSLSocketEmptyFragments.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 (366 lines) | stat: -rw-r--r-- 14,280 bytes parent folder | download | duplicates (8)
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
/*
 * 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 JSSE rejects empty Handshake, Alert, and ChangeCipherSpec messages.
 * @library /javax/net/ssl/templates
 * @run main SSLSocketEmptyFragments
 */

import javax.net.ssl.*;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.concurrent.*;
import java.util.function.Consumer;

public class SSLSocketEmptyFragments extends SSLContextTemplate {
    private static final boolean DEBUG = Boolean.getBoolean("test.debug");
    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 byte[] INVALID_ALERT = {ALERT_TYPE, 3, 3, 0, 0};

    private static final byte[] INVALID_HANDSHAKE = {HANDSHAKE_TYPE, 3, 3, 0, 0};
    private static final int SERVER_WAIT_SEC = 5;
    private static final String TLSv13 = "TLSv1.3";
    private static final String TLSv12 = "TLSv1.2";

    private final String protocol;

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


    private void testEmptyHandshakeRecord(Socket client) {
        log("Sending bad handshake packet to server...");

        try {
            OutputStream os = client.getOutputStream();
            os.write(INVALID_HANDSHAKE);
            os.flush();
        } catch (IOException exc) {
            throw new RuntimeException("Unexpected IOException thrown by socket operations", exc);
        }
    }


    private void testEmptyAlertNotHandshaking(Socket client) {
        log("Sending empty alert packet before handshaking starts.");

        try {
            OutputStream os = client.getOutputStream();
            os.write(INVALID_ALERT);
            os.flush();
        } catch (IOException exc) {
            throw new RuntimeException("Unexpected IOException thrown by socket operations.", exc);
        }
    }

    /**
     * Runs a test where the server -- in a separate thread -- accepts a connection
     * and attempts to read from the remote side. Tests are successful if the
     * server thread returns true.
     *
     * @param clientConsumer Client-side test code that injects bad packets into the TLS handshake.
     * @param expectedException The exception that should be thrown by the server
     */
    private void executeTest(Consumer<Socket> clientConsumer,
                             final Class<?> expectedException) throws Exception {
        SSLContext serverContext = createServerSSLContext();
        SSLServerSocketFactory factory = serverContext.getServerSocketFactory();

        try(ExecutorService threadPool = Executors.newFixedThreadPool(1);
            SSLServerSocket serverSocket = (SSLServerSocket) factory.createServerSocket()) {
            serverSocket.bind(null);
            int port = serverSocket.getLocalPort();
            InetAddress address = serverSocket.getInetAddress();

            Future<Boolean> serverThread = threadPool.submit(() -> {
                try (SSLSocket socket = (SSLSocket) serverSocket.accept()) {
                    log("Server reading data from client.");
                    socket.getInputStream().read();
                    log("The expected exception was not thrown.");
                    return false;

                } catch (Exception exc) {
                    if (expectedException.isAssignableFrom(exc.getClass())) {
                        log("Server thread received expected exception: " + expectedException.getName());
                        return true;
                    } else {
                        log("Server thread threw an unexpected exception: " + exc);
                        throw exc;
                    }
                }
            });

            try(Socket socket = new Socket(address, port)) {
                clientConsumer.accept(socket);
                log("waiting for server to exit.");

                // wait for the server to exit, which should be quick if the test passes.
                if (!serverThread.get(SERVER_WAIT_SEC, TimeUnit.SECONDS)) {
                    throw new RuntimeException(
                            "The server side of the connection did not throw the expected exception");
                }
            }
        }
    }

    /**
     * Performs the client side of the TLS handshake, sending and receiving
     * packets over the given socket.
     * @param socket Connected socket to the server side.
     * @throws IOException
     */
    private void testEmptyAlertDuringHandshake(Socket socket) {
        log("**** Testing empty alert during handshake");

        try {
            SSLEngine engine = createClientSSLContext().createSSLEngine();
            engine.setUseClientMode(true);
            SSLSession session = engine.getSession();

            int appBufferMax = session.getApplicationBufferSize();
            int netBufferMax = session.getPacketBufferSize();

            ByteBuffer clientIn = ByteBuffer.allocate(appBufferMax + 50);
            ByteBuffer clientToServer = ByteBuffer.allocate(appBufferMax + 50);
            ByteBuffer clientOut = ByteBuffer.wrap("Hi Server, I'm Client".getBytes());

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

            OutputStream socketOut = socket.getOutputStream();
            byte [] outbound = new byte[netBufferMax];
            clientToServer.get(outbound, 0, clientToServer.limit());
            socketOut.write(outbound, 0, clientToServer.limit());
            socketOut.flush();

            processServerResponse(engine, clientIn, socket.getInputStream());

            log("Sending invalid alert packet!");
            socketOut.write(new byte[]{ALERT_TYPE, 3, 3, 0, 0});
            socketOut.flush();

        } catch (Exception exc){
            throw new RuntimeException("An error occurred running the test.", exc);
        }
    }

    /**
     * Performs TLS handshake until the client (this method) needs to send the
     * ChangeCipherSpec message. Then we send a packet with a zero-length fragment.
     */
    private void testEmptyChangeCipherSpecMessage(Socket socket) {
        log("**** Testing invalid ChangeCipherSpec message");

        try {
            socket.setSoTimeout(500);
            SSLEngine engine = createClientSSLContext().createSSLEngine();
            engine.setUseClientMode(true);
            SSLSession session = engine.getSession();
            int appBufferMax = session.getApplicationBufferSize();

            ByteBuffer clientIn = ByteBuffer.allocate(appBufferMax + 50);
            ByteBuffer clientToServer = ByteBuffer.allocate(appBufferMax + 50);

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

            OutputStream outputStream = socket.getOutputStream();

            boolean foundCipherSpecMsg = false;

            byte[] outbound = new byte[8192];
            do {
                wrap(engine, clientOut, clientToServer);
                runDelegatedTasks(engine);
                clientToServer.flip();

                if(clientToServer.get(0) == CHANGE_CIPHERSPEC_TYPE) {
                    foundCipherSpecMsg = true;
                    break;
                }
                clientToServer.get(outbound, 0, clientToServer.limit());
                debug("Writing " + clientToServer.limit() + " bytes to the server.");
                outputStream.write(outbound, 0, clientToServer.limit());
                outputStream.flush();

                processServerResponse(engine, clientIn, socket.getInputStream());

                clientToServer.clear();

            } while(engine.getHandshakeStatus() != SSLEngineResult.HandshakeStatus.FINISHED);

            if (!foundCipherSpecMsg) {
                throw new RuntimeException("Didn't intercept the ChangeCipherSpec message.");
            } else {
                log("Sending invalid ChangeCipherSpec message");
                outputStream.write(new byte[]{CHANGE_CIPHERSPEC_TYPE, 3, 3, 0, 0});
                outputStream.flush();
            }

        } catch (Exception exc) {
            throw new RuntimeException("An error occurred running the test.", exc);
        }
    }

    /**
     * Processes TLS handshake messages received from the server.
     */
    private static void processServerResponse(SSLEngine engine, ByteBuffer clientIn,
                                      InputStream inputStream) throws IOException {
        byte [] inbound = new byte[8192];
        ByteBuffer serverToClient = ByteBuffer.allocate(
                engine.getSession().getApplicationBufferSize() + 50);

        while(engine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP) {
            log("reading data from server.");
            int len = inputStream.read(inbound);
            if (len == -1) {
                throw new IOException("Could not read from server.");
            }

            dumpBytes(inbound, len);

            serverToClient.put(inbound, 0, len);
            serverToClient.flip();

            // unwrap packets in a loop because we sometimes get multiple
            // TLS messages in one read() operation.
            do {
                unwrap(engine, serverToClient, clientIn);
                runDelegatedTasks(engine);
                log("Status after running tasks: " + engine.getHandshakeStatus());
            } while (serverToClient.hasRemaining());
            serverToClient.compact();
        }
    }

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

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

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


    @Override
    protected ContextParameters getClientContextParameters() {
        return getContextParameters();
    }

    @Override
    protected ContextParameters getServerContextParameters() {
        return getContextParameters();
    }

    private ContextParameters getContextParameters() {
        return new ContextParameters(protocol, "PKIX", "NewSunX509");
    }

    private static void log(String message) {
        System.out.println(message);
        System.out.flush();
    }

    private static void dumpBytes(byte[] buffer, int length) {
        int totalLength = Math.min(buffer.length, length);
        StringBuffer sb = new StringBuffer();
        int counter = 0;
        for (int idx = 0; idx < totalLength ; ++idx) {
            sb.append(String.format("%02x ", buffer[idx]));
            if (++counter == 16) {
                sb.append("\n");
                counter = 0;
            }
        }
        debug(sb.toString());
    }

    private static void debug(String message) {
        if (DEBUG) {
            log(message);
        }
    }

    private static FileWriter fw;

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


    public static void main(String [] args) throws Exception {
        SSLSocketEmptyFragments tests = new SSLSocketEmptyFragments(TLSv12);

        tests.executeTest(
                tests::testEmptyHandshakeRecord, SSLProtocolException.class);
        tests.executeTest(
                tests::testEmptyAlertNotHandshaking, SSLHandshakeException.class);
        tests.executeTest(
                tests::testEmptyAlertDuringHandshake, SSLHandshakeException.class);
        tests.executeTest(
                tests::testEmptyChangeCipherSpecMessage, SSLProtocolException.class);

        tests = new SSLSocketEmptyFragments(TLSv13);
        tests.executeTest(
                tests::testEmptyHandshakeRecord, SSLProtocolException.class);
        tests.executeTest(
                tests::testEmptyAlertNotHandshaking, SSLHandshakeException.class);
    }
}