SessionTimeOutTests.java revision 9372:171791e63397
1/*
2 * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24// SunJSSE does not support dynamic system properties, no way to re-use
25// system properties in samevm/agentvm mode.
26
27/*
28 * @test
29 * @bug   4366807
30 * @summary Need new APIs to get/set session timeout and session cache size.
31 * @run main/othervm SessionTimeOutTests
32 */
33
34import java.io.*;
35import java.net.*;
36import javax.net.ssl.*;
37import java.util.*;
38import java.security.*;
39
40/**
41 * Session reuse time-out tests cover the cases below:
42 * 1. general test, i.e timeout is set to x and session invalidates when
43 * its lifetime exceeds x.
44 * 2. Effect of changing the timeout limit.
45 * The test suite does not cover the default timeout(24 hours) usage. This
46 * case has been tested independetly.
47 *
48 * Invairant for passing this test is, at any given time,
49 * lifetime of a session < current_session_timeout, such that
50 * current_session_timeout > 0, for all sessions cached by the session
51 * context.
52 */
53
54public class SessionTimeOutTests {
55
56    /*
57     * =============================================================
58     * Set the various variables needed for the tests, then
59     * specify what tests to run on each side.
60     */
61
62    /*
63     * Should we run the client or server in a separate thread?
64     * Both sides can throw exceptions, but do you have a preference
65     * as to which side should be the main thread.
66     */
67    static boolean separateServerThread = true;
68
69    /*
70     * Where do we find the keystores?
71     */
72    static String pathToStores = "../etc";
73    static String keyStoreFile = "keystore";
74    static String trustStoreFile = "truststore";
75    static String passwd = "passphrase";
76
77    private static int PORTS = 3;
78
79    /*
80     * Is the server ready to serve?
81     */
82    volatile static int serverReady = PORTS;
83
84    /*
85     * Turn on SSL debugging?
86     */
87    static boolean debug = false;
88
89    /*
90     * If the client or server is doing some kind of object creation
91     * that the other side depends on, and that thread prematurely
92     * exits, you may experience a hang.  The test harness will
93     * terminate all hung threads after its timeout has expired,
94     * currently 3 minutes by default, but you might try to be
95     * smart about it....
96     */
97
98    /*
99     * Define the server side of the test.
100     *
101     * If the server prematurely exits, serverReady will be set to true
102     * to avoid infinite hangs.
103     */
104
105    /*
106     * A limit on the number of connections at any given time
107     */
108    static int MAX_ACTIVE_CONNECTIONS = 3;
109
110    void doServerSide(int serverPort, int serverConns) throws Exception {
111
112        SSLServerSocket sslServerSocket =
113            (SSLServerSocket) sslssf.createServerSocket(serverPort);
114        serverPorts[createdPorts++] = sslServerSocket.getLocalPort();
115
116        /*
117         * Signal Client, we're ready for his connect.
118         */
119        serverReady--;
120        int read = 0;
121        int nConnections = 0;
122        SSLSession sessions [] = new SSLSession [serverConns];
123
124        while (nConnections < serverConns) {
125            SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
126            InputStream sslIS = sslSocket.getInputStream();
127            OutputStream sslOS = sslSocket.getOutputStream();
128            read = sslIS.read();
129            sessions[nConnections] = sslSocket.getSession();
130            sslOS.write(85);
131            sslOS.flush();
132            sslSocket.close();
133            nConnections++;
134        }
135    }
136
137    /*
138     * Define the client side of the test.
139     *
140     * If the server prematurely exits, serverReady will be set to true
141     * to avoid infinite hangs.
142     */
143    void doClientSide() throws Exception {
144
145        /*
146         * Wait for server to get started.
147         */
148        while (serverReady > 0) {
149            Thread.sleep(50);
150        }
151
152        int nConnections = 0;
153        SSLSocket sslSockets[] = new SSLSocket [MAX_ACTIVE_CONNECTIONS];
154        Vector sessions = new Vector();
155        SSLSessionContext sessCtx = sslctx.getClientSessionContext();
156
157        sessCtx.setSessionTimeout(10); // in secs
158        int timeout = sessCtx.getSessionTimeout();
159        while (nConnections < MAX_ACTIVE_CONNECTIONS) {
160            // divide the connections among the available server ports
161            sslSockets[nConnections] = (SSLSocket) sslsf.
162                        createSocket("localhost",
163                        serverPorts [nConnections % (serverPorts.length)]);
164            InputStream sslIS = sslSockets[nConnections].getInputStream();
165            OutputStream sslOS = sslSockets[nConnections].getOutputStream();
166            sslOS.write(237);
167            sslOS.flush();
168            int read = sslIS.read();
169            SSLSession sess = sslSockets[nConnections].getSession();
170            if (!sessions.contains(sess))
171                sessions.add(sess);
172            nConnections++;
173        }
174        System.out.println();
175        System.out.println("Current timeout is set to: " + timeout);
176        System.out.println("Testing SSLSessionContext.getSession()......");
177        System.out.println("========================================"
178                                + "=======================");
179        System.out.println("Session                                 "
180                                + "Session-     Session");
181        System.out.println("                                        "
182                                + "lifetime     timedout?");
183        System.out.println("========================================"
184                                + "=======================");
185
186        for (int i = 0; i < sessions.size(); i++) {
187            SSLSession session = (SSLSession) sessions.elementAt(i);
188            long currentTime  = System.currentTimeMillis();
189            long creationTime = session.getCreationTime();
190            long lifetime = (currentTime - creationTime) / 1000;
191
192            System.out.print(session + "      " + lifetime + "            ");
193            if (sessCtx.getSession(session.getId()) == null) {
194                if (lifetime < timeout)
195                    // sessions can be garbage collected before the timeout
196                    // limit is reached
197                    System.out.println("Invalidated before timeout");
198                else
199                    System.out.println("YES");
200            } else {
201                System.out.println("NO");
202                if ((timeout != 0) && (lifetime > timeout)) {
203                    throw new Exception("Session timeout test failed for the"
204                        + " obove session");
205                }
206            }
207            // change the timeout
208            if (i == ((sessions.size()) / 2)) {
209                System.out.println();
210                sessCtx.setSessionTimeout(2); // in secs
211                timeout = sessCtx.getSessionTimeout();
212                System.out.println("timeout is changed to: " + timeout);
213                System.out.println();
214           }
215        }
216
217        // check the ids returned by the enumerator
218        Enumeration e = sessCtx.getIds();
219        System.out.println("----------------------------------------"
220                                + "-----------------------");
221        System.out.println("Testing SSLSessionContext.getId()......");
222        System.out.println();
223
224        SSLSession nextSess = null;
225        SSLSession sess;
226        for (int i = 0; i < sessions.size(); i++) {
227            sess = (SSLSession)sessions.elementAt(i);
228            String isTimedout = "YES";
229            long currentTime  = System.currentTimeMillis();
230            long creationTime  = sess.getCreationTime();
231            long lifetime = (currentTime - creationTime) / 1000;
232
233            if (nextSess != null) {
234                if (isEqualSessionId(nextSess.getId(), sess.getId())) {
235                    isTimedout = "NO";
236                    nextSess = null;
237                }
238            } else if (e.hasMoreElements()) {
239                nextSess = sessCtx.getSession((byte[]) e.nextElement());
240                if ((nextSess != null) && isEqualSessionId(nextSess.getId(),
241                                        sess.getId())) {
242                    nextSess = null;
243                    isTimedout = "NO";
244                }
245            }
246
247            /*
248             * A session not invalidated even after it's timeout?
249             */
250            if ((timeout != 0) && (lifetime > timeout) &&
251                        (isTimedout.equals("NO"))) {
252                throw new Exception("Session timeout test failed for session: "
253                                + sess + " lifetime: " + lifetime);
254            }
255            System.out.print(sess + "      " + lifetime);
256            if (((timeout == 0) || (lifetime < timeout)) &&
257                                  (isTimedout == "YES")) {
258                isTimedout = "Invalidated before timeout";
259            }
260
261            System.out.println("            " + isTimedout);
262        }
263        for (int i = 0; i < nConnections; i++) {
264            sslSockets[i].close();
265        }
266        System.out.println("----------------------------------------"
267                                 + "-----------------------");
268        System.out.println("Session timeout test passed");
269    }
270
271    boolean isEqualSessionId(byte[] id1, byte[] id2) {
272        if (id1.length != id2.length)
273           return false;
274        else {
275            for (int i = 0; i < id1.length; i++) {
276                if (id1[i] != id2[i]) {
277                   return false;
278                }
279            }
280            return true;
281        }
282    }
283
284
285    /*
286     * =============================================================
287     * The remainder is just support stuff
288     */
289
290    volatile int serverPorts[] = new int[PORTS];
291    volatile int createdPorts = 0;
292    static SSLServerSocketFactory sslssf;
293    static SSLSocketFactory sslsf;
294    static SSLContext sslctx;
295
296    volatile Exception serverException = null;
297    volatile Exception clientException = null;
298
299    public static void main(String[] args) throws Exception {
300        String keyFilename =
301            System.getProperty("test.src", "./") + "/" + pathToStores +
302                "/" + keyStoreFile;
303        String trustFilename =
304            System.getProperty("test.src", "./") + "/" + pathToStores +
305                "/" + trustStoreFile;
306
307        System.setProperty("javax.net.ssl.keyStore", keyFilename);
308        System.setProperty("javax.net.ssl.keyStorePassword", passwd);
309        System.setProperty("javax.net.ssl.trustStore", trustFilename);
310        System.setProperty("javax.net.ssl.trustStorePassword", passwd);
311
312        sslctx = SSLContext.getInstance("TLS");
313        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
314        KeyStore ks = KeyStore.getInstance("JKS");
315        ks.load(new FileInputStream(keyFilename), passwd.toCharArray());
316        kmf.init(ks, passwd.toCharArray());
317        sslctx.init(kmf.getKeyManagers(), null, null);
318        sslssf = (SSLServerSocketFactory) sslctx.getServerSocketFactory();
319        sslsf = (SSLSocketFactory) sslctx.getSocketFactory();
320        if (debug)
321            System.setProperty("javax.net.debug", "all");
322
323        /*
324         * Start the tests.
325         */
326        new SessionTimeOutTests();
327    }
328
329    Thread clientThread = null;
330    Thread serverThread = null;
331
332    /*
333     * Primary constructor, used to drive remainder of the test.
334     *
335     * Fork off the other side, then do your work.
336     */
337    SessionTimeOutTests() throws Exception {
338
339        /*
340         * create the SSLServerSocket and SSLSocket factories
341         */
342
343        /*
344         * Divide the max connections among the available server ports.
345         * The use of more than one server port ensures creation of more
346         * than one session.
347         */
348        int serverConns = MAX_ACTIVE_CONNECTIONS / (serverPorts.length);
349        int remainingConns = MAX_ACTIVE_CONNECTIONS % (serverPorts.length);
350
351        Exception startException = null;
352        try {
353            if (separateServerThread) {
354                for (int i = 0; i < serverPorts.length; i++) {
355                    // distribute remaining connections among the
356                    // vailable ports
357                    if (i < remainingConns)
358                        startServer(serverPorts[i], (serverConns + 1), true);
359                    else
360                        startServer(serverPorts[i], serverConns, true);
361                }
362                startClient(false);
363            } else {
364                startClient(true);
365                for (int i = 0; i < serverPorts.length; i++) {
366                    if (i < remainingConns)
367                        startServer(serverPorts[i], (serverConns + 1), false);
368                    else
369                        startServer(serverPorts[i], serverConns, false);
370                }
371            }
372        } catch (Exception e) {
373            startException = e;
374        }
375
376        /*
377         * Wait for other side to close down.
378         */
379        if (separateServerThread) {
380            if (serverThread != null) {
381                serverThread.join();
382            }
383        } else {
384            if (clientThread != null) {
385                clientThread.join();
386            }
387        }
388
389        /*
390         * When we get here, the test is pretty much over.
391         * Which side threw the error?
392         */
393        Exception local;
394        Exception remote;
395
396        if (separateServerThread) {
397            remote = serverException;
398            local = clientException;
399        } else {
400            remote = clientException;
401            local = serverException;
402        }
403
404        Exception exception = null;
405
406        /*
407         * Check various exception conditions.
408         */
409        if ((local != null) && (remote != null)) {
410            // If both failed, return the curthread's exception.
411            local.initCause(remote);
412            exception = local;
413        } else if (local != null) {
414            exception = local;
415        } else if (remote != null) {
416            exception = remote;
417        } else if (startException != null) {
418            exception = startException;
419        }
420
421        /*
422         * If there was an exception *AND* a startException,
423         * output it.
424         */
425        if (exception != null) {
426            if (exception != startException && startException != null) {
427                exception.addSuppressed(startException);
428            }
429            throw exception;
430        }
431
432        // Fall-through: no exception to throw!
433    }
434
435    void startServer(final int port, final int nConns,
436                        boolean newThread) throws Exception {
437        if (newThread) {
438            serverThread = new Thread() {
439                public void run() {
440                    try {
441                        doServerSide(port, nConns);
442                    } catch (Exception e) {
443                        /*
444                         * Our server thread just died.
445                         *
446                         * Release the client, if not active already...
447                         */
448                        System.err.println("Server died...");
449                        e.printStackTrace();
450                        serverReady = 0;
451                        serverException = e;
452                    }
453                }
454            };
455            serverThread.start();
456        } else {
457            try {
458                doServerSide(port, nConns);
459            } catch (Exception e) {
460                serverException = e;
461            } finally {
462                serverReady = 0;
463            }
464        }
465    }
466
467    void startClient(boolean newThread)
468                 throws Exception {
469        if (newThread) {
470            clientThread = new Thread() {
471                public void run() {
472                    try {
473                        doClientSide();
474                    } catch (Exception e) {
475                        /*
476                         * Our client thread just died.
477                         */
478                        System.err.println("Client died...");
479                        clientException = e;
480                    }
481                }
482            };
483            clientThread.start();
484        } else {
485            try {
486                doClientSide();
487            } catch (Exception e) {
488                clientException = e;
489            }
490        }
491    }
492}
493