File: DHEKeySizing.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 (375 lines) | stat: -rw-r--r-- 14,921 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
367
368
369
370
371
372
373
374
375
/*
 * Copyright (c) 2013, 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.
 */

//
// SunJSSE does not support dynamic system properties, no way to re-use
// system properties in samevm/agentvm mode.
//

/*
 * @test
 * @bug 6956398 8301700
 * @summary make ephemeral DH key match the length of the certificate key
 * @library /javax/net/ssl/templates
 * @run main/othervm -Djdk.tls.client.enableSessionTicketExtension=false
 *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA 1643 267 TLSv1
 * @run main/othervm -Djsse.enableFFDHE=false
 *      -Djdk.tls.client.enableSessionTicketExtension=false
 *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA 1259 75 TLSv1.1
 * @run main/othervm -Djsse.enableFFDHE=false
 *      -Djdk.tls.ephemeralDHKeySize=matched
 *      -Djdk.tls.client.enableSessionTicketExtension=false
 *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA 1259 75 TLSv1.2
 * @run main/othervm -Djsse.enableFFDHE=false
 *      -Djdk.tls.ephemeralDHKeySize=legacy
 *      -Djdk.tls.client.enableSessionTicketExtension=false
 *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA 1259 75 TLSv1
 * @run main/othervm -Djsse.enableFFDHE=false
 *      -Djdk.tls.ephemeralDHKeySize=1024
 *      -Djdk.tls.client.enableSessionTicketExtension=false
 *      DHEKeySizing SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA 1259 75 TLSv1.1
 * @run main/othervm -Djsse.enableFFDHE=false
 *      -Djdk.tls.client.enableSessionTicketExtension=false
 *      DHEKeySizing SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA 233 75 TLSv1.2
 * @run main/othervm -Djsse.enableFFDHE=false
 *      -Djdk.tls.client.enableSessionTicketExtension=false
 *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA 1643 267 TLSv1
 * @run main/othervm -Djsse.enableFFDHE=false
 *      -Djdk.tls.ephemeralDHKeySize=legacy
 *      -Djdk.tls.client.enableSessionTicketExtension=false
 *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA 1323 107 TLSv1.1
 * @run main/othervm -Djsse.enableFFDHE=false
 *      -Djdk.tls.ephemeralDHKeySize=matched
 *      -Djdk.tls.client.enableSessionTicketExtension=false
 *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA 1645 267 TLSv1.2
 * @run main/othervm -Djsse.enableFFDHE=false
 *      -Djdk.tls.ephemeralDHKeySize=1024
 *      -Djdk.tls.client.enableSessionTicketExtension=false
 *      DHEKeySizing TLS_DHE_RSA_WITH_AES_128_CBC_SHA 1387 139 TLSv1
 * @run main/othervm -Djsse.enableFFDHE=false
 *      -Djdk.tls.client.enableSessionTicketExtension=false
 *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5 617 267 TLSv1.1
 * @run main/othervm -Djsse.enableFFDHE=false
 *      -Djdk.tls.client.enableSessionTicketExtension=false
 *      -Djdk.tls.ephemeralDHKeySize=legacy
 *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5 297 107 TLSv1.2
 * @run main/othervm -Djsse.enableFFDHE=false
 *      -Djdk.tls.client.enableSessionTicketExtension=false
 *      -Djdk.tls.ephemeralDHKeySize=matched
 *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5 617 267 TLSv1
 * @run main/othervm -Djsse.enableFFDHE=false
 *      -Djdk.tls.client.enableSessionTicketExtension=false
 *      -Djdk.tls.ephemeralDHKeySize=1024
 *      DHEKeySizing SSL_DH_anon_WITH_RC4_128_MD5 361 139 TLSv1.1
 */

/*
 * This is a simple hack to test key sizes of Diffie-Hellman key exchanging
 * during SSL/TLS handshaking.
 *
 * The record length of DH ServerKeyExchange and ClientKeyExchange.
 * ServerKeyExchange message are wrapped in ServerHello series messages, which
 * contains ServerHello, Certificate and ServerKeyExchange message.
 *
 *    struct {
 *        opaque dh_p<1..2^16-1>;
 *        opaque dh_g<1..2^16-1>;
 *        opaque dh_Ys<1..2^16-1>;
 *    } ServerDHParams;     // Ephemeral DH parameters
 *
 *    struct {
 *        select (PublicValueEncoding) {
 *            case implicit: struct { };
 *            case explicit: opaque dh_Yc<1..2^16-1>;
 *        } dh_public;
 *    } ClientDiffieHellmanPublic;
 *
 * From the above structures, it is clear that if the DH key size increases 128
 * bits (16 bytes), the ServerHello series messages increases 48 bytes
 * (becuase dh_p, dh_g and dh_Ys each increase 16 bytes) and ClientKeyExchange
 * increases 16 bytes (because of the size increasing of dh_Yc).
 *
 * Here is a summary of the record length in the test case.
 *
 *            |  ServerHello Series  |  ClientKeyExchange | ServerHello Anon
 *   512-bit  |          1259 bytes  |           75 bytes |        233 bytes
 *   768-bit  |          1323 bytes  |          107 bytes |        297 bytes
 *  1024-bit  |          1387 bytes  |          139 bytes |        361 bytes
 *  2048-bit  |          1643 bytes  |          267 bytes |        617 bytes
 */

import javax.net.ssl.*;
import javax.net.ssl.SSLEngineResult.*;
import java.nio.*;
import java.security.Security;

public class DHEKeySizing extends SSLEngineTemplate {

    private final static boolean debug = true;

    // key length bias because of the stripping of leading zero bytes of
    // negotiated DH keys.
    //
    // This is an effort to minimize intermittent failures when we cannot
    // estimate what's the exact number of leading zero bytes of
    // negotiated DH keys.
    private final static int KEY_LEN_BIAS = 6;

    private static String protocol;

    private void checkResult(ByteBuffer bbIn, ByteBuffer bbOut,
            SSLEngineResult result,
            Status status, HandshakeStatus hsStatus,
            int consumed, int produced)
            throws Exception {

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

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

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

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

        if ((consumed != -1) && (bbIn.position() != result.bytesConsumed())) {
            throw new Exception("Consumed " + bbIn.position() +
                " != " + consumed);
        }

        if ((produced != -1) && (bbOut.position() != result.bytesProduced())) {
            throw new Exception("produced " + bbOut.position() +
                " != " + produced);
        }
    }

    private void test(String cipherSuite, int lenServerKeyEx,
            int lenClientKeyEx) throws Exception {

        SSLEngineResult result1;        // clientEngine's results from last operation
        SSLEngineResult result2;        // serverEngine's results from last operation

        String[] suites = new String [] {cipherSuite};

        clientEngine.setEnabledCipherSuites(suites);
        serverEngine.setEnabledCipherSuites(suites);

        log("======================================");
        log("===================");
        log("client hello");
        result1 = clientEngine.wrap(clientOut, cTOs);
        checkResult(clientOut, cTOs, result1,
            Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1);
        cTOs.flip();

        result2 = serverEngine.unwrap(cTOs, serverIn);
        checkResult(cTOs, serverIn, result2,
            Status.OK, HandshakeStatus.NEED_TASK, result1.bytesProduced(), 0);
        runDelegatedTasks(serverEngine);
        cTOs.compact();

        log("===================");
        log("ServerHello");
        result2 = serverEngine.wrap(serverOut, sTOc);
        checkResult(serverOut, sTOc, result2,
            Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1);
        sTOc.flip();

        log("Message length of ServerHello series: " + sTOc.remaining());
        if (sTOc.remaining() < (lenServerKeyEx - KEY_LEN_BIAS) ||
                sTOc.remaining() > lenServerKeyEx) {
            throw new Exception(
                "Expected to generate ServerHello series messages of " +
                lenServerKeyEx + " bytes, but not " + sTOc.remaining());
        }

        result1 = clientEngine.unwrap(sTOc, clientIn);
        checkResult(sTOc, clientIn, result1,
            Status.OK, HandshakeStatus.NEED_TASK, result2.bytesProduced(), 0);
        runDelegatedTasks(clientEngine);
        sTOc.compact();

        log("===================");
        log("Key Exchange");
        result1 = clientEngine.wrap(clientOut, cTOs);
        checkResult(clientOut, cTOs, result1,
            Status.OK, HandshakeStatus.NEED_WRAP, 0, -1);
        cTOs.flip();

        log("Message length of ClientKeyExchange: " + cTOs.remaining());
        if (cTOs.remaining() < (lenClientKeyEx - KEY_LEN_BIAS) ||
                cTOs.remaining() > lenClientKeyEx) {
            throw new Exception(
                "Expected to generate ClientKeyExchange message of " +
                lenClientKeyEx + " bytes, but not " + cTOs.remaining());
        }
        result2 = serverEngine.unwrap(cTOs, serverIn);
        checkResult(cTOs, serverIn, result2,
            Status.OK, HandshakeStatus.NEED_TASK, result1.bytesProduced(), 0);
        runDelegatedTasks(serverEngine);
        cTOs.compact();

        log("===================");
        log("Client CCS");
        result1 = clientEngine.wrap(clientOut, cTOs);
        checkResult(clientOut, cTOs, result1,
            Status.OK, HandshakeStatus.NEED_WRAP, 0, -1);
        cTOs.flip();

        result2 = serverEngine.unwrap(cTOs, serverIn);
        checkResult(cTOs, serverIn, result2,
            Status.OK, HandshakeStatus.NEED_UNWRAP,
            result1.bytesProduced(), 0);
        cTOs.compact();

        log("===================");
        log("Client Finished");
        result1 = clientEngine.wrap(clientOut, cTOs);
        checkResult(clientOut, cTOs, result1,
            Status.OK, HandshakeStatus.NEED_UNWRAP, 0, -1);
        cTOs.flip();

        result2 = serverEngine.unwrap(cTOs, serverIn);
        checkResult(cTOs, serverIn, result2,
            Status.OK, HandshakeStatus.NEED_WRAP,
            result1.bytesProduced(), 0);
        cTOs.compact();

        log("===================");
        log("Server CCS");
        result2 = serverEngine.wrap(serverOut, sTOc);
        checkResult(serverOut, sTOc, result2,
            Status.OK, HandshakeStatus.NEED_WRAP, 0, -1);
        sTOc.flip();

        result1 = clientEngine.unwrap(sTOc, clientIn);
        checkResult(sTOc, clientIn, result1,
            Status.OK, HandshakeStatus.NEED_UNWRAP, result2.bytesProduced(), 0);
        sTOc.compact();

        log("===================");
        log("Server Finished");
        result2 = serverEngine.wrap(serverOut, sTOc);
        checkResult(serverOut, sTOc, result2,
            Status.OK, HandshakeStatus.FINISHED, 0, -1);
        sTOc.flip();

        result1 = clientEngine.unwrap(sTOc, clientIn);
        checkResult(sTOc, clientIn, result1,
            Status.OK, HandshakeStatus.FINISHED, result2.bytesProduced(), 0);
        sTOc.compact();

        log("===================");
        log("Check Session/Ciphers");
        String cs = clientEngine.getSession().getCipherSuite();
        if (!cs.equals(suites[0])) {
            throw new Exception("suites not equal: " + cs + "/" + suites[0]);
        }

        cs = serverEngine.getSession().getCipherSuite();
        if (!cs.equals(suites[0])) {
            throw new Exception("suites not equal: " + cs + "/" + suites[0]);
        }

        log("===================");
        log("Done with SSL/TLS handshaking");
    }

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

        if (args.length != 4) {
            System.out.println(
                "Usage: java DHEKeySizing cipher-suite " +
                "size-of-server-hello-record\n" +
                "    size-of-client-key-exchange protocol");
            throw new Exception("Incorrect usage!");
        }

        protocol = args[3];

        (new DHEKeySizing()).test(args[0],
                Integer.parseInt(args[1]),
                Integer.parseInt(args[2]));
        System.out.println("Test Passed.");
    }

    /*
     * **********************************************************
     * Majority of the test case is above, below is just setup stuff
     * **********************************************************
     */

    public DHEKeySizing() throws Exception {
        super();
    }

    @Override
    protected SSLEngine configureServerEngine(SSLEngine engine) {
        engine.setNeedClientAuth(false);
        engine.setUseClientMode(false);
        return engine;
    }

    @Override
    protected SSLContext createServerSSLContext() throws Exception {
        return createSSLContext(null, new Cert[]{Cert.CA_SHA1_RSA_2048},
                getServerContextParameters());
    }

    @Override
    protected SSLContext createClientSSLContext() throws Exception {
        return createSSLContext(new Cert[]{Cert.CA_SHA1_RSA_2048}, null,
                getClientContextParameters());
    }

    @Override
    protected ContextParameters getClientContextParameters() {
        return new ContextParameters(protocol, "PKIX", "NewSunX509");
    }

    @Override
    protected ContextParameters getServerContextParameters() {
        return new ContextParameters(protocol, "PKIX", "NewSunX509");
    }

    private static void log(String str) {
        if (debug) {
            System.out.println(str);
        }
    }
}