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