aboutsummaryrefslogtreecommitdiff
path: root/src/share/classes/sun/security/provider/certpath/OCSPChecker.java
blob: 35ed85def19ebbffd77662eb5684a5d70bd4e737 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
/*
 * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

package sun.security.provider.certpath;

import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.security.AccessController;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.security.Security;
import java.security.cert.*;
import java.security.cert.CertPathValidatorException.BasicReason;
import java.net.*;
import javax.security.auth.x500.X500Principal;

import sun.security.util.*;
import sun.security.x509.*;

/**
 * OCSPChecker is a <code>PKIXCertPathChecker</code> that uses the
 * Online Certificate Status Protocol (OCSP) as specified in RFC 2560
 * <a href="http://www.ietf.org/rfc/rfc2560.txt">
 * http://www.ietf.org/rfc/rfc2560.txt</a>.
 *
 * @author      Ram Marti
 */
class OCSPChecker extends PKIXCertPathChecker {

    public static final String OCSP_ENABLE_PROP = "ocsp.enable";
    public static final String OCSP_URL_PROP = "ocsp.responderURL";
    public static final String OCSP_CERT_SUBJECT_PROP =
        "ocsp.responderCertSubjectName";
    public static final String OCSP_CERT_ISSUER_PROP =
        "ocsp.responderCertIssuerName";
    public static final String OCSP_CERT_NUMBER_PROP =
        "ocsp.responderCertSerialNumber";

    private static final String HEX_DIGITS = "0123456789ABCDEFabcdef";
    private static final Debug DEBUG = Debug.getInstance("certpath");
    private static final boolean dump = false;

    // Supported extensions
    private static final int OCSP_NONCE_DATA[] =
        { 1, 3, 6, 1, 5, 5, 7, 48, 1, 2 };
    private static final ObjectIdentifier OCSP_NONCE_OID;
    static {
        OCSP_NONCE_OID = ObjectIdentifier.newInternal(OCSP_NONCE_DATA);
    }

    private int remainingCerts;

    private X509Certificate[] certs;

    private CertPath cp;

    private PKIXParameters pkixParams;

    /**
     * Default Constructor
     *
     * @param certPath the X509 certification path
     * @param pkixParams the input PKIX parameter set
     * @exception CertPathValidatorException Exception thrown if cert path
     * does not validate.
     */
    OCSPChecker(CertPath certPath, PKIXParameters pkixParams)
        throws CertPathValidatorException {

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

    /**
     * Initializes the internal state of the checker from parameters
     * specified in the constructor
     */
    public void init(boolean forward) throws CertPathValidatorException {
        if (!forward) {
            remainingCerts = certs.length + 1;
        } else {
            throw new CertPathValidatorException(
                "Forward checking not supported");
        }
    }

    public boolean isForwardCheckingSupported() {
        return false;
    }

    public Set<String> getSupportedExtensions() {
        return Collections.<String>emptySet();
    }

    /**
     * Sends an OCSPRequest for the certificate to the OCSP Server and
     * processes the response back from the OCSP Server.
     *
     * @param cert the Certificate
     * @param unresolvedCritExts the unresolved critical extensions
     * @exception CertPathValidatorException Exception is thrown if the
     *            certificate has been revoked.
     */
    public void check(Certificate cert, Collection<String> unresolvedCritExts)
        throws CertPathValidatorException {

        InputStream in = null;
        OutputStream out = null;

        // Decrement the certificate counter
        remainingCerts--;

        try {
            X509Certificate responderCert = null;
            boolean seekResponderCert = false;
            X500Principal responderSubjectName = null;
            X500Principal responderIssuerName = null;
            BigInteger responderSerialNumber = null;

            boolean seekIssuerCert = true;
            X509CertImpl issuerCertImpl = null;
            X509CertImpl currCertImpl =
                X509CertImpl.toImpl((X509Certificate)cert);

            /*
             * OCSP security property values, in the following order:
             *   1. ocsp.responderURL
             *   2. ocsp.responderCertSubjectName
             *   3. ocsp.responderCertIssuerName
             *   4. ocsp.responderCertSerialNumber
             */
            String[] properties = getOCSPProperties();

            // Check whether OCSP is feasible before seeking cert information
            URL url = getOCSPServerURL(currCertImpl, properties);

            // When responder's subject name is set then the issuer/serial
            // properties are ignored
            if (properties[1] != null) {
                responderSubjectName = new X500Principal(properties[1]);

            } else if (properties[2] != null && properties[3] != null) {
                responderIssuerName = new X500Principal(properties[2]);
                // remove colon or space separators
                String value = stripOutSeparators(properties[3]);
                responderSerialNumber = new BigInteger(value, 16);

            } else if (properties[2] != null || properties[3] != null) {
                throw new CertPathValidatorException(
                    "Must specify both ocsp.responderCertIssuerName and " +
                    "ocsp.responderCertSerialNumber properties");
            }

            // If the OCSP responder cert properties are set then the
            // identified cert must be located in the trust anchors or
            // in the cert stores.
            if (responderSubjectName != null || responderIssuerName != null) {
                seekResponderCert = true;
            }

            // Set the issuer certificate to the next cert in the chain
            // (unless we're processing the final cert).
            if (remainingCerts < certs.length) {
                issuerCertImpl = X509CertImpl.toImpl(certs[remainingCerts]);
                seekIssuerCert = false; // done

                // By default, the OCSP responder's cert is the same as the
                // issuer of the cert being validated.
                if (! seekResponderCert) {
                    responderCert = certs[remainingCerts];
                    if (DEBUG != null) {
                        DEBUG.println("Responder's certificate is the same " +
                            "as the issuer of the certificate being validated");
                    }
                }
            }

            // Check anchor certs for:
            //    - the issuer cert (of the cert being validated)
            //    - the OCSP responder's cert
            if (seekIssuerCert || seekResponderCert) {

                if (DEBUG != null && seekResponderCert) {
                    DEBUG.println("Searching trust anchors for responder'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 =
                    currCertImpl.getIssuerX500Principal();
                while (anchors.hasNext() &&
                        (seekIssuerCert || seekResponderCert)) {

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

                    if (dump) {
                        System.out.println("Issuer DN is " + certIssuerName);
                        System.out.println("Subject DN is " +
                            anchorSubjectName);
                    }

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

                        issuerCertImpl = X509CertImpl.toImpl(anchorCert);
                        seekIssuerCert = false; // done

                        // By default, the OCSP responder's cert is the same as
                        // the issuer of the cert being validated.
                        if (! seekResponderCert && responderCert == null) {
                            responderCert = anchorCert;
                            if (DEBUG != null) {
                                DEBUG.println("Responder's certificate is the" +
                                    " same as the issuer of the certificate " +
                                    "being validated");
                            }
                        }
                    }

                    // Check if anchor cert is the responder cert
                    if (seekResponderCert) {
                        // Satisfy the responder subject name property only, or
                        // satisfy the responder issuer name and serial number
                        // properties only
                        if ((responderSubjectName != null &&
                             responderSubjectName.equals(anchorSubjectName)) ||
                            (responderIssuerName != null &&
                             responderSerialNumber != null &&
                             responderIssuerName.equals(
                                anchorCert.getIssuerX500Principal()) &&
                             responderSerialNumber.equals(
                                anchorCert.getSerialNumber()))) {

                            responderCert = anchorCert;
                            seekResponderCert = false; // done
                        }
                    }
                }
                if (issuerCertImpl == null) {
                    throw new CertPathValidatorException(
                        "No trusted certificate for " +
                        currCertImpl.getIssuerDN());
                }

                // Check cert stores if responder cert has not yet been found
                if (seekResponderCert) {
                    if (DEBUG != null) {
                        DEBUG.println("Searching cert stores for responder's " +
                            "certificate");
                    }
                    X509CertSelector filter = null;
                    if (responderSubjectName != null) {
                        filter = new X509CertSelector();
                        filter.setSubject(responderSubjectName.getName());
                    } else if (responderIssuerName != null &&
                        responderSerialNumber != null) {
                        filter = new X509CertSelector();
                        filter.setIssuer(responderIssuerName.getName());
                        filter.setSerialNumber(responderSerialNumber);
                    }
                    if (filter != null) {
                        List<CertStore> certStores = pkixParams.getCertStores();
                        for (CertStore certStore : certStores) {
                            Iterator i =
                                certStore.getCertificates(filter).iterator();
                            if (i.hasNext()) {
                                responderCert = (X509Certificate) i.next();
                                seekResponderCert = false; // done
                                break;
                            }
                        }
                    }
                }
            }

            // Could not find the certificate identified in the OCSP properties
            if (seekResponderCert) {
                throw new CertPathValidatorException(
                    "Cannot find the responder's certificate " +
                    "(set using the OCSP security properties).");
            }

            // Construct an OCSP Request
            OCSPRequest ocspRequest =
                new OCSPRequest(currCertImpl, issuerCertImpl);

            // Use the URL to the OCSP service that was created earlier
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            if (DEBUG != null) {
                DEBUG.println("connecting to OCSP service at: " + url);
            }

            // Indicate that both input and output will be performed,
            // that the method is POST, and that the content length is
            // the length of the byte array

            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-type", "application/ocsp-request");
            byte[] bytes = ocspRequest.encodeBytes();
            CertId certId = ocspRequest.getCertId();

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

            // Check the response
            if (DEBUG != null &&
                con.getResponseCode() != HttpURLConnection.HTTP_OK) {
                DEBUG.println("Received HTTP error: " + con.getResponseCode() +
                    " - " + con.getResponseMessage());
            }
            in = con.getInputStream();

            int contentLength = con.getContentLength();
            if (contentLength == -1) {
                contentLength = Integer.MAX_VALUE;
            }

            byte[] response = new byte[contentLength];
            int total = 0;
            int count = 0;
            while (count != -1 && total < contentLength) {
                count = in.read(response, total, response.length - total);
                total += count;
            }

            OCSPResponse ocspResponse = new OCSPResponse(response, pkixParams,
                responderCert);
            // Check that response applies to the cert that was supplied
            if (! certId.equals(ocspResponse.getCertId())) {
                throw new CertPathValidatorException(
                    "Certificate in the OCSP response does not match the " +
                    "certificate supplied in the OCSP request.");
            }
            SerialNumber serialNumber = currCertImpl.getSerialNumberObject();
            int certOCSPStatus = ocspResponse.getCertStatus(serialNumber);

            if (DEBUG != null) {
                DEBUG.println("Status of certificate (with serial number " +
                    serialNumber.getNumber() + ") is: " +
                    OCSPResponse.certStatusToText(certOCSPStatus));
            }

            if (certOCSPStatus == OCSPResponse.CERT_STATUS_REVOKED) {
                Throwable t = new CertificateRevokedException(
                        ocspResponse.getRevocationTime(),
                        ocspResponse.getRevocationReason(),
                        responderCert.getSubjectX500Principal(),
                        ocspResponse.getSingleExtensions());
                throw new CertPathValidatorException(t.getMessage(), t,
                        null, -1, BasicReason.REVOKED);

            } else if (certOCSPStatus == OCSPResponse.CERT_STATUS_UNKNOWN) {
                throw new CertPathValidatorException(
                    "Certificate's revocation status is unknown", null, cp,
                    remainingCerts, BasicReason.UNDETERMINED_REVOCATION_STATUS);
            }
        } 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);
                }
            }
        }
    }

    /*
     * The OCSP security property values are in the following order:
     *   1. ocsp.responderURL
     *   2. ocsp.responderCertSubjectName
     *   3. ocsp.responderCertIssuerName
     *   4. ocsp.responderCertSerialNumber
     */
    private static URL getOCSPServerURL(X509CertImpl currCertImpl,
        String[] properties)
        throws CertificateParsingException, CertPathValidatorException {

        if (properties[0] != null) {
           try {
                return new URL(properties[0]);
           } catch (java.net.MalformedURLException e) {
                throw new CertPathValidatorException(e);
           }
        }

        // Examine the certificate's AuthorityInfoAccess extension

        AuthorityInfoAccessExtension aia =
            currCertImpl.getAuthorityInfoAccessExtension();
        if (aia == null) {
            throw new CertPathValidatorException(
                "Must specify the location of an OCSP Responder");
        }

        List<AccessDescription> descriptions = aia.getAccessDescriptions();
        for (AccessDescription description : descriptions) {
            if (description.getAccessMethod().equals(
                AccessDescription.Ad_OCSP_Id)) {

                GeneralName generalName = description.getAccessLocation();
                if (generalName.getType() == GeneralNameInterface.NAME_URI) {
                    try {
                        URIName uri = (URIName) generalName.getName();
                        return (new URL(uri.getName()));

                    } catch (java.net.MalformedURLException e) {
                        throw new CertPathValidatorException(e);
                    }
                }
            }
        }

        throw new CertPathValidatorException(
            "Cannot find the location of the OCSP Responder");
    }

    /*
     * Retrieves the values of the OCSP security properties.
     */
    private static String[] getOCSPProperties() {
        final String[] properties = new String[4];

        AccessController.doPrivileged(
            new PrivilegedAction<Void>() {
                public Void run() {
                    properties[0] = Security.getProperty(OCSP_URL_PROP);
                    properties[1] =
                        Security.getProperty(OCSP_CERT_SUBJECT_PROP);
                    properties[2] =
                        Security.getProperty(OCSP_CERT_ISSUER_PROP);
                    properties[3] =
                        Security.getProperty(OCSP_CERT_NUMBER_PROP);
                    return null;
                }
            });

        return properties;
    }

    /*
     * Removes any non-hexadecimal characters from a string.
     */
    private static String stripOutSeparators(String value) {
        char[] chars = value.toCharArray();
        StringBuilder hexNumber = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            if (HEX_DIGITS.indexOf(chars[i]) != -1) {
                hexNumber.append(chars[i]);
            }
        }
        return hexNumber.toString();
    }
}