View Javadoc

1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License.
18   *
19   */package org.apache.mina.filter.ssl;
20  
21  import java.io.BufferedReader;
22  import java.io.IOException;
23  import java.io.InputStreamReader;
24  import java.net.InetAddress;
25  import java.net.InetSocketAddress;
26  import java.net.Socket;
27  import java.security.GeneralSecurityException;
28  import java.security.KeyStore;
29  import java.security.Security;
30  
31  import javax.net.ssl.KeyManagerFactory;
32  import javax.net.ssl.SSLContext;
33  import javax.net.ssl.SSLSocketFactory;
34  import javax.net.ssl.TrustManagerFactory;
35  
36  import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
37  import org.apache.mina.core.service.IoHandlerAdapter;
38  import org.apache.mina.core.session.IoSession;
39  import org.apache.mina.filter.codec.ProtocolCodecFilter;
40  import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
41  import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
42  import org.apache.mina.util.AvailablePortFinder;
43  import org.junit.Test;
44  
45  /**
46   * Test a SSL session where the connection is established and closed twice. It should be
47   * processed correctly (Test for DIRMINA-650)
48   *
49   * @author <a href="http://mina.apache.org">Apache MINA Project</a>
50   */
51  public class SslTest {
52      /** A static port used for his test, chosen to avoid collisions */
53      private static final int port = AvailablePortFinder.getNextAvailable(5555);
54  
55      private static Exception clientError = null;
56      private static InetAddress address;
57      private static SSLSocketFactory factory;
58  
59      /** A JVM independant KEY_MANAGER_FACTORY algorithm */
60      private static final String KEY_MANAGER_FACTORY_ALGORITHM;
61  
62      static {
63          String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
64          if (algorithm == null) {
65              algorithm = KeyManagerFactory.getDefaultAlgorithm();
66          }
67  
68          KEY_MANAGER_FACTORY_ALGORITHM = algorithm;
69      }
70  
71      private static class TestHandler extends IoHandlerAdapter {
72          public void messageReceived(IoSession session, Object message) throws Exception {
73              String line = (String) message;
74  
75              if (line.startsWith("hello")) {
76                  System.out.println("Server got: 'hello', waiting for 'send'");
77                  Thread.sleep(1500);
78              } else if (line.startsWith("send")) {
79                  System.out.println("Server got: 'send', sending 'data'");
80                  session.write("data");
81              }
82          }
83      }
84  
85      
86      /**
87       * Starts a Server with the SSL Filter and a simple text line 
88       * protocol codec filter
89       */
90      private static void startServer() throws Exception {
91          NioSocketAcceptor acceptor = new NioSocketAcceptor();
92  
93          acceptor.setReuseAddress(true);
94          DefaultIoFilterChainBuilder filters = acceptor.getFilterChain();
95  
96          // Inject the SSL filter
97          SslFilter sslFilter = new SslFilter(createSSLContext());
98          filters.addLast("sslFilter", sslFilter);
99          
100         // Inject the TestLine codec filter
101         filters.addLast("text", new ProtocolCodecFilter(new TextLineCodecFactory()));
102         
103         acceptor.setHandler(new TestHandler());
104         acceptor.bind(new InetSocketAddress(port));
105     }
106 
107     /**
108      * Starts a client which will connect twice using SSL
109      */
110     private static void startClient() throws Exception {
111         address = InetAddress.getByName("localhost");
112 
113         SSLContext context = createSSLContext();
114         factory = context.getSocketFactory();
115 
116         connectAndSend();
117         
118         // This one will throw a SocketTimeoutException if DIRMINA-650 is not fixed
119         connectAndSend();
120     }
121 
122     private static void connectAndSend() throws Exception {
123         Socket parent = new Socket(address, port);
124         Socket socket = factory.createSocket(parent, address.getCanonicalHostName(), port, false);
125 
126         System.out.println("Client sending: hello");
127         socket.getOutputStream().write("hello                      \n".getBytes());
128         socket.getOutputStream().flush();
129         socket.setSoTimeout(10000);
130 
131         System.out.println("Client sending: send");
132         socket.getOutputStream().write("send\n".getBytes());
133         socket.getOutputStream().flush();
134 
135         BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
136         String line = in.readLine();
137         System.out.println("Client got: " + line);
138         socket.close();
139 
140     }
141 
142     private static SSLContext createSSLContext() throws IOException, GeneralSecurityException {
143         char[] passphrase = "password".toCharArray();
144 
145         SSLContext ctx = SSLContext.getInstance("TLS");
146         KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEY_MANAGER_FACTORY_ALGORITHM);
147         TrustManagerFactory tmf = TrustManagerFactory.getInstance(KEY_MANAGER_FACTORY_ALGORITHM);
148 
149         KeyStore ks = KeyStore.getInstance("JKS");
150         KeyStore ts = KeyStore.getInstance("JKS");
151 
152         ks.load(SslTest.class.getResourceAsStream("keystore.sslTest"), passphrase);
153         ts.load(SslTest.class.getResourceAsStream("truststore.sslTest"), passphrase);
154 
155         kmf.init(ks, passphrase);
156         tmf.init(ts);
157         ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
158 
159         return ctx;
160     }
161 
162     @Test
163     public void testSSL() throws Exception {
164         startServer();
165 
166         Thread t = new Thread() {
167             public void run() {
168                 try {
169                     startClient();
170                 } catch (Exception e) {
171                     clientError = e;
172                 }
173             }
174         };
175         t.start();
176         t.join();
177         if (clientError != null)
178             throw clientError;
179     }
180 }