ServerTrustManager.java 9.92 KB
Newer Older
Gaston Dombiak's avatar
Gaston Dombiak committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/**
 * Copyright (C) 2004 Jive Software. All rights reserved.
 *
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
 */

package org.jivesoftware.wildfire.net;

import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.Log;

import javax.net.ssl.X509TrustManager;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.Enumeration;
19
import java.util.List;
Gaston Dombiak's avatar
Gaston Dombiak committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53

/**
 * ServerTrustManager is a Trust Manager that is only used for s2s connections. This TrustManager
 * is used both when the server connects to another server as well as when receiving a connection
 * from another server. In both cases, it is possible to indicate if self-signed certificates
 * are going to be accepted. In case of accepting a self-signed certificate a warning is logged.
 * Future version of the server might include a small workflow so admins can review self-signed
 * certificates or certificates of unknown issuers and manually accept them.
 *
 * @author Gaston Dombiak
 */
class ServerTrustManager implements X509TrustManager {

    /**
     * KeyStore that holds the trusted CA
     */
    private KeyStore trustStore;
    /**
     * Holds the domain of the remote server we are trying to connect
     */
    private String server;

    public ServerTrustManager(String server, KeyStore trustTrust) {
        super();
        this.server = server;
        this.trustStore = trustTrust;
    }

    public void checkClientTrusted(X509Certificate[] x509Certificates,
            String string) {
        // Do not validate the certificate at this point. The certificate is going to be used
        // when the remote server requests to do EXTERNAL SASL
    }

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    /**
     * Given the partial or complete certificate chain provided by the peer, build a certificate
     * path to a trusted root and return if it can be validated and is trusted for server SSL
     * authentication based on the authentication type. The authentication type is the key
     * exchange algorithm portion of the cipher suites represented as a String, such as "RSA",
     * "DHE_DSS". Note: for some exportable cipher suites, the key exchange algorithm is
     * determined at run time during the handshake. For instance, for
     * TLS_RSA_EXPORT_WITH_RC4_40_MD5, the authType should be RSA_EXPORT when an ephemeral
     * RSA key is used for the key exchange, and RSA when the key from the server certificate
     * is used. Checking is case-sensitive.<p>
     *
     * By default certificates are going to be verified. This includes verifying the certificate
     * chain, the root certificate and the certificates validity. However, it is possible to
     * disable certificates validation as a whole or each specific validation.
     *
     * @param x509Certificates an ordered array of peer X.509 certificates with the peer's own
     *        certificate listed first and followed by any certificate authorities.
     * @param string the key exchange algorithm used.
     * @throws CertificateException if the certificate chain is not trusted by this TrustManager.
     */
Gaston Dombiak's avatar
Gaston Dombiak committed
74 75 76 77 78 79 80 81 82
    public void checkServerTrusted(X509Certificate[] x509Certificates, String string)
            throws CertificateException {

        // Flag that indicates if certificates of the remote server should be validated. Disabling
        // certificate validation is not recommended for production environments.
        boolean verify = JiveGlobals.getBooleanProperty("xmpp.server.certificate.verify", true);
        if (verify) {
            int nSize = x509Certificates.length;

83
            List<String> peerIdentities = TLSStreamHandler.getPeerIdentities(x509Certificates[0]);
Gaston Dombiak's avatar
Gaston Dombiak committed
84

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
            if (JiveGlobals.getBooleanProperty("xmpp.server.certificate.verify.chain", true)) {
                // Working down the chain, for every certificate in the chain,
                // verify that the subject of the certificate is the issuer of the
                // next certificate in the chain.
                Principal principalLast = null;
                for (int i = nSize -1; i >= 0 ; i--) {
                    X509Certificate x509certificate = x509Certificates[i];
                    Principal principalIssuer = x509certificate.getIssuerDN();
                    Principal principalSubject = x509certificate.getSubjectDN();
                    if (principalLast != null) {
                        if (principalIssuer.equals(principalLast)) {
                            try {
                                PublicKey publickey =
                                        x509Certificates[i + 1].getPublicKey();
                                x509Certificates[i].verify(publickey);
                            }
                            catch (GeneralSecurityException generalsecurityexception) {
                                throw new CertificateException(
103
                                        "signature verification failed of " + peerIdentities);
104
                            }
Gaston Dombiak's avatar
Gaston Dombiak committed
105
                        }
106
                        else {
Gaston Dombiak's avatar
Gaston Dombiak committed
107
                            throw new CertificateException(
108
                                    "subject/issuer verification failed of " + peerIdentities);
Gaston Dombiak's avatar
Gaston Dombiak committed
109 110
                        }
                    }
111
                    principalLast = principalSubject;
Gaston Dombiak's avatar
Gaston Dombiak committed
112 113 114
                }
            }

115 116 117 118 119 120 121 122 123 124
            if (JiveGlobals.getBooleanProperty("xmpp.server.certificate.verify.root", true)) {
                // Verify that the the last certificate in the chain was issued
                // by a third-party that the client trusts.
                boolean trusted = false;
                try {
                    trusted = trustStore.getCertificateAlias(x509Certificates[nSize - 1]) != null;
                    if (!trusted && nSize == 1 && JiveGlobals
                            .getBooleanProperty("xmpp.server.certificate.accept-selfsigned", false))
                    {
                        Log.warn("Accepting self-signed certificate of remote server: " +
125
                                peerIdentities);
126 127 128 129 130 131 132
                        trusted = true;
                    }
                }
                catch (KeyStoreException e) {
                    Log.error(e);
                }
                if (!trusted) {
133
                    throw new CertificateException("root certificate not trusted of " + peerIdentities);
Gaston Dombiak's avatar
Gaston Dombiak committed
134 135 136
                }
            }

137
            // Verify that the first certificate in the chain corresponds to
Gaston Dombiak's avatar
Gaston Dombiak committed
138
            // the server we desire to authenticate.
139
            // Check if the certificate uses a wildcard indicating that subdomains are valid
140
            if (peerIdentities.size() == 1 && peerIdentities.get(0).startsWith("*.")) {
141
                // Remove the wildcard
142
                String peerIdentity = peerIdentities.get(0).replace("*.", "");
143 144
                // Check if the requested subdomain matches the certified domain
                if (!server.endsWith(peerIdentity)) {
145
                    throw new CertificateException("target verification failed of " + peerIdentities);
146 147
                }
            }
148 149
            else if (!peerIdentities.contains(server)) {
                throw new CertificateException("target verification failed of " + peerIdentities);
Gaston Dombiak's avatar
Gaston Dombiak committed
150 151
            }

152 153 154 155 156 157 158 159 160
            if (JiveGlobals.getBooleanProperty("xmpp.server.certificate.verify.validity", true)) {
                // For every certificate in the chain, verify that the certificate
                // is valid at the current time.
                Date date = new Date();
                for (int i = 0; i < nSize; i++) {
                    try {
                        x509Certificates[i].checkValidity(date);
                    }
                    catch (GeneralSecurityException generalsecurityexception) {
161
                        throw new CertificateException("invalid date of " + peerIdentities);
162
                    }
Gaston Dombiak's avatar
Gaston Dombiak committed
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
                }
            }
        }
    }

    private boolean isChainTrusted(X509Certificate[] chain) {
        boolean trusted = false;
        try {
            // Start with the root and see if it is in the Keystore.
            // The root is at the end of the chain.
            for (int i = chain.length - 1; i >= 0; i--) {
                if (trustStore.getCertificateAlias(chain[i]) != null) {
                    trusted = true;
                    break;
                }
            }
        }
        catch (Exception e) {
            Log.error(e);
            trusted = false;
        }
        return trusted;
    }

    public X509Certificate[] getAcceptedIssuers() {
        if (JiveGlobals.getBooleanProperty("xmpp.server.certificate.accept-selfsigned", false)) {
            // Answer an empty list since we accept any issuer
            return new X509Certificate[0];
        }
        else {
            X509Certificate[] X509Certs = null;
            try {
                // See how many certificates are in the keystore.
                int numberOfEntry = trustStore.size();
                // If there are any certificates in the keystore.
                if (numberOfEntry > 0) {
                    // Create an array of X509Certificates
                    X509Certs = new X509Certificate[numberOfEntry];

                    // Get all of the certificate alias out of the keystore.
                    Enumeration aliases = trustStore.aliases();

                    // Retrieve all of the certificates out of the keystore
                    // via the alias name.
                    int i = 0;
                    while (aliases.hasMoreElements()) {
                        X509Certs[i] =
                                (X509Certificate) trustStore.
                                        getCertificate((String) aliases.nextElement());
                        i++;
                    }

                }
            }
            catch (Exception e) {
                Log.error(e);
                X509Certs = null;
            }
            return X509Certs;
        }
    }
}