OCSPChecker.java 13 KB
Newer Older
Jay Kline's avatar
Jay Kline committed
1 2 3
/**
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
 *
4 5 6 7 8 9 10 11 12 13 14
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
Jay Kline's avatar
Jay Kline committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
 */
package org.jivesoftware.openfire.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.NoSuchProviderException;
import java.security.cert.CertPath;
import java.security.cert.CertPathValidatorException;
import java.security.cert.CertStore;
import java.security.cert.Certificate;
import java.security.cert.PKIXCertPathChecker;
import java.security.cert.PKIXParameters;
import java.security.cert.TrustAnchor;
import java.security.cert.X509CertSelector;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
40

Jay Kline's avatar
Jay Kline committed
41
import javax.security.auth.x500.X500Principal;
42

Jay Kline's avatar
Jay Kline committed
43 44 45 46 47 48 49 50
import org.bouncycastle.ocsp.BasicOCSPResp;
import org.bouncycastle.ocsp.CertificateID;
import org.bouncycastle.ocsp.CertificateStatus;
import org.bouncycastle.ocsp.OCSPReq;
import org.bouncycastle.ocsp.OCSPReqGenerator;
import org.bouncycastle.ocsp.OCSPResp;
import org.bouncycastle.ocsp.SingleResp;
import org.jivesoftware.util.JiveGlobals;
51 52
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Jay Kline's avatar
Jay Kline committed
53 54 55 56 57 58 59 60 61 62 63

/**
 * A <code>PKIXCertPathChecker</code> that uses 
 * Online Certificate Status Protocol (OCSP) 
 * 
 * See <a href="http://www.ietf.org/rfc/rfc2560.txt">RFC 2560</a>.
 *
 * @author Jay Kline
 */
public class OCSPChecker extends PKIXCertPathChecker {

64 65
	private static final Logger Log = LoggerFactory.getLogger(OCSPChecker.class);

Jay Kline's avatar
Jay Kline committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    private static String ocspServerUrl = JiveGlobals.getProperty("ocsp.responderURL");
    private static String ocspServerSubject = JiveGlobals.getProperty("ocsp.responderCertSubjectName");
    private static final boolean dump = true;
    private int certIndex;
    private X509Certificate[] certs;
    private CertPath cp;
    private PKIXParameters pkixParams;

    OCSPChecker(CertPath certPath, PKIXParameters pkixParams)
            throws CertPathValidatorException {

        this.cp = certPath;
        this.pkixParams = pkixParams;
        List<? extends Certificate> tmp = cp.getCertificates();
        certs =
                (X509Certificate[]) tmp.toArray(new X509Certificate[tmp.size()]);
        init(false);
    }

85 86
    @Override
	public void init(boolean forward) throws CertPathValidatorException {
Jay Kline's avatar
Jay Kline committed
87 88 89 90 91 92 93 94
        if (!forward) {
            certIndex = certs.length - 1;
        } else {
            throw new CertPathValidatorException(
                    "Forward checking not supported");
        }
    }

95 96
    @Override
	public boolean isForwardCheckingSupported() {
Jay Kline's avatar
Jay Kline committed
97 98 99
        return false;
    }

100 101
    @Override
	public Set<String> getSupportedExtensions() {
Jay Kline's avatar
Jay Kline committed
102 103 104
        return Collections.<String>emptySet();
    }

105 106
    @Override
	public void check(Certificate cert, Collection<String> unresolvedCritExts)
Jay Kline's avatar
Jay Kline committed
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 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 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
            throws CertPathValidatorException {
        Log.debug("OCSPChecker: check called");
        InputStream in = null;
        OutputStream out = null;
        try {
            // Examine OCSP properties
            X509Certificate responderCert = null;
            boolean haveResponderCert = true; //defaults to issuers cert
            X500Principal responderSubjectName = null;
            boolean haveIssuerCert = false;

            // If we set the subject name, we need to find the certificate
            if (ocspServerSubject != null) {
                haveResponderCert = false;
                responderSubjectName = new X500Principal(ocspServerSubject);
            }


            X509Certificate issuerCert = null;
            X509Certificate currCert = (X509Certificate) cert;

            // Set the issuer certificate if we were passed a chain
            if (certIndex != 0) {
                issuerCert = (X509Certificate) (certs[certIndex]);
                haveIssuerCert = true;

                if (haveResponderCert) {
                    responderCert = certs[certIndex];
                }
            }


            if (!haveIssuerCert || !haveResponderCert) {

                if (!haveResponderCert) {
                    Log.debug("OCSPChecker: Looking for responder's certificate");
                }
                if (!haveIssuerCert) {
                    Log.debug("OCSPChecker: Looking for issuer's certificate");
                }

                // Extract the anchor certs
                Iterator anchors = pkixParams.getTrustAnchors().iterator();
                if (!anchors.hasNext()) {
                    throw new CertPathValidatorException(
                            "Must specify at least one trust anchor");
                }

                X500Principal certIssuerName =
                        currCert.getIssuerX500Principal();
                while (anchors.hasNext() &&
                        (!haveIssuerCert || !haveResponderCert)) {

                    TrustAnchor anchor = (TrustAnchor) anchors.next();
                    X509Certificate anchorCert = anchor.getTrustedCert();
                    X500Principal anchorSubjectName =
                            anchorCert.getSubjectX500Principal();

                    // Check if this anchor cert is the issuer cert
                    if (!haveIssuerCert && certIssuerName.equals(anchorSubjectName)) {

                        issuerCert = anchorCert;
                        haveIssuerCert = true;

                        //If we have not set the responderCert at this point, set it to the issuer
                        if (haveResponderCert && responderCert == null) {
                            responderCert = anchorCert;
                            Log.debug("OCSPChecker: Responder's certificate = issuer certificate");
                        }
                    }

                    // Check if this anchor cert is the responder cert
                    if (!haveResponderCert) {
                        if (responderSubjectName != null &&
                                responderSubjectName.equals(anchorSubjectName)) {

                            responderCert = anchorCert;
                            haveResponderCert = true;
                        }
                    }
                }
                
                if (issuerCert == null) {
                    //No trust anchor was found matching the issuer
                    throw new CertPathValidatorException("No trusted certificate for " + currCert.getIssuerDN());
                }

                // Check cert stores if responder cert has not yet been found
                if (!haveResponderCert) {
                    Log.debug("OCSPChecker: Searching cert stores for responder's certificate");
                    
                    if (responderSubjectName != null) {
                        X509CertSelector filter = new X509CertSelector();
                        filter.setSubject(responderSubjectName.getName());
                    
                        List<CertStore> certStores = pkixParams.getCertStores();
                        for (CertStore certStore : certStores) {
                            Iterator i = certStore.getCertificates(filter).iterator();
                            if (i.hasNext()) {
                                responderCert = (X509Certificate) i.next();
                                haveResponderCert = true;
                                break;
                            }
                        }
                    }
                }
            }

            // Could not find the responder cert
            if (!haveResponderCert) {
                throw new CertPathValidatorException("Cannot find the responder's certificate.");
            }

            // Construct an OCSP Request
            OCSPReqGenerator gen = new OCSPReqGenerator();

            CertificateID certID = new CertificateID(CertificateID.HASH_SHA1, issuerCert, currCert.getSerialNumber());
            gen.addRequest(certID);
            OCSPReq ocspRequest = gen.generate();


            URL url;
            if (ocspServerUrl != null) {
                try {
                    url = new URL(ocspServerUrl);
                } catch (MalformedURLException e) {
                    throw new CertPathValidatorException(e);
                }
            } else {
                throw new CertPathValidatorException("Must set OCSP Server URL");
            }
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            Log.debug("OCSPChecker: connecting to OCSP service at: " + url);

            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-type", "application/ocsp-request");
            con.setRequestProperty("Accept","application/ocsp-response");
            byte[] bytes = ocspRequest.getEncoded();


            con.setRequestProperty("Content-length", String.valueOf(bytes.length));
            out = con.getOutputStream();
            out.write(bytes);
            out.flush();

            // Check the response
            if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
                Log.debug("OCSPChecker: Received HTTP error: " + con.getResponseCode() +
                        " - " + con.getResponseMessage());
            }
            in = con.getInputStream();
            OCSPResp ocspResponse = new OCSPResp(in);
            BigInteger serialNumber = currCert.getSerialNumber();
            BasicOCSPResp brep = (BasicOCSPResp) ocspResponse.getResponseObject();
            try {
                if( ! brep.verify(responderCert.getPublicKey(),"BC")) {
                    throw new CertPathValidatorException("OCSP response is not verified");
                }
            } catch (NoSuchProviderException e) {
                throw new CertPathValidatorException("OCSP response could not be verified ("+e.getMessage()+")" ,null, cp, certIndex);
            }
            SingleResp[] singleResp = brep.getResponses();
            boolean foundResponse = false;
            for (SingleResp resp : singleResp) {
                CertificateID respCertID = resp.getCertID();
                if (respCertID.equals(certID)) {
                    Object status = resp.getCertStatus();
                    if (status == CertificateStatus.GOOD) {
                        Log.debug("OCSPChecker: Status of certificate (with serial number " +
                                serialNumber.toString() + ") is: good");
                        foundResponse = true;
                        break;
                    } else if (status instanceof org.bouncycastle.ocsp.RevokedStatus) {
                        Log.debug("OCSPChecker: Status of certificate (with serial number " +
                                serialNumber.toString() + ") is: revoked");
                        throw new CertPathValidatorException("Certificate has been revoked", null, cp, certIndex);
                    } else if (status instanceof org.bouncycastle.ocsp.UnknownStatus) {
                        Log.debug("OCSPChecker: Status of certificate (with serial number " +
                                serialNumber.toString() + ") is: unknown");
                        throw new CertPathValidatorException("Certificate's revocation status is unknown", null, cp, certIndex);
                    } else {
                        Log.debug("Status of certificate (with serial number " +
                                serialNumber.toString() + ") is: not recognized");
                        throw new CertPathValidatorException("Unknown OCSP response for certificate", null, cp, certIndex);
                    }
                }
            }

            // Check that response applies to the cert that was supplied
            if (!foundResponse) {
                throw new CertPathValidatorException(
                        "No certificates in the OCSP response match the " +
                        "certificate supplied in the OCSP request.");
            }
        } catch (CertPathValidatorException cpve) {
            throw cpve;
        } catch (Exception e) {
            throw new CertPathValidatorException(e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ioe) {
                    throw new CertPathValidatorException(ioe);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ioe) {
                    throw new CertPathValidatorException(ioe);
                }
            }
        }
    }
}