Path: blob/master/src/java.base/share/classes/sun/security/provider/certpath/OCSP.java
41161 views
/*1* Copyright (c) 2009, 2021, 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.IOException;27import java.io.OutputStream;28import java.net.URI;29import java.net.URL;30import java.net.HttpURLConnection;31import java.net.URLEncoder;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.Base64;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.util.Event;48import sun.security.util.IOUtils;49import sun.security.validator.Validator;50import sun.security.x509.AccessDescription;51import sun.security.x509.AuthorityInfoAccessExtension;52import sun.security.x509.GeneralName;53import sun.security.x509.GeneralNameInterface;54import sun.security.x509.PKIXExtensions;55import sun.security.x509.URIName;56import sun.security.x509.X509CertImpl;5758/**59* This is a class that checks the revocation status of a certificate(s) using60* OCSP. It is not a PKIXCertPathChecker and therefore can be used outside of61* the CertPathValidator framework. It is useful when you want to62* just check the revocation status of a certificate, and you don't want to63* incur the overhead of validating all of the certificates in the64* associated certificate chain.65*66* @author Sean Mullan67*/68public final class OCSP {6970private static final Debug debug = Debug.getInstance("certpath");7172private static final int DEFAULT_CONNECT_TIMEOUT = 15000;7374/**75* Integer value indicating the timeout length, in seconds, to be76* used for the OCSP check. A timeout of zero is interpreted as77* an infinite timeout.78*/79private static final int CONNECT_TIMEOUT = initializeTimeout();8081/**82* Initialize the timeout length by getting the OCSP timeout83* system property. If the property has not been set, or if its84* value is negative, set the timeout length to the default.85*/86private static int initializeTimeout() {87@SuppressWarnings("removal")88Integer tmp = java.security.AccessController.doPrivileged(89new GetIntegerAction("com.sun.security.ocsp.timeout"));90if (tmp == null || tmp < 0) {91return DEFAULT_CONNECT_TIMEOUT;92}93// Convert to milliseconds, as the system property will be94// specified in seconds95return tmp * 1000;96}9798private OCSP() {}99100101/**102* Obtains the revocation status of a certificate using OCSP.103*104* @param cert the certificate to be checked105* @param issuerCert the issuer certificate106* @param responderURI the URI of the OCSP responder107* @param responderCert the OCSP responder's certificate108* @param date the time the validity of the OCSP responder's certificate109* should be checked against. If null, the current time is used.110* @return the RevocationStatus111* @throws IOException if there is an exception connecting to or112* communicating with the OCSP responder113* @throws CertPathValidatorException if an exception occurs while114* encoding the OCSP Request or validating the OCSP Response115*/116117// Called by com.sun.deploy.security.TrustDecider118public static RevocationStatus check(X509Certificate cert,119X509Certificate issuerCert,120URI responderURI,121X509Certificate responderCert,122Date date)123throws IOException, CertPathValidatorException124{125return check(cert, issuerCert, responderURI, responderCert, date,126Collections.<Extension>emptyList(),127Validator.VAR_PLUGIN_CODE_SIGNING);128}129130131public static RevocationStatus check(X509Certificate cert,132X509Certificate issuerCert, URI responderURI,133X509Certificate responderCert, Date date, List<Extension> extensions,134String variant)135throws IOException, CertPathValidatorException136{137return check(cert, responderURI, null, issuerCert, responderCert, date,138extensions, variant);139}140141public static RevocationStatus check(X509Certificate cert,142URI responderURI, TrustAnchor anchor, X509Certificate issuerCert,143X509Certificate responderCert, Date date,144List<Extension> extensions, String variant)145throws IOException, CertPathValidatorException146{147CertId certId;148try {149X509CertImpl certImpl = X509CertImpl.toImpl(cert);150certId = new CertId(issuerCert, certImpl.getSerialNumberObject());151} catch (CertificateException | IOException e) {152throw new CertPathValidatorException153("Exception while encoding OCSPRequest", e);154}155OCSPResponse ocspResponse = check(Collections.singletonList(certId),156responderURI, new OCSPResponse.IssuerInfo(anchor, issuerCert),157responderCert, date, extensions, variant);158return (RevocationStatus) ocspResponse.getSingleResponse(certId);159}160161/**162* Checks the revocation status of a list of certificates using OCSP.163*164* @param certIds the CertIds to be checked165* @param responderURI the URI of the OCSP responder166* @param issuerInfo the issuer's certificate and/or subject and public key167* @param responderCert the OCSP responder's certificate168* @param date the time the validity of the OCSP responder's certificate169* should be checked against. If null, the current time is used.170* @param extensions zero or more OCSP extensions to be included in the171* request. If no extensions are requested, an empty {@code List} must172* be used. A {@code null} value is not allowed.173* @return the OCSPResponse174* @throws IOException if there is an exception connecting to or175* communicating with the OCSP responder176* @throws CertPathValidatorException if an exception occurs while177* encoding the OCSP Request or validating the OCSP Response178*/179static OCSPResponse check(List<CertId> certIds, URI responderURI,180OCSPResponse.IssuerInfo issuerInfo,181X509Certificate responderCert, Date date,182List<Extension> extensions, String variant)183throws IOException, CertPathValidatorException184{185byte[] nonce = null;186for (Extension ext : extensions) {187if (ext.getId().equals(PKIXExtensions.OCSPNonce_Id.toString())) {188nonce = ext.getValue();189}190}191192OCSPResponse ocspResponse = null;193try {194byte[] response = getOCSPBytes(certIds, responderURI, extensions);195ocspResponse = new OCSPResponse(response);196197// verify the response198ocspResponse.verify(certIds, issuerInfo, responderCert, date,199nonce, variant);200} catch (IOException ioe) {201throw new CertPathValidatorException(202"Unable to determine revocation status due to network error",203ioe, null, -1, BasicReason.UNDETERMINED_REVOCATION_STATUS);204}205206return ocspResponse;207}208209210/**211* Send an OCSP request, then read and return the OCSP response bytes.212*213* @param certIds the CertIds to be checked214* @param responderURI the URI of the OCSP responder215* @param extensions zero or more OCSP extensions to be included in the216* request. If no extensions are requested, an empty {@code List} must217* be used. A {@code null} value is not allowed.218*219* @return the OCSP response bytes220*221* @throws IOException if there is an exception connecting to or222* communicating with the OCSP responder223*/224public static byte[] getOCSPBytes(List<CertId> certIds, URI responderURI,225List<Extension> extensions) throws IOException {226OCSPRequest request = new OCSPRequest(certIds, extensions);227byte[] bytes = request.encodeBytes();228229if (debug != null) {230debug.println("connecting to OCSP service at: " + responderURI);231}232Event.report(Event.ReporterCategory.CRLCHECK, "event.ocsp.check",233responderURI.toString());234235URL url;236HttpURLConnection con = null;237try {238String encodedGetReq = responderURI.toString() + "/" +239URLEncoder.encode(Base64.getEncoder().encodeToString(bytes),240"UTF-8");241242if (encodedGetReq.length() <= 255) {243url = new URL(encodedGetReq);244con = (HttpURLConnection)url.openConnection();245con.setDoOutput(true);246con.setDoInput(true);247con.setRequestMethod("GET");248} else {249url = responderURI.toURL();250con = (HttpURLConnection)url.openConnection();251con.setConnectTimeout(CONNECT_TIMEOUT);252con.setReadTimeout(CONNECT_TIMEOUT);253con.setDoOutput(true);254con.setDoInput(true);255con.setRequestMethod("POST");256con.setRequestProperty257("Content-type", "application/ocsp-request");258con.setRequestProperty259("Content-length", String.valueOf(bytes.length));260OutputStream out = con.getOutputStream();261out.write(bytes);262out.flush();263}264265// Check the response266if (debug != null &&267con.getResponseCode() != HttpURLConnection.HTTP_OK) {268debug.println("Received HTTP error: " + con.getResponseCode()269+ " - " + con.getResponseMessage());270}271272int contentLength = con.getContentLength();273if (contentLength == -1) {274contentLength = Integer.MAX_VALUE;275}276277return IOUtils.readExactlyNBytes(con.getInputStream(),278contentLength);279} finally {280if (con != null) {281con.disconnect();282}283}284}285286/**287* Returns the URI of the OCSP Responder as specified in the288* certificate's Authority Information Access extension, or null if289* not specified.290*291* @param cert the certificate292* @return the URI of the OCSP Responder, or null if not specified293*/294// Called by com.sun.deploy.security.TrustDecider295public static URI getResponderURI(X509Certificate cert) {296try {297return getResponderURI(X509CertImpl.toImpl(cert));298} catch (CertificateException ce) {299// treat this case as if the cert had no extension300return null;301}302}303304static URI getResponderURI(X509CertImpl certImpl) {305306// Examine the certificate's AuthorityInfoAccess extension307AuthorityInfoAccessExtension aia =308certImpl.getAuthorityInfoAccessExtension();309if (aia == null) {310return null;311}312313List<AccessDescription> descriptions = aia.getAccessDescriptions();314for (AccessDescription description : descriptions) {315if (description.getAccessMethod().equals(316AccessDescription.Ad_OCSP_Id)) {317318GeneralName generalName = description.getAccessLocation();319if (generalName.getType() == GeneralNameInterface.NAME_URI) {320URIName uri = (URIName) generalName.getName();321return uri.getURI();322}323}324}325return null;326}327328/**329* The Revocation Status of a certificate.330*/331public static interface RevocationStatus {332public enum CertStatus { GOOD, REVOKED, UNKNOWN };333334/**335* Returns the revocation status.336*/337CertStatus getCertStatus();338/**339* Returns the time when the certificate was revoked, or null340* if it has not been revoked.341*/342Date getRevocationTime();343/**344* Returns the reason the certificate was revoked, or null if it345* has not been revoked.346*/347CRLReason getRevocationReason();348349/**350* Returns a Map of additional extensions.351*/352Map<String, Extension> getSingleExtensions();353}354}355356357