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      /** A JVM independant KEY_MANAGER_FACTORY algorithm */
57      private static final String KEY_MANAGER_FACTORY_ALGORITHM;
58  
59      static {
60          String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
61          if (algorithm == null) {
62              algorithm = KeyManagerFactory.getDefaultAlgorithm();
63          }
64  
65          KEY_MANAGER_FACTORY_ALGORITHM = algorithm;
66      }
67  
68      private static class TestHandler extends IoHandlerAdapter {
69          public void messageReceived(IoSession session, Object message) throws Exception {
70              String line = (String) message;
71  
72              if (line.startsWith("hello")) {
73                  //System.out.println("Server got: 'hello', waiting for 'send'");
74                  Thread.sleep(1500);
75              } else if (line.startsWith("send")) {
76                  //System.out.println("Server got: 'send', sending 'data'");
77                  session.write("data");
78              }
79          }
80      }
81  
82      /**
83       * Starts a Server with the SSL Filter and a simple text line 
84       * protocol codec filter
85       */
86      private static void startServer() throws Exception {
87          NioSocketAcceptor acceptor = new NioSocketAcceptor();
88  
89          acceptor.setReuseAddress(true);
90          DefaultIoFilterChainBuilder filters = acceptor.getFilterChain();
91  
92          // Inject the SSL filter
93          SSLContext context = createSSLContext("TLSv1");
94          SslFilter sslFilter = new SslFilter(context);
95          sslFilter.setEnabledProtocols(new String[] { "TLSv1" });
96          //sslFilter.setEnabledCipherSuites(getServerCipherSuites(context.getDefaultSSLParameters().getCipherSuites()));
97          filters.addLast("sslFilter", sslFilter);
98  
99          // Inject the TestLine codec filter
100         filters.addLast("text", new ProtocolCodecFilter(new TextLineCodecFactory()));
101 
102         acceptor.setHandler(new TestHandler());
103         acceptor.bind(new InetSocketAddress(port));
104     }
105 
106     /**
107      * Starts a client which will connect twice using SSL
108      */
109     private static void startClient(final CountDownLatch counter) throws Exception {
110         NioSocketConnector connector = new NioSocketConnector();
111         
112         DefaultIoFilterChainBuilder filters = connector.getFilterChain();
113         SslFilter sslFilter = new SslFilter(createSSLContext("TLSv1.1"));
114         sslFilter.setEnabledProtocols(new String[] { "TLSv1.1" });
115         sslFilter.setUseClientMode(true);
116         //sslFilter.setEnabledCipherSuites(getClientCipherSuites());
117         filters.addLast("sslFilter", sslFilter);
118         connector.setHandler(new IoHandlerAdapter() {
119             @Override
120             public void sessionCreated(IoSession session) throws Exception {
121                 session.setAttribute(SslFilter.USE_NOTIFICATION, Boolean.TRUE);
122             }
123 
124             @Override
125             public void messageReceived(IoSession session, Object message) throws Exception {
126                 if (message == SslFilter.SESSION_SECURED) {
127                     counter.countDown();
128                 }
129             }
130 
131 
132         });
133         connector.connect(new InetSocketAddress("localhost", port));
134     }
135 
136     private static SSLContext createSSLContext(String protocol) throws IOException, GeneralSecurityException {
137         char[] passphrase = "password".toCharArray();
138 
139         SSLContext ctx = SSLContext.getInstance(protocol);
140         KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEY_MANAGER_FACTORY_ALGORITHM);
141         TrustManagerFactory tmf = TrustManagerFactory.getInstance(KEY_MANAGER_FACTORY_ALGORITHM);
142 
143         KeyStore ks = KeyStore.getInstance("JKS");
144         KeyStore ts = KeyStore.getInstance("JKS");
145 
146         ks.load(SslDIRMINA937Test.class.getResourceAsStream("keystore.sslTest"), passphrase);
147         ts.load(SslDIRMINA937Test.class.getResourceAsStream("truststore.sslTest"), passphrase);
148 
149         kmf.init(ks, passphrase);
150         tmf.init(ts);
151         ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
152 
153         return ctx;
154     }
155 
156     /**
157      * Test is ignore as it will cause the build to fail
158      */
159     @Test
160     @Ignore("This test is not yet fully functionnal, it servers as the basis for validating DIRMINA-937")
161     public void testDIRMINA937() throws Exception {
162         startServer();
163 
164         final CountDownLatch counter = new CountDownLatch(1);
165         startClient(counter);
166         assertTrue(counter.await(10, TimeUnit.SECONDS));
167     }
168 }