File: SSLSocketKeyLimit.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 (318 lines) | stat: -rw-r--r-- 11,619 bytes parent folder | download | duplicates (7)
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
/*
 * Copyright (c) 2018, 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 8164879 8300285
 * @library ../../
 * @library /test/lib
 * @modules java.base/sun.security.util
 * @summary Verify AEAD TLS cipher suite limits set in the jdk.tls.keyLimits
 * property
 * @run main SSLSocketKeyLimit 0 server TLS_AES_256_GCM_SHA384
 *      AES/GCM/NoPadding keyupdate 1000000
 * @run main SSLSocketKeyLimit 0 client TLS_AES_256_GCM_SHA384
 *      AES/GCM/NoPadding keyupdate 1000000
 * @run main SSLSocketKeyLimit 1 client TLS_AES_256_GCM_SHA384
 *      AES/GCM/NoPadding keyupdate 2^22
 * @run main SSLSocketKeyLimit 0 server TLS_CHACHA20_POLY1305_SHA256
 *      AES/GCM/NoPadding keyupdate 1000000, ChaCha20-Poly1305 KeyUpdate 1000000
 * @run main SSLSocketKeyLimit 0 client TLS_CHACHA20_POLY1305_SHA256
 *      AES/GCM/NoPadding keyupdate 1000000, ChaCha20-Poly1305 KeyUpdate 1000000
 * @run main SSLSocketKeyLimit 1 client TLS_CHACHA20_POLY1305_SHA256
 *      AES/GCM/NoPadding keyupdate 2^22, ChaCha20-Poly1305 KeyUpdate 2^22
 */

 /**
  * Verify AES/GCM's limits set in the jdk.tls.keyLimits property
  * start a new handshake sequence to renegotiate the symmetric key with an
  * SSLSocket connection.  This test verifies the handshake method was called
  * via debugging info.  It does not verify the renegotiation was successful
  * as that is very hard.
  */

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Arrays;

import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import jdk.test.lib.Utils;
import jdk.test.lib.hexdump.HexPrinter;

public class SSLSocketKeyLimit {
    SSLSocket socket;
    private InputStream in;
    private OutputStream out;

    static boolean serverReady = false;
    static int serverPort = 0;

    static String pathToStores = "../../../../javax/net/ssl/etc/";
    static String keyStoreFile = "keystore";
    static String passwd = "passphrase";
    static int dataLen = 10240;
    static byte[] data  = new byte[dataLen];
    static boolean serverwrite = true;
    int totalDataLen = 0;
    static boolean done = false;

    SSLSocketKeyLimit() {
    }

    SSLContext initContext() throws Exception {
        SSLContext sc = SSLContext.getInstance("TLSv1.3");
        KeyStore ks = KeyStore.getInstance(
                new File(System.getProperty("javax.net.ssl.keyStore")),
                passwd.toCharArray());
        KeyManagerFactory kmf =
                KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, passwd.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
        return sc;
    }

    /**
     * args should have three values:  server|client, cipher suite, <limit size>
     * Prepending 'p' is for internal use only.
     */
    public static void main(String args[]) throws Exception {
        if (args[0].compareTo("p") != 0) {

            boolean expectedFail = (Integer.parseInt(args[0]) == 1);
            if (expectedFail) {
                System.out.println("Test expected to not find updated msg");
            }
            //Write security property file to overwrite default
            File f = new File("keyusage."+ System.nanoTime());
            PrintWriter p = new PrintWriter(f);
            p.write("jdk.tls.keyLimits=");
            for (int i = 3; i < args.length; i++) {
                p.write(" "+ args[i]);
            }
            p.close();
            System.out.println("Keyusage path = " + f.getAbsolutePath());
            System.setProperty("test.java.opts",
                    "-Dtest.src=" + System.getProperty("test.src") +
                            " -Dtest.jdk=" + System.getProperty("test.jdk") +
                            " -Djavax.net.debug=ssl,handshake" +
                            " -Djava.security.properties=" + f.getName());

            System.out.println("test.java.opts: " +
                    System.getProperty("test.java.opts"));

            ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(
                    Utils.addTestJavaOpts("SSLSocketKeyLimit", "p", args[1],
                            args[2]));

            OutputAnalyzer output = ProcessTools.executeProcess(pb);
            try {
                output.shouldContain(String.format(
                        "\"cipher suite\"        : \"%s", args[2]));
                if (expectedFail) {
                    output.shouldNotContain("KeyUpdate: write key updated");
                    output.shouldNotContain("KeyUpdate: read key updated");
                } else {
                    output.shouldContain("trigger key update");
                    output.shouldContain("KeyUpdate: write key updated");
                    output.shouldContain("KeyUpdate: read key updated");
                }
            } catch (Exception e) {
                throw e;
            } finally {
                System.out.println("-- BEGIN Stdout:");
                System.out.println(output.getStdout());
                System.out.println("-- END Stdout");
                System.out.println("-- BEGIN Stderr:");
                System.out.println(output.getStderr());
                System.out.println("-- END Stderr");
            }
            return;
        }

        if (args.length > 0 && args[1].compareToIgnoreCase("client") == 0) {
            serverwrite = false;
        }

        String keyFilename =
            System.getProperty("test.src", "./") + "/" + pathToStores +
                "/" + keyStoreFile;

        System.setProperty("javax.net.ssl.keyStore", keyFilename);
        System.setProperty("javax.net.ssl.keyStorePassword", passwd);

        Arrays.fill(data, (byte)0x0A);
        Thread ts = new Thread(new Server(args[2]));

        ts.start();
        while (!serverReady) {
            Thread.sleep(100);
        }
        new Client().run();
        ts.join(10000);  // 10sec
        System.exit(0);
    }

    void write(SSLSocket s) throws Exception {
        int i = 0;
        in = s.getInputStream();
        out = s.getOutputStream();
        while (i++ < 150) {
            out.write(data, 0, dataLen);
            System.out.print("W");
            in.readNBytes(1);
            System.out.print("R");
        }
        out.write(0x0D);
        out.flush();

        // Let read side all the data
        while (!done) {
            Thread.sleep(100);
        }
        out.close();
        in.close();
    }


    void read(SSLSocket s) throws Exception {
        byte[] buf = new byte[dataLen];
        int len;
        byte i = 0;
        try {
            System.out.println("Server: connected " +
                    s.getSession().getCipherSuite());
            in = s.getInputStream();
            out = s.getOutputStream();
            while (true) {
                len = in.read(buf, 0, dataLen);
                System.out.print("r");
                out.write(i++);
                System.out.print("w");
                for (byte b: buf) {
                    if (b == 0x0A || b == 0x0D) {
                        continue;
                    }
                    System.out.println("\nData invalid: " +
                            HexPrinter.minimal().toString(buf));
                    break;
                }

                if (len > 0 && buf[len-1] == 0x0D) {
                    System.out.println("got end byte");
                    break;
                }
                totalDataLen += len;
            }
        } catch (Exception e) {
            System.out.println("\n"  + e.getMessage());
            e.printStackTrace();
        } finally {
            // Tell write side that we are done reading
            out.close();
            in.close();
            done = true;
        }
        System.out.println("\nTotalDataLen = " + totalDataLen);
    }

    static class Server extends SSLSocketKeyLimit implements Runnable {
        private SSLServerSocketFactory ssf;
        private SSLServerSocket ss;
        Server(String cipherSuite) {
            super();
            try {
                ssf = initContext().getServerSocketFactory();
                ss = (SSLServerSocket) ssf.createServerSocket(serverPort);
                if (cipherSuite != null && cipherSuite.length() > 0) {
                    ss.setEnabledCipherSuites(new String[] { cipherSuite });
                }
                serverPort = ss.getLocalPort();
            } catch (Exception e) {
                System.out.println("server: " + e.getMessage());
                e.printStackTrace();
            }
        }

        public void run() {
            try {
                serverReady = true;
                System.out.println("Server waiting... port: " + serverPort);
                socket = (SSLSocket) ss.accept();
                if (serverwrite) {
                    write(socket);
                } else {
                    read(socket);
                }

                socket.close();
            } catch (Exception e) {
                System.out.println("server: " + e.getMessage());
                e.printStackTrace();
            }
            System.out.println("Server closed");
        }
    }


    static class Client extends SSLSocketKeyLimit implements Runnable {
        private SSLSocketFactory sf;

        Client() {
            super();
        }

        public void run() {
            try {
                sf = initContext().getSocketFactory();
                System.out.println("Client: connecting... port: " + serverPort);
                socket = (SSLSocket)sf.createSocket("localhost", serverPort);
                System.out.println("Client: connected." + socket.getSession().getCipherSuite());

                // Opposite of what the server does
                if (!serverwrite) {
                    write(socket);
                } else {
                    read(socket);
                }

            } catch (Exception e) {
                System.err.println("client: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
}