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.example.echoserver.ssl;
21  
22  import java.net.InetSocketAddress;
23  import java.net.Socket;
24  import java.nio.charset.Charset;
25  import java.security.cert.CertificateException;
26  import java.util.ArrayList;
27  import java.util.List;
28  
29  import javax.net.ssl.SSLContext;
30  import javax.net.ssl.SSLSocket;
31  import javax.net.ssl.TrustManager;
32  import javax.net.ssl.X509TrustManager;
33  
34  import org.apache.mina.core.service.IoHandlerAdapter;
35  import org.apache.mina.core.session.IoSession;
36  import org.apache.mina.filter.codec.ProtocolCodecFilter;
37  import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
38  import org.apache.mina.filter.ssl.SslFilter;
39  import org.apache.mina.transport.socket.SocketAcceptor;
40  import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
41  import org.junit.After;
42  import org.junit.Before;
43  import org.junit.Test;
44  import static org.junit.Assert.assertEquals;
45  import static org.junit.Assert.assertTrue;
46  
47  /**
48   * TODO Add documentation
49   * 
50   * @author The Apache MINA Project (dev@mina.apache.org)
51   */
52  public class SslFilterTest {
53  
54      private int port;
55      private SocketAcceptor acceptor;
56  
57      @Before
58      public void setUp() throws Exception {
59          acceptor = new NioSocketAcceptor();
60      }
61  
62      @After
63      public void tearDown() throws Exception {
64          acceptor.setCloseOnDeactivation(true);
65          acceptor.dispose();
66      }
67  
68      @Test
69      public void testMessageSentIsCalled() throws Exception {
70          testMessageSentIsCalled(false);
71      }
72  
73      @Test
74      public void testMessageSentIsCalled_With_SSL() throws Exception {
75          testMessageSentIsCalled(true);
76      }
77  
78      private void testMessageSentIsCalled(boolean useSSL) throws Exception {
79          SslFilter sslFilter = null;
80          if (useSSL) {
81              sslFilter = new SslFilter(BogusSslContextFactory.getInstance(true));
82              acceptor.getFilterChain().addLast("sslFilter", sslFilter);
83          }
84          acceptor.getFilterChain().addLast(
85                  "codec",
86                  new ProtocolCodecFilter(new TextLineCodecFactory(Charset
87                          .forName("UTF-8"))));
88  
89          EchoHandler handler = new EchoHandler();
90          acceptor.setHandler(handler);
91          acceptor.bind(new InetSocketAddress(0));
92          port = acceptor.getLocalAddress().getPort();
93          //System.out.println("MINA server started.");
94  
95          Socket socket = getClientSocket(useSSL);
96          int bytesSent = 0;
97          bytesSent += writeMessage(socket, "test-1\n");
98  
99          if (useSSL) {
100             // Test renegotiation
101             SSLSocket ss = (SSLSocket) socket;
102             //ss.getSession().invalidate();
103             ss.startHandshake();
104         }
105 
106         bytesSent += writeMessage(socket, "test-2\n");
107 
108         int[] response = new int[bytesSent];
109         for (int i = 0; i < response.length; i++) {
110             response[i] = socket.getInputStream().read();
111         }
112 
113         if (useSSL) {
114             // Read SSL close notify.
115             while (socket.getInputStream().read() >= 0) {
116                 continue;
117             }
118         }
119 
120         socket.close();
121         while (acceptor.getManagedSessions().size() != 0) {
122             Thread.sleep(100);
123         }
124 
125         //System.out.println("handler: " + handler.sentMessages);
126         assertEquals("handler should have sent 2 messages:", 2,
127                 handler.sentMessages.size());
128         assertTrue(handler.sentMessages.contains("test-1"));
129         assertTrue(handler.sentMessages.contains("test-2"));
130     }
131 
132     private int writeMessage(Socket socket, String message) throws Exception {
133         byte request[] = message.getBytes("UTF-8");
134         socket.getOutputStream().write(request);
135         return request.length;
136     }
137 
138     private Socket getClientSocket(boolean ssl) throws Exception {
139         if (ssl) {
140             SSLContext ctx = SSLContext.getInstance("TLS");
141             ctx.init(null, trustManagers, null);
142             return ctx.getSocketFactory().createSocket("localhost", port);
143         }
144         return new Socket("localhost", port);
145     }
146 
147     private static class EchoHandler extends IoHandlerAdapter {
148 
149         List<String> sentMessages = new ArrayList<String>();
150 
151         @Override
152         public void exceptionCaught(IoSession session, Throwable cause)
153                 throws Exception {
154             //cause.printStackTrace();
155         }
156 
157         @Override
158         public void messageReceived(IoSession session, Object message)
159                 throws Exception {
160             session.write(message);
161         }
162 
163         @Override
164         public void messageSent(IoSession session, Object message)
165                 throws Exception {
166             sentMessages.add(message.toString());
167             //System.out.println(message);
168             if (sentMessages.size() >= 2) {
169                 session.close(true);
170             }
171         }
172     }
173 
174     TrustManager[] trustManagers = new TrustManager[] { new TrustAnyone() };
175 
176     private static class TrustAnyone implements X509TrustManager {
177         public void checkClientTrusted(
178                 java.security.cert.X509Certificate[] x509Certificates, String s)
179                 throws CertificateException {
180         }
181 
182         public void checkServerTrusted(
183                 java.security.cert.X509Certificate[] x509Certificates, String s)
184                 throws CertificateException {
185         }
186 
187         public java.security.cert.X509Certificate[] getAcceptedIssuers() {
188             return new java.security.cert.X509Certificate[0];
189         }
190     }
191 
192 }