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   */
20  package org.apache.mina.filter.ssl;
21  
22  import static org.junit.Assert.*;
23  import java.io.IOException;
24  import java.net.InetSocketAddress;
25  import java.security.GeneralSecurityException;
26  import java.security.KeyStore;
27  import java.security.Security;
28  import java.util.concurrent.CountDownLatch;
29  import java.util.concurrent.TimeUnit;
30  
31  import javax.net.ssl.KeyManagerFactory;
32  import javax.net.ssl.SSLContext;
33  import javax.net.ssl.TrustManagerFactory;
34  
35  import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
36  import org.apache.mina.core.service.IoHandlerAdapter;
37  import org.apache.mina.core.session.IoSession;
38  import org.apache.mina.filter.codec.ProtocolCodecFilter;
39  import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
40  import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
41  import org.apache.mina.transport.socket.nio.NioSocketConnector;
42  import org.apache.mina.util.AvailablePortFinder;
43  import org.junit.Ignore;
44  import org.junit.Test;
45  
46  /**
47   * Test an SSL session where the connection cannot be established with the server due to 
48   * incompatible protocols (Test for DIRMINA-937)
49   *
50   * @author <a href="http://mina.apache.org">Apache MINA Project</a>
51   */
52  public class SslDIRMINA937Test {
53      /** A static port used for his test, chosen to avoid collisions */
54      private static final int port = AvailablePortFinder.getNextAvailable(5555);
55  
56      private static Exception clientError = null;
57  
58      /** A JVM independant KEY_MANAGER_FACTORY algorithm */
59      private static final String KEY_MANAGER_FACTORY_ALGORITHM;
60  
61      static {
62          String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
63          if (algorithm == null) {
64              algorithm = KeyManagerFactory.getDefaultAlgorithm();
65          }
66  
67          KEY_MANAGER_FACTORY_ALGORITHM = algorithm;
68      }
69  
70      private static class TestHandler extends IoHandlerAdapter {
71          public void messageReceived(IoSession session, Object message) throws Exception {
72              String line = (String) message;
73  
74              if (line.startsWith("hello")) {
75                  //System.out.println("Server got: 'hello', waiting for 'send'");
76                  Thread.sleep(1500);
77              } else if (line.startsWith("send")) {
78                  //System.out.println("Server got: 'send', sending 'data'");
79                  session.write("data");
80              }
81          }
82      }
83  
84      /**
85       * Starts a Server with the SSL Filter and a simple text line 
86       * protocol codec filter
87       */
88      private static void startServer() throws Exception {
89          NioSocketAcceptor acceptor = new NioSocketAcceptor();
90  
91          acceptor.setReuseAddress(true);
92          DefaultIoFilterChainBuilder filters = acceptor.getFilterChain();
93  
94          // Inject the SSL filter
95          SSLContext context = createSSLContext("TLSv1");
96          SslFilter sslFilter = new SslFilter(context);
97          sslFilter.setEnabledProtocols(new String[] { "TLSv1" });
98          //sslFilter.setEnabledCipherSuites(getServerCipherSuites(context.getDefaultSSLParameters().getCipherSuites()));
99          filters.addLast("sslFilter", sslFilter);
100 
101         // Inject the TestLine codec filter
102         filters.addLast("text", new ProtocolCodecFilter(new TextLineCodecFactory()));
103 
104         acceptor.setHandler(new TestHandler());
105         acceptor.bind(new InetSocketAddress(port));
106     }
107 
108     /**
109      * Starts a client which will connect twice using SSL
110      */
111     private static void startClient(final CountDownLatch counter) throws Exception {
112         NioSocketConnector connector = new NioSocketConnector();
113         
114         DefaultIoFilterChainBuilder filters = connector.getFilterChain();
115         SslFilter sslFilter = new SslFilter(createSSLContext("TLSv1.1"));
116         sslFilter.setEnabledProtocols(new String[] { "TLSv1.1" });
117         sslFilter.setUseClientMode(true);
118         //sslFilter.setEnabledCipherSuites(getClientCipherSuites());
119         filters.addLast("sslFilter", sslFilter);
120         connector.setHandler(new IoHandlerAdapter() {
121             @Override
122             public void sessionCreated(IoSession session) throws Exception {
123                 session.setAttribute(SslFilter.USE_NOTIFICATION, Boolean.TRUE);
124             }
125 
126             @Override
127             public void messageReceived(IoSession session, Object message) throws Exception {
128                 if (message == SslFilter.SESSION_SECURED) {
129                     counter.countDown();
130                 }
131             }
132 
133 
134         });
135         connector.connect(new InetSocketAddress("localhost", port));
136     }
137 
138     private static SSLContext createSSLContext(String protocol) throws IOException, GeneralSecurityException {
139         char[] passphrase = "password".toCharArray();
140 
141         SSLContext ctx = SSLContext.getInstance(protocol);
142         KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEY_MANAGER_FACTORY_ALGORITHM);
143         TrustManagerFactory tmf = TrustManagerFactory.getInstance(KEY_MANAGER_FACTORY_ALGORITHM);
144 
145         KeyStore ks = KeyStore.getInstance("JKS");
146         KeyStore ts = KeyStore.getInstance("JKS");
147 
148         ks.load(SslDIRMINA937Test.class.getResourceAsStream("keystore.sslTest"), passphrase);
149         ts.load(SslDIRMINA937Test.class.getResourceAsStream("truststore.sslTest"), passphrase);
150 
151         kmf.init(ks, passphrase);
152         tmf.init(ts);
153         ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
154 
155         return ctx;
156     }
157 
158     /**
159      * Test is ignore as it will cause the build to fail
160      */
161     @Test
162     @Ignore("This test is not yet fully functionnal, it servers as the basis for validating DIRMINA-937")
163     public void testDIRMINA937() throws Exception {
164         startServer();
165 
166         final CountDownLatch counter = new CountDownLatch(1);
167         startClient(counter);
168         assertTrue(counter.await(10, TimeUnit.SECONDS));
169     }
170 }