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.FilterEvent;
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.transport.socket.nio.NioSocketConnector;
43  import org.apache.mina.util.AvailablePortFinder;
44  import org.junit.Ignore;
45  import org.junit.Test;
46  
47  /**
48   * Test an SSL session where the connection cannot be established with the server due to 
49   * incompatible protocols (Test for DIRMINA-937)
50   *
51   * @author <a href="http://mina.apache.org">Apache MINA Project</a>
52   */
53  public class SslDIRMINA937Test {
54      /** A static port used for his test, chosen to avoid collisions */
55      private static final int port = AvailablePortFinder.getNextAvailable(5555);
56  
57      /** A JVM independant KEY_MANAGER_FACTORY algorithm */
58      private static final String KEY_MANAGER_FACTORY_ALGORITHM;
59  
60      static {
61          String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
62          if (algorithm == null) {
63              algorithm = KeyManagerFactory.getDefaultAlgorithm();
64          }
65  
66          KEY_MANAGER_FACTORY_ALGORITHM = algorithm;
67      }
68  
69      private static class TestHandler extends IoHandlerAdapter {
70          public void messageReceived(IoSession session, Object message) throws Exception {
71              String line = (String) message;
72  
73              if (line.startsWith("hello")) {
74                  //System.out.println("Server got: 'hello', waiting for 'send'");
75                  Thread.sleep(1500);
76              } else if (line.startsWith("send")) {
77                  //System.out.println("Server got: 'send', sending 'data'");
78                  session.write("data");
79              }
80          }
81      }
82  
83      /**
84       * Starts a Server with the SSL Filter and a simple text line 
85       * protocol codec filter
86       */
87      private static void startServer() throws Exception {
88          NioSocketAcceptor acceptor = new NioSocketAcceptor();
89  
90          acceptor.setReuseAddress(true);
91          DefaultIoFilterChainBuilder filters = acceptor.getFilterChain();
92  
93          // Inject the SSL filter
94          SSLContext context = createSSLContext("TLSv1");
95          SslFilter sslFilter = new SslFilter(context);
96          sslFilter.setEnabledProtocols(new String[] { "TLSv1" });
97          //sslFilter.setEnabledCipherSuites(getServerCipherSuites(context.getDefaultSSLParameters().getCipherSuites()));
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(final CountDownLatch counter) throws Exception {
111         NioSocketConnector connector = new NioSocketConnector();
112         
113         DefaultIoFilterChainBuilder filters = connector.getFilterChain();
114         SslFilter sslFilter = new SslFilter(createSSLContext("TLSv1.1"));
115         sslFilter.setEnabledProtocols(new String[] { "TLSv1.1" });
116         sslFilter.setUseClientMode(true);
117         //sslFilter.setEnabledCipherSuites(getClientCipherSuites());
118         filters.addLast("sslFilter", sslFilter);
119         connector.setHandler(new IoHandlerAdapter() {
120             @Override
121             public void messageReceived(IoSession session, Object message) throws Exception {
122             }
123 
124             @Override
125             public void event(IoSession session, FilterEvent event) throws Exception {
126                 if (event == SslEvent.UNSECURED ) {
127                     counter.countDown();
128                 }
129             }
130         });
131         connector.connect(new InetSocketAddress("localhost", port));
132     }
133 
134     private static SSLContext createSSLContext(String protocol) throws IOException, GeneralSecurityException {
135         char[] passphrase = "password".toCharArray();
136 
137         SSLContext ctx = SSLContext.getInstance(protocol);
138         KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEY_MANAGER_FACTORY_ALGORITHM);
139         TrustManagerFactory tmf = TrustManagerFactory.getInstance(KEY_MANAGER_FACTORY_ALGORITHM);
140 
141         KeyStore ks = KeyStore.getInstance("JKS");
142         KeyStore ts = KeyStore.getInstance("JKS");
143 
144         ks.load(SslDIRMINA937Test.class.getResourceAsStream("keystore.sslTest"), passphrase);
145         ts.load(SslDIRMINA937Test.class.getResourceAsStream("truststore.sslTest"), passphrase);
146 
147         kmf.init(ks, passphrase);
148         tmf.init(ts);
149         ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
150 
151         return ctx;
152     }
153 
154     /**
155      * Test is ignore as it will cause the build to fail
156      * 
157      * @throws Exception If the test failed
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 }