001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.activemq.transport.tcp;
018
019import java.io.IOException;
020import java.net.URI;
021import java.net.UnknownHostException;
022import java.security.cert.X509Certificate;
023import java.util.HashMap;
024
025import javax.net.ssl.SSLPeerUnverifiedException;
026import javax.net.ssl.SSLSession;
027import javax.net.ssl.SSLSocket;
028import javax.net.ssl.SSLSocketFactory;
029
030import org.apache.activemq.command.ConnectionInfo;
031import org.apache.activemq.util.IntrospectionSupport;
032import org.apache.activemq.wireformat.WireFormat;
033
034/**
035 * A Transport class that uses SSL and client-side certificate authentication.
036 * Client-side certificate authentication must be enabled through the
037 * constructor. By default, this class will have the same client authentication
038 * behavior as the socket it is passed. This class will set ConnectionInfo's
039 * transportContext to the SSL certificates of the client. NOTE: Accessor method
040 * for needClientAuth was not provided on purpose. This is because
041 * needClientAuth's value must be set before the socket is connected. Otherwise,
042 * unexpected situations may occur.
043 */
044public class SslTransport extends TcpTransport {
045
046    /**
047     * Connect to a remote node such as a Broker.
048     *
049     * @param wireFormat The WireFormat to be used.
050     * @param socketFactory The socket factory to be used. Forcing SSLSockets
051     *                for obvious reasons.
052     * @param remoteLocation The remote location.
053     * @param localLocation The local location.
054     * @param needClientAuth If set to true, the underlying socket will need
055     *                client certificate authentication.
056     * @throws UnknownHostException If TcpTransport throws.
057     * @throws IOException If TcpTransport throws.
058     */
059    @SuppressWarnings({ "unchecked", "rawtypes" })
060    public SslTransport(WireFormat wireFormat, SSLSocketFactory socketFactory, URI remoteLocation, URI localLocation, boolean needClientAuth) throws IOException {
061        super(wireFormat, socketFactory, remoteLocation, localLocation);
062        if (this.socket != null) {
063            ((SSLSocket)this.socket).setNeedClientAuth(needClientAuth);
064
065            // Lets try to configure the SSL SNI field.  Handy in case your using
066            // a single proxy to route to different messaging apps.
067
068            // On java 1.7 it seems like it can only be configured via reflection.
069            // TODO: find out if this will work on java 1.8
070            HashMap props = new HashMap();
071            props.put("host", remoteLocation.getHost());
072            IntrospectionSupport.setProperties(this.socket, props);
073        }
074    }
075
076    /**
077     * Initialize from a ServerSocket. No access to needClientAuth is given
078     * since it is already set within the provided socket.
079     *
080     * @param wireFormat The WireFormat to be used.
081     * @param socket The Socket to be used. Forcing SSL.
082     * @throws IOException If TcpTransport throws.
083     */
084    public SslTransport(WireFormat wireFormat, SSLSocket socket) throws IOException {
085        super(wireFormat, socket);
086    }
087
088    public SslTransport(WireFormat format, SSLSocket socket,
089            InitBuffer initBuffer) throws IOException {
090        super(format, socket, initBuffer);
091    }
092
093    /**
094     * Overriding in order to add the client's certificates to ConnectionInfo
095     * Commmands.
096     *
097     * @param command The Command coming in.
098     */
099    @Override
100    public void doConsume(Object command) {
101        // The instanceof can be avoided, but that would require modifying the
102        // Command clas tree and that would require too much effort right
103        // now.
104        if (command instanceof ConnectionInfo) {
105            ConnectionInfo connectionInfo = (ConnectionInfo)command;
106            connectionInfo.setTransportContext(getPeerCertificates());
107        }
108        super.doConsume(command);
109    }
110
111    /**
112     * @return peer certificate chain associated with the ssl socket
113     */
114    @Override
115    public X509Certificate[] getPeerCertificates() {
116
117        SSLSocket sslSocket = (SSLSocket)this.socket;
118
119        SSLSession sslSession = sslSocket.getSession();
120
121        X509Certificate[] clientCertChain;
122        try {
123            clientCertChain = (X509Certificate[])sslSession.getPeerCertificates();
124        } catch (SSLPeerUnverifiedException e) {
125            clientCertChain = null;
126        }
127
128        return clientCertChain;
129    }
130
131    /**
132     * @return pretty print of 'this'
133     */
134    @Override
135    public String toString() {
136        return "ssl://" + socket.getInetAddress() + ":" + socket.getPort();
137    }
138}