Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/security/provider/certpath/OCSP.java
38923 views
/*1* Copyright (c) 2009, 2017, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/24package sun.security.provider.certpath;2526import java.io.InputStream;27import java.io.IOException;28import java.io.OutputStream;29import java.net.URI;30import java.net.URL;31import java.net.HttpURLConnection;32import java.security.cert.CertificateException;33import java.security.cert.CertPathValidatorException;34import java.security.cert.CertPathValidatorException.BasicReason;35import java.security.cert.CRLReason;36import java.security.cert.Extension;37import java.security.cert.TrustAnchor;38import java.security.cert.X509Certificate;39import java.util.Arrays;40import java.util.Collections;41import java.util.Date;42import java.util.List;43import java.util.Map;4445import sun.security.action.GetIntegerAction;46import sun.security.util.Debug;47import sun.security.validator.Validator;48import sun.security.x509.AccessDescription;49import sun.security.x509.AuthorityInfoAccessExtension;50import sun.security.x509.GeneralName;51import sun.security.x509.GeneralNameInterface;52import sun.security.x509.PKIXExtensions;53import sun.security.x509.URIName;54import sun.security.x509.X509CertImpl;5556/**57* This is a class that checks the revocation status of a certificate(s) using58* OCSP. It is not a PKIXCertPathChecker and therefore can be used outside of59* the CertPathValidator framework. It is useful when you want to60* just check the revocation status of a certificate, and you don't want to61* incur the overhead of validating all of the certificates in the62* associated certificate chain.63*64* @author Sean Mullan65*/66public final class OCSP {6768private static final Debug debug = Debug.getInstance("certpath");6970private static final int DEFAULT_CONNECT_TIMEOUT = 15000;7172/**73* Integer value indicating the timeout length, in seconds, to be74* used for the OCSP check. A timeout of zero is interpreted as75* an infinite timeout.76*/77private static final int CONNECT_TIMEOUT = initializeTimeout();7879/**80* Initialize the timeout length by getting the OCSP timeout81* system property. If the property has not been set, or if its82* value is negative, set the timeout length to the default.83*/84private static int initializeTimeout() {85Integer tmp = java.security.AccessController.doPrivileged(86new GetIntegerAction("com.sun.security.ocsp.timeout"));87if (tmp == null || tmp < 0) {88return DEFAULT_CONNECT_TIMEOUT;89}90// Convert to milliseconds, as the system property will be91// specified in seconds92return tmp * 1000;93}9495private OCSP() {}969798/**99* Obtains the revocation status of a certificate using OCSP.100*101* @param cert the certificate to be checked102* @param issuerCert the issuer certificate103* @param responderURI the URI of the OCSP responder104* @param responderCert the OCSP responder's certificate105* @param date the time the validity of the OCSP responder's certificate106* should be checked against. If null, the current time is used.107* @return the RevocationStatus108* @throws IOException if there is an exception connecting to or109* communicating with the OCSP responder110* @throws CertPathValidatorException if an exception occurs while111* encoding the OCSP Request or validating the OCSP Response112*/113114// Called by com.sun.deploy.security.TrustDecider115public static RevocationStatus check(X509Certificate cert,116X509Certificate issuerCert,117URI responderURI,118X509Certificate responderCert,119Date date)120throws IOException, CertPathValidatorException121{122return check(cert, issuerCert, responderURI, responderCert, date,123Collections.<Extension>emptyList(),124Validator.VAR_PLUGIN_CODE_SIGNING);125}126127128public static RevocationStatus check(X509Certificate cert,129X509Certificate issuerCert, URI responderURI,130X509Certificate responderCert, Date date, List<Extension> extensions,131String variant)132throws IOException, CertPathValidatorException133{134return check(cert, responderURI, null, issuerCert, responderCert, date,135extensions, variant);136}137138public static RevocationStatus check(X509Certificate cert,139URI responderURI, TrustAnchor anchor, X509Certificate issuerCert,140X509Certificate responderCert, Date date,141List<Extension> extensions, String variant)142throws IOException, CertPathValidatorException143{144CertId certId;145try {146X509CertImpl certImpl = X509CertImpl.toImpl(cert);147certId = new CertId(issuerCert, certImpl.getSerialNumberObject());148} catch (CertificateException | IOException e) {149throw new CertPathValidatorException150("Exception while encoding OCSPRequest", e);151}152OCSPResponse ocspResponse = check(Collections.singletonList(certId),153responderURI, new OCSPResponse.IssuerInfo(anchor, issuerCert),154responderCert, date, extensions, variant);155return (RevocationStatus) ocspResponse.getSingleResponse(certId);156}157158/**159* Checks the revocation status of a list of certificates using OCSP.160*161* @param certIds the CertIds to be checked162* @param responderURI the URI of the OCSP responder163* @param issuerInfo the issuer's certificate and/or subject and public key164* @param responderCert the OCSP responder's certificate165* @param date the time the validity of the OCSP responder's certificate166* should be checked against. If null, the current time is used.167* @param extensions zero or more OCSP extensions to be included in the168* request. If no extensions are requested, an empty {@code List} must169* be used. A {@code null} value is not allowed.170* @return the OCSPResponse171* @throws IOException if there is an exception connecting to or172* communicating with the OCSP responder173* @throws CertPathValidatorException if an exception occurs while174* encoding the OCSP Request or validating the OCSP Response175*/176static OCSPResponse check(List<CertId> certIds, URI responderURI,177OCSPResponse.IssuerInfo issuerInfo,178X509Certificate responderCert, Date date,179List<Extension> extensions, String variant)180throws IOException, CertPathValidatorException181{182byte[] nonce = null;183for (Extension ext : extensions) {184if (ext.getId().equals(PKIXExtensions.OCSPNonce_Id.toString())) {185nonce = ext.getValue();186}187}188189OCSPResponse ocspResponse = null;190try {191byte[] response = getOCSPBytes(certIds, responderURI, extensions);192ocspResponse = new OCSPResponse(response);193194// verify the response195ocspResponse.verify(certIds, issuerInfo, responderCert, date,196nonce, variant);197} catch (IOException ioe) {198throw new CertPathValidatorException(199"Unable to determine revocation status due to network error",200ioe, null, -1, BasicReason.UNDETERMINED_REVOCATION_STATUS);201}202203return ocspResponse;204}205206207/**208* Send an OCSP request, then read and return the OCSP response bytes.209*210* @param certIds the CertIds to be checked211* @param responderURI the URI of the OCSP responder212* @param extensions zero or more OCSP extensions to be included in the213* request. If no extensions are requested, an empty {@code List} must214* be used. A {@code null} value is not allowed.215*216* @return the OCSP response bytes217*218* @throws IOException if there is an exception connecting to or219* communicating with the OCSP responder220*/221public static byte[] getOCSPBytes(List<CertId> certIds, URI responderURI,222List<Extension> extensions) throws IOException {223OCSPRequest request = new OCSPRequest(certIds, extensions);224byte[] bytes = request.encodeBytes();225226InputStream in = null;227OutputStream out = null;228byte[] response = null;229230try {231URL url = responderURI.toURL();232if (debug != null) {233debug.println("connecting to OCSP service at: " + url);234}235HttpURLConnection con = (HttpURLConnection)url.openConnection();236con.setConnectTimeout(CONNECT_TIMEOUT);237con.setReadTimeout(CONNECT_TIMEOUT);238con.setDoOutput(true);239con.setDoInput(true);240con.setRequestMethod("POST");241con.setRequestProperty242("Content-type", "application/ocsp-request");243con.setRequestProperty244("Content-length", String.valueOf(bytes.length));245out = con.getOutputStream();246out.write(bytes);247out.flush();248// Check the response249if (debug != null &&250con.getResponseCode() != HttpURLConnection.HTTP_OK) {251debug.println("Received HTTP error: " + con.getResponseCode()252+ " - " + con.getResponseMessage());253}254in = con.getInputStream();255int contentLength = con.getContentLength();256if (contentLength == -1) {257contentLength = Integer.MAX_VALUE;258}259response = new byte[contentLength > 2048 ? 2048 : contentLength];260int total = 0;261while (total < contentLength) {262int count = in.read(response, total, response.length - total);263if (count < 0)264break;265266total += count;267if (total >= response.length && total < contentLength) {268response = Arrays.copyOf(response, total * 2);269}270}271response = Arrays.copyOf(response, total);272} finally {273if (in != null) {274try {275in.close();276} catch (IOException ioe) {277throw ioe;278}279}280if (out != null) {281try {282out.close();283} catch (IOException ioe) {284throw ioe;285}286}287}288return response;289}290291/**292* Returns the URI of the OCSP Responder as specified in the293* certificate's Authority Information Access extension, or null if294* not specified.295*296* @param cert the certificate297* @return the URI of the OCSP Responder, or null if not specified298*/299// Called by com.sun.deploy.security.TrustDecider300public static URI getResponderURI(X509Certificate cert) {301try {302return getResponderURI(X509CertImpl.toImpl(cert));303} catch (CertificateException ce) {304// treat this case as if the cert had no extension305return null;306}307}308309static URI getResponderURI(X509CertImpl certImpl) {310311// Examine the certificate's AuthorityInfoAccess extension312AuthorityInfoAccessExtension aia =313certImpl.getAuthorityInfoAccessExtension();314if (aia == null) {315return null;316}317318List<AccessDescription> descriptions = aia.getAccessDescriptions();319for (AccessDescription description : descriptions) {320if (description.getAccessMethod().equals(321AccessDescription.Ad_OCSP_Id)) {322323GeneralName generalName = description.getAccessLocation();324if (generalName.getType() == GeneralNameInterface.NAME_URI) {325URIName uri = (URIName) generalName.getName();326return uri.getURI();327}328}329}330return null;331}332333/**334* The Revocation Status of a certificate.335*/336public static interface RevocationStatus {337public enum CertStatus { GOOD, REVOKED, UNKNOWN };338339/**340* Returns the revocation status.341*/342CertStatus getCertStatus();343/**344* Returns the time when the certificate was revoked, or null345* if it has not been revoked.346*/347Date getRevocationTime();348/**349* Returns the reason the certificate was revoked, or null if it350* has not been revoked.351*/352CRLReason getRevocationReason();353354/**355* Returns a Map of additional extensions.356*/357Map<String, Extension> getSingleExtensions();358}359}360361362