File: HRRKeyShares.java

package info (click to toggle)
openjdk-23 23.0.2%2B7-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 815,324 kB
  • sloc: java: 5,632,909; cpp: 1,303,022; xml: 1,237,193; ansic: 419,177; asm: 404,932; objc: 20,978; sh: 15,486; javascript: 11,040; python: 6,802; makefile: 2,331; perl: 357; awk: 351; sed: 172; pascal: 103; exp: 26; jsp: 24; csh: 3
file content (435 lines) | stat: -rw-r--r-- 17,554 bytes parent folder | download | duplicates (11)
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
/*
 * Copyright (c) 2020, 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.
 */

// SunJSSE does not support dynamic system properties, no way to re-use
// system properties in samevm/agentvm mode.  For further debugging output
// set the -Djavax.net.debug=ssl:handshake property on the @run lines.

/*
 * @test
 * @bug 8247630
 * @summary Use two key share entries
 * @library /test/lib
 * @run main/othervm -Djdk.tls.namedGroups=x25519,secp256r1,secp384r1 HRRKeyShares
 */

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.net.ssl.*;
import javax.net.ssl.SSLEngineResult.*;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import jdk.test.lib.Utils;


public class HRRKeyShares {

    // Some TLS constants we'll use for testing
    private static final int TLS_REC_HANDSHAKE = 22;
    private static final int TLS_REC_ALERT = 21;
    private static final int HS_MSG_CLIHELLO = 1;
    private static final int HS_MSG_SERVHELLO = 2;          // Also for HRR
    private static final int HELLO_EXT_SUPP_GROUPS = 10;
    private static final int HELLO_EXT_SUPP_VERS = 43;
    private static final int HELLO_EXT_KEY_SHARE = 51;
    private static final int TLS_LEGACY_VER = 0x0303;       // TLSv1.2
    private static final int TLS_PROT_VER_13 = 0x0304;      // TLSv1.3
    private static final int NG_SECP256R1 = 0x0017;
    private static final int NG_SECP384R1 = 0x0018;
    private static final int NG_X25519 = 0x001D;
    private static final int NG_X448 = 0x001E;
    private static final int NG_GC512A = 0x0026;
    private static final int COMP_NONE = 0;
    private static final int ALERT_TYPE_FATAL = 2;
    private static final int ALERT_DESC_ILLEGAL_PARAM = 47;
    private static final byte[] HRR_RANDOM = Utils.toByteArray(
            "CF21AD74E59A6111BE1D8C021E65B891" +
            "C2A211167ABB8C5E079E09E2C8A8339C");

    static class ClientHello {
        // TLS Record header fields
        final int recType;
        final int recVers;
        final int recLength;

        // Handshake header fields
        final int hsMsgType;
        final int hsMsgLength;

        // ClientHello fields
        final int version;
        final byte[] random;
        final byte[] sessId;
        final List<Integer> cipherSuites = new ArrayList<>();
        final List<Integer> compressionList = new ArrayList<>();
        final Map<Integer,byte[]> extensionMap = new LinkedHashMap<>();

        // These are fields built from specific extension data fields we
        // are interested in for our tests
        final List<Integer> suppGroups = new ArrayList<>();
        final Map<Integer,byte[]> keyShares = new LinkedHashMap<>();
        final List<Integer> suppVersions = new ArrayList<>();

        ClientHello(ByteBuffer data) {
            Objects.requireNonNull(data);
            data.mark();

            // Process the TLS record header
            recType = Byte.toUnsignedInt(data.get());
            recVers = Short.toUnsignedInt(data.getShort());
            recLength = Short.toUnsignedInt(data.getShort());
            if (recType != TLS_REC_HANDSHAKE) {
                throw new RuntimeException("Not a Handshake TLS record. " +
                        "Type = " + recType);
            }

            // Process the Handshake message header
            int recHdr = data.getInt();
            hsMsgType = recHdr >>> 24;
            hsMsgLength = recHdr & 0x00FFFFFF;
            if (hsMsgType != HS_MSG_CLIHELLO) {
                throw new RuntimeException("Not a ClientHello message. " +
                        "Type = " + hsMsgType);
            } else if (hsMsgLength > data.remaining()) {
                throw new RuntimeException("Incomplete record in buffer: " +
                        "Record length = " + hsMsgLength + ", Remaining = " +
                        data.remaining());
            }

            version = Short.toUnsignedInt(data.getShort());
            random = new byte[32];
            data.get(random);
            sessId = new byte[Byte.toUnsignedInt(data.get())];
            data.get(sessId);

            int suiteLen = Short.toUnsignedInt(data.getShort());
            while (suiteLen > 0) {
                cipherSuites.add(Short.toUnsignedInt(data.getShort()));
                suiteLen -= 2;
            }

            int compLen = Byte.toUnsignedInt(data.get());
            while (compLen > 0) {
                compressionList.add(Byte.toUnsignedInt(data.get()));
                compLen--;
            }

            // Extension processing time!
            int extListLen = Short.toUnsignedInt(data.getShort());
            while (extListLen > 0) {
                int extType = Short.toUnsignedInt(data.getShort());
                int extLen = Short.toUnsignedInt(data.getShort());
                byte[] extData = new byte[extLen];
                data.get(extData);
                extensionMap.put(extType, extData);
                switch (extType) {
                    case HELLO_EXT_SUPP_GROUPS:
                        ByteBuffer sgBuf = ByteBuffer.wrap(extData);
                        int supGrpLen = Short.toUnsignedInt(sgBuf.getShort());
                        for (int remain = supGrpLen; remain > 0; remain -= 2) {
                            suppGroups.add(Short.toUnsignedInt(
                                    sgBuf.getShort()));
                        }
                        break;
                    case HELLO_EXT_SUPP_VERS:
                        ByteBuffer svBuf = ByteBuffer.wrap(extData);
                        int supVerLen = Byte.toUnsignedInt(svBuf.get());
                        for (int remain = supVerLen; remain > 0; remain -= 2) {
                            suppVersions.add(Short.toUnsignedInt(
                                    svBuf.getShort()));
                        }
                        break;
                    case HELLO_EXT_KEY_SHARE:
                        ByteBuffer ksBuf = ByteBuffer.wrap(extData);
                        int ksListLen = Short.toUnsignedInt(ksBuf.getShort());
                        while (ksListLen > 0) {
                            int namedGroup = Short.toUnsignedInt(
                                    ksBuf.getShort());
                            int ksLen = Short.toUnsignedInt(ksBuf.getShort());
                            byte[] ksData = new byte[ksLen];
                            ksBuf.get(ksData);
                            keyShares.put(namedGroup, ksData);
                            ksListLen -= (4 + ksLen);
                        }
                        break;
                }
                extListLen -= (4 + extLen);
            }
        }
    }

    static class Alert {
        final int recType;
        final int recVers;
        final int recLength;
        final int alertType;
        final int alertDesc;

        Alert(ByteBuffer data) {
            Objects.requireNonNull(data);
            data.mark();

            // Process the TLS record header
            recType = Byte.toUnsignedInt(data.get());
            recVers = Short.toUnsignedInt(data.getShort());
            recLength = Short.toUnsignedInt(data.getShort());
            if (recType != TLS_REC_ALERT) {
                throw new RuntimeException("Not a Handshake TLS record. " +
                        "Type = " + recType);
            }

            alertType = Byte.toUnsignedInt(data.get());
            alertDesc = Byte.toUnsignedInt(data.get());
        }
    }

    public static void main(String args[]) throws Exception {
        System.out.println("Test 1: Good HRR exchange using secp384r1");
        hrrKeyShareTest(NG_SECP384R1, true);
        System.out.println();

        System.out.println("Test 2: Bad HRR exchange using secp256r1");
        hrrKeyShareTest(NG_SECP256R1, false);
        System.out.println();

        System.out.println("Test 3: Bad HRR using unknown GC512A");
        hrrKeyShareTest(NG_GC512A, false);
        System.out.println();

        System.out.println("Test 4: Bad HRR using known / unasserted x448");
        hrrKeyShareTest(NG_X448, false);
        System.out.println();
    }

    private static void logResult(String str, SSLEngineResult result) {
        HandshakeStatus hsStatus = result.getHandshakeStatus();
        System.out.println(str +
            result.getStatus() + "/" + hsStatus + ", " +
            result.bytesConsumed() + "/" + result.bytesProduced() +
            " bytes");
        if (hsStatus == HandshakeStatus.FINISHED) {
            System.out.println("\t...ready for application data");
        }
    }

    /*
     * If the result indicates that we have outstanding tasks to do,
     * go ahead and run them in this thread.
     */
    private static void runDelegatedTasks(SSLEngine engine) throws Exception {
        if (engine.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
            Runnable runnable;
            while ((runnable = engine.getDelegatedTask()) != null) {
                System.out.println("    running delegated task...");
                runnable.run();
            }
            HandshakeStatus hsStatus = engine.getHandshakeStatus();
            if (hsStatus == HandshakeStatus.NEED_TASK) {
                throw new Exception(
                    "handshake shouldn't need additional tasks");
            }
        }
    }

    /**
     * Dump a ByteBuffer as a hexdump to stdout.  The dumping routine will
     * start at the current position of the buffer and run to its limit.
     * After completing the dump, the position will be returned to its
     * starting point.
     *
     * @param data the ByteBuffer to dump to stdout.
     *
     * @return the hexdump of the byte array.
     */
    private static String dumpHexBytes(ByteBuffer data) {
        StringBuilder sb = new StringBuilder();
        if (data != null) {
            int i = 0;
            data.mark();
            while (data.hasRemaining()) {
                if (i % 16 == 0 && i != 0) {
                    sb.append("\n");
                }
                sb.append(String.format("%02X ", data.get()));
                i++;
            }
            data.reset();
        }

        return sb.toString();
    }

    private static void hrrKeyShareTest(int hrrNamedGroup, boolean expectedPass)
            throws Exception {
        SSLContext sslCtx = SSLContext.getDefault();
        SSLEngine engine = sslCtx.createSSLEngine();
        engine.setUseClientMode(true);
        SSLSession session = engine.getSession();
        ByteBuffer clientOut =
                ByteBuffer.wrap("I'm a Client".getBytes());
        ByteBuffer cTOs = ByteBuffer.allocateDirect(
                session.getPacketBufferSize());

        // Create and check the ClientHello message
        SSLEngineResult clientResult = engine.wrap(clientOut, cTOs);
        logResult("client wrap: ", clientResult);
        if (clientResult.getStatus() != SSLEngineResult.Status.OK) {
            throw new RuntimeException("Client wrap got status: " +
                    clientResult.getStatus());
        }

        cTOs.flip();
        System.out.println("----- ORIGINAL CLIENT HELLO -----\n" +
                dumpHexBytes(cTOs));
        ClientHello initialCh = new ClientHello(cTOs);

        if (!initialCh.suppVersions.contains(TLS_PROT_VER_13)) {
            throw new RuntimeException(
                    "Missing TLSv1.3 protocol in supported_versions");
        } else if (!initialCh.keyShares.containsKey(NG_X25519) ||
                !initialCh.keyShares.containsKey(NG_SECP256R1)) {
            throw new RuntimeException(
                    "Missing one or more expected KeyShares");
        }

        // Craft the HRR message with the passed-in named group as the
        // key share named group to request.
        ByteBuffer sTOc = buildHRRMessage(initialCh, hrrNamedGroup);
        System.out.println("----- SERVER HELLO RETRY REQUEST -----\n" +
                dumpHexBytes(sTOc));

        // Unwrap the HRR and process it
        clientResult = engine.unwrap(sTOc, clientOut);
        logResult("client unwrap: ", clientResult);
        if (clientResult.getStatus() != SSLEngineResult.Status.OK) {
            throw new RuntimeException("Client wrap got status: " +
                    clientResult.getStatus());
        }
        runDelegatedTasks(engine);

        try {
            // Now we're expecting to reissue the ClientHello, this time
            // with a secp384r1 share.
            cTOs.compact();
            clientResult = engine.wrap(clientOut, cTOs);
            logResult("client wrap: ", clientResult);
            if (clientResult.getStatus() != SSLEngineResult.Status.OK) {
                throw new RuntimeException("Client wrap got status: " +
                        clientResult.getStatus());
            }
        } catch (RuntimeException | SSLException ssle) {
            if (expectedPass) {
                System.out.println("Caught unexpected exception");
                throw ssle;
            } else {
                System.out.println("Caught expected exception: " + ssle);

                // Try issuing another wrap call and see if we can get
                // the Alert out.
                clientResult = engine.wrap(clientOut, cTOs);
                logResult("client wrap: ", clientResult);
                if (clientResult.getStatus() != SSLEngineResult.Status.CLOSED) {
                    throw new RuntimeException("Client wrap got status: " +
                            clientResult.getStatus());
                }

                cTOs.flip();
                System.out.println("----- ALERT -----\n" + dumpHexBytes(cTOs));
                Alert alert = new Alert(cTOs);
                if (alert.alertType != ALERT_TYPE_FATAL ||
                        alert.alertDesc != ALERT_DESC_ILLEGAL_PARAM) {
                    throw new RuntimeException("Unexpected alert.  " +
                            "received " + alert.alertType + " / " +
                            alert.alertDesc);
                }
                return;
            }
        }

        cTOs.flip();
        System.out.println("----- REISSUED CLIENT HELLO -----\n" +
                dumpHexBytes(cTOs));
        ClientHello reissuedCh = new ClientHello(cTOs);

        if (!reissuedCh.keyShares.containsKey(hrrNamedGroup)) {
            throw new RuntimeException("Missing secp384r1 key share");
        }
    }

    private static ByteBuffer buildHRRMessage(ClientHello cliHello,
            int namedGroup) throws IOException {
        // Create a ByteBuffer that will be large enough to handle
        // the HelloRetryRequest
        ByteBuffer hrrBuf = ByteBuffer.allocate(2048);  // More than enough!

        // Advance past the TLS record and handshake message headers.  We will
        // go back later and scribble in the proper lengths.  The record header
        // is 5 bytes long, the handshake header is 4.
        hrrBuf.position(9);
        hrrBuf.putShort((short)TLS_LEGACY_VER);
        hrrBuf.put(HRR_RANDOM);
        hrrBuf.put((byte)cliHello.sessId.length);
        hrrBuf.put(cliHello.sessId);
        hrrBuf.putShort(cliHello.cipherSuites.get(0).shortValue());
        hrrBuf.put((byte)COMP_NONE);

        // Use a separate stream for creating the extension section
        ByteArrayOutputStream extBaos = new ByteArrayOutputStream();
        DataOutputStream extStream = new DataOutputStream(extBaos);

        // Supported version
        extStream.writeShort(HELLO_EXT_SUPP_VERS);
        extStream.writeShort(2);
        extStream.writeShort(TLS_PROT_VER_13);

        // Key share
        extStream.writeShort(HELLO_EXT_KEY_SHARE);
        extStream.writeShort(2);
        extStream.writeShort(namedGroup);

        // Now add in the extensions into the main message
        hrrBuf.putShort((short)extStream.size());
        hrrBuf.put(extBaos.toByteArray());

        // At this point we can go back and write in the TLS record and
        // handshake message headers.
        hrrBuf.flip();

        // Write in the TLS record header
        hrrBuf.put((byte)TLS_REC_HANDSHAKE);
        hrrBuf.putShort((short)TLS_LEGACY_VER);
        hrrBuf.putShort((short)(hrrBuf.limit() - 5));

        // Write the Handshake message header
        hrrBuf.putInt((HS_MSG_SERVHELLO << 24) |
                ((hrrBuf.limit() - 9) & 0x00FFFFFF));

        hrrBuf.rewind();
        return hrrBuf;
    }
}