提交 adaaa91b 编写于 作者: M mullan

6745437: Add option to only check revocation of end-entity certificate in a chain of certificates

6869739: Cannot check revocation of single certificate without validating the entire chain
Reviewed-by: xuelei
上级 4412c101
/*
* Copyright 2009 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.action;
import java.security.Security;
/**
* A convenience class for retrieving the boolean value of a security property
* as a privileged action.
*
* <p>An instance of this class can be used as the argument of
* <code>AccessController.doPrivileged</code>.
*
* <p>The following code retrieves the boolean value of the security
* property named <code>"prop"</code> as a privileged action: <p>
*
* <pre>
* boolean b = java.security.AccessController.doPrivileged
* (new GetBooleanSecurityPropertyAction("prop")).booleanValue();
* </pre>
*
*/
public class GetBooleanSecurityPropertyAction
implements java.security.PrivilegedAction<Boolean> {
private String theProp;
/**
* Constructor that takes the name of the security property whose boolean
* value needs to be determined.
*
* @param theProp the name of the security property
*/
public GetBooleanSecurityPropertyAction(String theProp) {
this.theProp = theProp;
}
/**
* Determines the boolean value of the security property whose name was
* specified in the constructor.
*
* @return the <code>Boolean</code> value of the security property.
*/
public Boolean run() {
boolean b = false;
try {
String value = Security.getProperty(theProp);
b = (value != null) && value.equalsIgnoreCase("true");
} catch (NullPointerException e) {}
return b;
}
}
/*
* Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved.
* Copyright 2000-2009 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
......@@ -26,12 +26,14 @@
package sun.security.provider.certpath;
import java.io.IOException;
import java.security.AccessController;
import java.security.GeneralSecurityException;
import java.security.cert.*;
import java.util.*;
import javax.security.auth.x500.X500Principal;
import sun.security.action.GetBooleanAction;
import sun.security.util.Debug;
import sun.security.x509.GeneralNames;
import sun.security.x509.GeneralNameInterface;
......@@ -64,9 +66,8 @@ public abstract class Builder {
* Authority Information Access extension shall be enabled. Currently
* disabled by default for compatibility reasons.
*/
final static boolean USE_AIA =
DistributionPointFetcher.getBooleanProperty
("com.sun.security.enableAIAcaIssuers", false);
final static boolean USE_AIA = AccessController.doPrivileged
(new GetBooleanAction("com.sun.security.enableAIAcaIssuers"));
/**
* Initialize the builder with the input parameters.
......
/*
* Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
* Copyright 2003-2009 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
......@@ -25,9 +25,11 @@
package sun.security.provider.certpath;
import java.io.*;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import sun.misc.HexDumpEncoder;
import sun.security.x509.*;
......@@ -54,21 +56,28 @@ import sun.security.util.*;
public class CertId {
private static final boolean debug = false;
private AlgorithmId hashAlgId;
private byte[] issuerNameHash;
private byte[] issuerKeyHash;
private SerialNumber certSerialNumber;
private static final AlgorithmId SHA1_ALGID
= new AlgorithmId(AlgorithmId.SHA_oid);
private final AlgorithmId hashAlgId;
private final byte[] issuerNameHash;
private final byte[] issuerKeyHash;
private final SerialNumber certSerialNumber;
private int myhash = -1; // hashcode for this CertId
/**
* Creates a CertId. The hash algorithm used is SHA-1.
*/
public CertId(X509CertImpl issuerCert, SerialNumber serialNumber)
throws Exception {
public CertId(X509Certificate issuerCert, SerialNumber serialNumber)
throws IOException {
// compute issuerNameHash
MessageDigest md = MessageDigest.getInstance("SHA1");
hashAlgId = AlgorithmId.get("SHA1");
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA1");
} catch (NoSuchAlgorithmException nsae) {
throw new IOException("Unable to create CertId", nsae);
}
hashAlgId = SHA1_ALGID;
md.update(issuerCert.getSubjectX500Principal().getEncoded());
issuerNameHash = md.digest();
......@@ -90,6 +99,7 @@ public class CertId {
encoder.encode(issuerNameHash));
System.out.println("issuerKeyHash is " +
encoder.encode(issuerKeyHash));
System.out.println("SerialNumber is " + serialNumber.getNumber());
}
}
......@@ -97,7 +107,6 @@ public class CertId {
* Creates a CertId from its ASN.1 DER encoding.
*/
public CertId(DerInputStream derIn) throws IOException {
hashAlgId = AlgorithmId.parse(derIn.getDerValue());
issuerNameHash = derIn.getOctetString();
issuerKeyHash = derIn.getOctetString();
......@@ -157,7 +166,7 @@ public class CertId {
*
* @return the hashcode value.
*/
public int hashCode() {
@Override public int hashCode() {
if (myhash == -1) {
myhash = hashAlgId.hashCode();
for (int i = 0; i < issuerNameHash.length; i++) {
......@@ -180,8 +189,7 @@ public class CertId {
* @param other the object to test for equality with this object.
* @return true if the objects are considered equal, false otherwise.
*/
public boolean equals(Object other) {
@Override public boolean equals(Object other) {
if (this == other) {
return true;
}
......@@ -203,7 +211,7 @@ public class CertId {
/**
* Create a string representation of the CertId.
*/
public String toString() {
@Override public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("CertId \n");
sb.append("Algorithm: " + hashAlgId.toString() +"\n");
......
......@@ -80,6 +80,7 @@ class CrlRevocationChecker extends PKIXCertPathChecker {
{ false, false, false, false, false, false, true };
private static final boolean[] ALL_REASONS =
{true, true, true, true, true, true, true, true, true};
private boolean mOnlyEECert = false;
// Maximum clock skew in milliseconds (15 minutes) allowed when checking
// validity of CRLs
......@@ -114,6 +115,12 @@ class CrlRevocationChecker extends PKIXCertPathChecker {
CrlRevocationChecker(TrustAnchor anchor, PKIXParameters params,
Collection<X509Certificate> certs) throws CertPathValidatorException
{
this(anchor, params, certs, false);
}
CrlRevocationChecker(TrustAnchor anchor, PKIXParameters params,
Collection<X509Certificate> certs, boolean onlyEECert)
throws CertPathValidatorException {
mAnchor = anchor;
mParams = params;
mStores = new ArrayList<CertStore>(params.getCertStores());
......@@ -133,6 +140,7 @@ class CrlRevocationChecker extends PKIXCertPathChecker {
}
Date testDate = params.getDate();
mCurrentTime = (testDate != null ? testDate : new Date());
mOnlyEECert = onlyEECert;
init(false);
}
......@@ -264,6 +272,13 @@ class CrlRevocationChecker extends PKIXCertPathChecker {
" ---checking " + msg + "...");
}
if (mOnlyEECert && currCert.getBasicConstraints() != -1) {
if (debug != null) {
debug.println("Skipping revocation check, not end entity cert");
}
return;
}
// reject circular dependencies - RFC 3280 is not explicit on how
// to handle this, so we feel it is safest to reject them until
// the issue is resolved in the PKIX WG.
......
......@@ -32,7 +32,7 @@ import java.security.*;
import java.security.cert.*;
import javax.security.auth.x500.X500Principal;
import sun.security.action.GetPropertyAction;
import sun.security.action.GetBooleanAction;
import sun.security.util.Debug;
import sun.security.util.DerOutputStream;
import sun.security.x509.*;
......@@ -62,28 +62,8 @@ class DistributionPointFetcher {
* extension shall be enabled. Currently disabled by default for
* compatibility and legal reasons.
*/
private final static boolean USE_CRLDP =
getBooleanProperty("com.sun.security.enableCRLDP", false);
/**
* Return the value of the boolean System property propName.
*/
public static boolean getBooleanProperty(String propName,
boolean defaultValue) {
// if set, require value of either true or false
String b = AccessController.doPrivileged(
new GetPropertyAction(propName));
if (b == null) {
return defaultValue;
} else if (b.equalsIgnoreCase("false")) {
return false;
} else if (b.equalsIgnoreCase("true")) {
return true;
} else {
throw new RuntimeException("Value of " + propName
+ " must either be 'true' or 'false'");
}
}
private final static boolean USE_CRLDP = AccessController.doPrivileged
(new GetBooleanAction("com.sun.security.enableCRLDP"));
// singleton instance
private static final DistributionPointFetcher INSTANCE =
......
......@@ -82,6 +82,7 @@ class ForwardBuilder extends Builder {
TrustAnchor trustAnchor;
private Comparator<X509Certificate> comparator;
private boolean searchAllCertStores = true;
private boolean onlyEECert = false;
/**
* Initialize the builder with the input parameters.
......@@ -89,7 +90,8 @@ class ForwardBuilder extends Builder {
* @param params the parameter set used to build a certification path
*/
ForwardBuilder(PKIXBuilderParameters buildParams,
X500Principal targetSubjectDN, boolean searchAllCertStores)
X500Principal targetSubjectDN, boolean searchAllCertStores,
boolean onlyEECert)
{
super(buildParams, targetSubjectDN);
......@@ -108,6 +110,7 @@ class ForwardBuilder extends Builder {
}
comparator = new PKIXCertComparator(trustedSubjectDNs);
this.searchAllCertStores = searchAllCertStores;
this.onlyEECert = onlyEECert;
}
/**
......@@ -875,8 +878,8 @@ class ForwardBuilder extends Builder {
/* Check revocation if it is enabled */
if (buildParams.isRevocationEnabled()) {
try {
CrlRevocationChecker crlChecker =
new CrlRevocationChecker(anchor, buildParams);
CrlRevocationChecker crlChecker = new CrlRevocationChecker
(anchor, buildParams, null, onlyEECert);
crlChecker.check(cert, anchor.getCAPublicKey(), true);
} catch (CertPathValidatorException cpve) {
if (debug != null) {
......
/*
* Copyright 2009 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.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.net.HttpURLConnection;
import java.security.cert.CertificateException;
import java.security.cert.CertPathValidatorException;
import java.security.cert.CRLReason;
import java.security.cert.Extension;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static sun.security.provider.certpath.OCSPResponse.*;
import sun.security.util.Debug;
import sun.security.x509.AccessDescription;
import sun.security.x509.AuthorityInfoAccessExtension;
import sun.security.x509.GeneralName;
import sun.security.x509.GeneralNameInterface;
import sun.security.x509.URIName;
import sun.security.x509.X509CertImpl;
/**
* This is a class that checks the revocation status of a certificate(s) using
* OCSP. It is not a PKIXCertPathChecker and therefore can be used outside of
* the CertPathValidator framework. It is useful when you want to
* just check the revocation status of a certificate, and you don't want to
* incur the overhead of validating all of the certificates in the
* associated certificate chain.
*
* @author Sean Mullan
*/
public final class OCSP {
private static final Debug debug = Debug.getInstance("certpath");
private OCSP() {}
/**
* Obtains the revocation status of a certificate using OCSP using the most
* common defaults. The OCSP responder URI is retrieved from the
* certificate's AIA extension. The OCSP responder certificate is assumed
* to be the issuer's certificate (or issued by the issuer CA).
*
* @param cert the certificate to be checked
* @param issuerCert the issuer certificate
* @return the RevocationStatus
* @throws IOException if there is an exception connecting to or
* communicating with the OCSP responder
* @throws CertPathValidatorException if an exception occurs while
* encoding the OCSP Request or validating the OCSP Response
*/
public static RevocationStatus check(X509Certificate cert,
X509Certificate issuerCert)
throws IOException, CertPathValidatorException {
CertId certId = null;
URI responderURI = null;
try {
X509CertImpl certImpl = X509CertImpl.toImpl(cert);
responderURI = getResponderURI(certImpl);
if (responderURI == null) {
throw new CertPathValidatorException
("No OCSP Responder URI in certificate");
}
certId = new CertId(issuerCert, certImpl.getSerialNumberObject());
} catch (CertificateException ce) {
throw new CertPathValidatorException
("Exception while encoding OCSPRequest", ce);
} catch (IOException ioe) {
throw new CertPathValidatorException
("Exception while encoding OCSPRequest", ioe);
}
OCSPResponse ocspResponse = check(Collections.singletonList(certId),
responderURI, issuerCert, null);
return (RevocationStatus) ocspResponse.getSingleResponse(certId);
}
/**
* Obtains the revocation status of a certificate using OCSP.
*
* @param cert the certificate to be checked
* @param issuerCert the issuer certificate
* @param responderURI the URI of the OCSP responder
* @param responderCert the OCSP responder's certificate
* @param date the time the validity of the OCSP responder's certificate
* should be checked against. If null, the current time is used.
* @return the RevocationStatus
* @throws IOException if there is an exception connecting to or
* communicating with the OCSP responder
* @throws CertPathValidatorException if an exception occurs while
* encoding the OCSP Request or validating the OCSP Response
*/
public static RevocationStatus check(X509Certificate cert,
X509Certificate issuerCert, URI responderURI, X509Certificate
responderCert, Date date)
throws IOException, CertPathValidatorException {
CertId certId = null;
try {
X509CertImpl certImpl = X509CertImpl.toImpl(cert);
certId = new CertId(issuerCert, certImpl.getSerialNumberObject());
} catch (CertificateException ce) {
throw new CertPathValidatorException
("Exception while encoding OCSPRequest", ce);
} catch (IOException ioe) {
throw new CertPathValidatorException
("Exception while encoding OCSPRequest", ioe);
}
OCSPResponse ocspResponse = check(Collections.singletonList(certId),
responderURI, responderCert, date);
return (RevocationStatus) ocspResponse.getSingleResponse(certId);
}
/**
* Checks the revocation status of a list of certificates using OCSP.
*
* @param certs the CertIds to be checked
* @param responderURI the URI of the OCSP responder
* @param responderCert the OCSP responder's certificate
* @param date the time the validity of the OCSP responder's certificate
* should be checked against. If null, the current time is used.
* @return the OCSPResponse
* @throws IOException if there is an exception connecting to or
* communicating with the OCSP responder
* @throws CertPathValidatorException if an exception occurs while
* encoding the OCSP Request or validating the OCSP Response
*/
static OCSPResponse check(List<CertId> certIds, URI responderURI,
X509Certificate responderCert, Date date)
throws IOException, CertPathValidatorException {
byte[] bytes = null;
try {
OCSPRequest request = new OCSPRequest(certIds);
bytes = request.encodeBytes();
} catch (IOException ioe) {
throw new CertPathValidatorException
("Exception while encoding OCSPRequest", ioe);
}
InputStream in = null;
OutputStream out = null;
byte[] response = null;
try {
URL url = responderURI.toURL();
if (debug != null) {
debug.println("connecting to OCSP service at: " + url);
}
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty
("Content-type", "application/ocsp-request");
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;
}
response = new byte[contentLength > 2048 ? 2048 : contentLength];
int total = 0;
while (total < contentLength) {
int count = in.read(response, total, response.length - total);
if (count < 0)
break;
total += count;
if (total >= response.length && total < contentLength) {
response = Arrays.copyOf(response, total * 2);
}
}
response = Arrays.copyOf(response, total);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ioe) {
throw ioe;
}
}
if (out != null) {
try {
out.close();
} catch (IOException ioe) {
throw ioe;
}
}
}
OCSPResponse ocspResponse = null;
try {
ocspResponse = new OCSPResponse(response, date, responderCert);
} catch (IOException ioe) {
// response decoding exception
throw new CertPathValidatorException(ioe);
}
if (ocspResponse.getResponseStatus() != ResponseStatus.SUCCESSFUL) {
throw new CertPathValidatorException
("OCSP response error: " + ocspResponse.getResponseStatus());
}
// Check that the response includes a response for all of the
// certs that were supplied in the request
for (CertId certId : certIds) {
SingleResponse sr = ocspResponse.getSingleResponse(certId);
if (sr == null) {
if (debug != null) {
debug.println("No response found for CertId: " + certId);
}
throw new CertPathValidatorException(
"OCSP response does not include a response for a " +
"certificate supplied in the OCSP request");
}
if (debug != null) {
debug.println("Status of certificate (with serial number " +
certId.getSerialNumber() + ") is: " + sr.getCertStatus());
}
}
return ocspResponse;
}
/**
* Returns the URI of the OCSP Responder as specified in the
* certificate's Authority Information Access extension, or null if
* not specified.
*
* @param cert the certificate
* @return the URI of the OCSP Responder, or null if not specified
*/
public static URI getResponderURI(X509Certificate cert) {
try {
return getResponderURI(X509CertImpl.toImpl(cert));
} catch (CertificateException ce) {
// treat this case as if the cert had no extension
return null;
}
}
static URI getResponderURI(X509CertImpl certImpl) {
// Examine the certificate's AuthorityInfoAccess extension
AuthorityInfoAccessExtension aia =
certImpl.getAuthorityInfoAccessExtension();
if (aia == null) {
return null;
}
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) {
URIName uri = (URIName) generalName.getName();
return uri.getURI();
}
}
}
return null;
}
/**
* The Revocation Status of a certificate.
*/
public static interface RevocationStatus {
public enum CertStatus { GOOD, REVOKED, UNKNOWN };
/**
* Returns the revocation status.
*/
CertStatus getCertStatus();
/**
* Returns the time when the certificate was revoked, or null
* if it has not been revoked.
*/
Date getRevocationTime();
/**
* Returns the reason the certificate was revoked, or null if it
* has not been revoked.
*/
CRLReason getRevocationReason();
/**
* Returns a Map of additional extensions.
*/
Map<String, Extension> getSingleExtensions();
}
}
......@@ -25,19 +25,20 @@
package sun.security.provider.certpath;
import java.io.*;
import java.io.IOException;
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 java.net.URI;
import java.net.URISyntaxException;
import javax.security.auth.x500.X500Principal;
import sun.security.util.*;
import static sun.security.provider.certpath.OCSP.*;
import sun.security.util.Debug;
import sun.security.x509.*;
/**
......@@ -50,27 +51,18 @@ import sun.security.x509.*;
*/
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 =
static final String OCSP_ENABLE_PROP = "ocsp.enable";
static final String OCSP_URL_PROP = "ocsp.responderURL";
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 =
static final String OCSP_CERT_ISSUER_PROP = "ocsp.responderCertIssuerName";
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;
......@@ -79,19 +71,26 @@ class OCSPChecker extends PKIXCertPathChecker {
private PKIXParameters pkixParams;
private boolean onlyEECert = false;
/**
* 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.
* @throws CertPathValidatorException if OCSPChecker can not be created
*/
OCSPChecker(CertPath certPath, PKIXParameters pkixParams)
throws CertPathValidatorException {
this(certPath, pkixParams, false);
}
OCSPChecker(CertPath certPath, PKIXParameters pkixParams, boolean onlyEECert)
throws CertPathValidatorException {
this.cp = certPath;
this.pkixParams = pkixParams;
this.onlyEECert = onlyEECert;
List<? extends Certificate> tmp = cp.getCertificates();
certs = tmp.toArray(new X509Certificate[tmp.size()]);
init(false);
......@@ -101,6 +100,7 @@ class OCSPChecker extends PKIXCertPathChecker {
* Initializes the internal state of the checker from parameters
* specified in the constructor
*/
@Override
public void init(boolean forward) throws CertPathValidatorException {
if (!forward) {
remainingCerts = certs.length + 1;
......@@ -110,11 +110,11 @@ class OCSPChecker extends PKIXCertPathChecker {
}
}
public boolean isForwardCheckingSupported() {
@Override public boolean isForwardCheckingSupported() {
return false;
}
public Set<String> getSupportedExtensions() {
@Override public Set<String> getSupportedExtensions() {
return Collections.<String>emptySet();
}
......@@ -127,26 +127,26 @@ class OCSPChecker extends PKIXCertPathChecker {
* @exception CertPathValidatorException Exception is thrown if the
* certificate has been revoked.
*/
@Override
public void check(Certificate cert, Collection<String> unresolvedCritExts)
throws CertPathValidatorException {
InputStream in = null;
OutputStream out = null;
// Decrement the certificate counter
remainingCerts--;
X509CertImpl currCertImpl = null;
try {
X509Certificate responderCert = null;
boolean seekResponderCert = false;
X500Principal responderSubjectName = null;
X500Principal responderIssuerName = null;
BigInteger responderSerialNumber = null;
currCertImpl = X509CertImpl.toImpl((X509Certificate)cert);
} catch (CertificateException ce) {
throw new CertPathValidatorException(ce);
}
boolean seekIssuerCert = true;
X509CertImpl issuerCertImpl = null;
X509CertImpl currCertImpl =
X509CertImpl.toImpl((X509Certificate)cert);
if (onlyEECert && currCertImpl.getBasicConstraints() != -1) {
if (DEBUG != null) {
DEBUG.println("Skipping revocation check, not end entity cert");
}
return;
}
/*
* OCSP security property values, in the following order:
......@@ -155,22 +155,24 @@ class OCSPChecker extends PKIXCertPathChecker {
* 3. ocsp.responderCertIssuerName
* 4. ocsp.responderCertSerialNumber
*/
// should cache these properties to avoid calling every time?
String[] properties = getOCSPProperties();
// Check whether OCSP is feasible before seeking cert information
URL url = getOCSPServerURL(currCertImpl, properties);
URI uri = getOCSPServerURI(currCertImpl, properties[0]);
// When responder's subject name is set then the issuer/serial
// properties are ignored
X500Principal responderSubjectName = null;
X500Principal responderIssuerName = null;
BigInteger responderSerialNumber = null;
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 " +
......@@ -180,20 +182,24 @@ class OCSPChecker extends PKIXCertPathChecker {
// If the OCSP responder cert properties are set then the
// identified cert must be located in the trust anchors or
// in the cert stores.
boolean seekResponderCert = false;
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).
X509Certificate issuerCert = null;
boolean seekIssuerCert = true;
X509Certificate responderCert = null;
if (remainingCerts < certs.length) {
issuerCertImpl = X509CertImpl.toImpl(certs[remainingCerts]);
issuerCert = 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 (!seekResponderCert) {
responderCert = issuerCert;
if (DEBUG != null) {
DEBUG.println("Responder's certificate is the same " +
"as the issuer of the certificate being validated");
......@@ -212,38 +218,37 @@ class OCSPChecker extends PKIXCertPathChecker {
}
// Extract the anchor certs
Iterator anchors = pkixParams.getTrustAnchors().iterator();
if (! anchors.hasNext()) {
Iterator<TrustAnchor> 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)) {
while (anchors.hasNext() && (seekIssuerCert || seekResponderCert)) {
TrustAnchor anchor = (TrustAnchor)anchors.next();
TrustAnchor anchor = 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);
System.out.println("Subject DN is " + anchorSubjectName);
}
// Check if anchor cert is the issuer cert
if (seekIssuerCert &&
certIssuerName.equals(anchorSubjectName)) {
issuerCertImpl = X509CertImpl.toImpl(anchorCert);
issuerCert = 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) {
if (!seekResponderCert && responderCert == null) {
responderCert = anchorCert;
if (DEBUG != null) {
DEBUG.println("Responder's certificate is the" +
......@@ -272,10 +277,9 @@ class OCSPChecker extends PKIXCertPathChecker {
}
}
}
if (issuerCertImpl == null) {
if (issuerCert == null) {
throw new CertPathValidatorException(
"No trusted certificate for " +
currCertImpl.getIssuerDN());
"No trusted certificate for " + currCertImpl.getIssuerDN());
}
// Check cert stores if responder cert has not yet been found
......@@ -287,18 +291,26 @@ class OCSPChecker extends PKIXCertPathChecker {
X509CertSelector filter = null;
if (responderSubjectName != null) {
filter = new X509CertSelector();
filter.setSubject(responderSubjectName.getName());
filter.setSubject(responderSubjectName);
} else if (responderIssuerName != null &&
responderSerialNumber != null) {
filter = new X509CertSelector();
filter.setIssuer(responderIssuerName.getName());
filter.setIssuer(responderIssuerName);
filter.setSerialNumber(responderSerialNumber);
}
if (filter != null) {
List<CertStore> certStores = pkixParams.getCertStores();
for (CertStore certStore : certStores) {
Iterator i =
certStore.getCertificates(filter).iterator();
Iterator i = null;
try {
i = certStore.getCertificates(filter).iterator();
} catch (CertStoreException cse) {
// ignore and try next certStore
if (DEBUG != null) {
DEBUG.println("CertStore exception:" + cse);
}
continue;
}
if (i.hasNext()) {
responderCert = (X509Certificate) i.next();
seekResponderCert = false; // done
......@@ -316,112 +328,33 @@ class OCSPChecker extends PKIXCertPathChecker {
"(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();
byte[] response = null;
int total = 0;
int contentLength = con.getContentLength();
if (contentLength != -1) {
response = new byte[contentLength];
} else {
response = new byte[2048];
contentLength = Integer.MAX_VALUE;
}
while (total < contentLength) {
int count = in.read(response, total, response.length - total);
if (count < 0)
break;
total += count;
if (total >= response.length && total < contentLength) {
response = Arrays.copyOf(response, total * 2);
}
}
response = Arrays.copyOf(response, total);
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));
CertId certId = null;
OCSPResponse response = null;
try {
certId = new CertId
(issuerCert, currCertImpl.getSerialNumberObject());
response = OCSP.check(Collections.singletonList(certId), uri,
responderCert, pkixParams.getDate());
} catch (IOException ioe) {
// should allow this to pass if network failures are acceptable
throw new CertPathValidatorException
("Unable to send OCSP request", ioe);
}
if (certOCSPStatus == OCSPResponse.CERT_STATUS_REVOKED) {
RevocationStatus rs = (RevocationStatus) response.getSingleResponse(certId);
RevocationStatus.CertStatus certStatus = rs.getCertStatus();
if (certStatus == RevocationStatus.CertStatus.REVOKED) {
Throwable t = new CertificateRevokedException(
ocspResponse.getRevocationTime(),
ocspResponse.getRevocationReason(),
rs.getRevocationTime(), rs.getRevocationReason(),
responderCert.getSubjectX500Principal(),
ocspResponse.getSingleExtensions());
rs.getSingleExtensions());
throw new CertPathValidatorException(t.getMessage(), t,
null, -1, BasicReason.REVOKED);
} else if (certOCSPStatus == OCSPResponse.CERT_STATUS_UNKNOWN) {
} else if (certStatus == RevocationStatus.CertStatus.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);
}
}
}
}
/*
......@@ -431,20 +364,18 @@ class OCSPChecker extends PKIXCertPathChecker {
* 3. ocsp.responderCertIssuerName
* 4. ocsp.responderCertSerialNumber
*/
private static URL getOCSPServerURL(X509CertImpl currCertImpl,
String[] properties)
throws CertificateParsingException, CertPathValidatorException {
private static URI getOCSPServerURI(X509CertImpl currCertImpl,
String responderURL) throws CertPathValidatorException {
if (properties[0] != null) {
if (responderURL != null) {
try {
return new URL(properties[0]);
} catch (java.net.MalformedURLException e) {
return new URI(responderURL);
} catch (URISyntaxException e) {
throw new CertPathValidatorException(e);
}
}
// Examine the certificate's AuthorityInfoAccess extension
AuthorityInfoAccessExtension aia =
currCertImpl.getAuthorityInfoAccessExtension();
if (aia == null) {
......@@ -459,13 +390,8 @@ class OCSPChecker extends PKIXCertPathChecker {
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);
}
return uri.getURI();
}
}
}
......
/*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
* Copyright 2003-2009 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
......@@ -26,9 +26,9 @@
package sun.security.provider.certpath;
import java.io.IOException;
import java.security.cert.CertPathValidatorException;
import java.util.Collections;
import java.util.List;
import sun.misc.HexDumpEncoder;
import sun.security.x509.*;
import sun.security.util.*;
/**
......@@ -77,47 +77,33 @@ class OCSPRequest {
private static final Debug debug = Debug.getInstance("certpath");
private static final boolean dump = false;
// Serial number of the certificates to be checked for revocation
private SerialNumber serialNumber;
// Issuer's certificate (for computing certId hash values)
private X509CertImpl issuerCert;
// CertId of the certificate to be checked
private CertId certId = null;
// List of request CertIds
private final List<CertId> certIds;
/*
* Constructs an OCSPRequest. This constructor is used
* to construct an unsigned OCSP Request for a single user cert.
*/
// used by OCSPChecker
OCSPRequest(X509CertImpl userCert, X509CertImpl issuerCert)
throws CertPathValidatorException {
if (issuerCert == null) {
throw new CertPathValidatorException("Null IssuerCertificate");
OCSPRequest(CertId certId) {
this.certIds = Collections.singletonList(certId);
}
this.issuerCert = issuerCert;
serialNumber = userCert.getSerialNumberObject();
OCSPRequest(List<CertId> certIds) {
this.certIds = certIds;
}
// used by OCSPChecker
byte[] encodeBytes() throws IOException {
// encode tbsRequest
DerOutputStream tmp = new DerOutputStream();
DerOutputStream derSingleReqList = new DerOutputStream();
SingleRequest singleRequest = null;
try {
singleRequest = new SingleRequest(issuerCert, serialNumber);
} catch (Exception e) {
throw new IOException("Error encoding OCSP request");
DerOutputStream requestsOut = new DerOutputStream();
for (CertId certId : certIds) {
DerOutputStream certIdOut = new DerOutputStream();
certId.encode(certIdOut);
requestsOut.write(DerValue.tag_Sequence, certIdOut);
}
certId = singleRequest.getCertId();
singleRequest.encode(derSingleReqList);
tmp.write(DerValue.tag_Sequence, derSingleReqList);
tmp.write(DerValue.tag_Sequence, requestsOut);
// No extensions supported
DerOutputStream tbsRequest = new DerOutputStream();
tbsRequest.write(DerValue.tag_Sequence, tmp);
......@@ -130,35 +116,14 @@ class OCSPRequest {
if (dump) {
HexDumpEncoder hexEnc = new HexDumpEncoder();
System.out.println ("OCSPRequest bytes are... ");
System.out.println("OCSPRequest bytes are... ");
System.out.println(hexEnc.encode(bytes));
}
return(bytes);
}
// used by OCSPChecker
CertId getCertId() {
return certId;
return bytes;
}
private static class SingleRequest {
private CertId certId;
// No extensions are set
private SingleRequest(X509CertImpl cert, SerialNumber serialNo) throws Exception {
certId = new CertId(cert, serialNo);
}
private void encode(DerOutputStream out) throws IOException {
DerOutputStream tmp = new DerOutputStream();
certId.encode(tmp);
out.write(DerValue.tag_Sequence, tmp);
}
private CertId getCertId() {
return certId;
}
List<CertId> getCertIds() {
return certIds;
}
}
/*
* Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved.
* Copyright 2000-2009 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
......@@ -28,8 +28,6 @@ package sun.security.provider.certpath;
import java.io.IOException;
import java.security.AccessController;
import java.security.InvalidAlgorithmParameterException;
import java.security.PrivilegedAction;
import java.security.Security;
import java.security.cert.CertPath;
import java.security.cert.CertPathParameters;
import java.security.cert.CertPathValidatorException;
......@@ -49,6 +47,7 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.Set;
import javax.security.auth.x500.X500Principal;
import sun.security.action.GetBooleanSecurityPropertyAction;
import sun.security.util.Debug;
/**
......@@ -67,7 +66,8 @@ public class PKIXCertPathValidator extends CertPathValidatorSpi {
private List<PKIXCertPathChecker> userCheckers;
private String sigProvider;
private BasicChecker basicChecker;
private String ocspProperty;
private boolean ocspEnabled = false;
private boolean onlyEECert = false;
/**
* Default constructor.
......@@ -253,13 +253,12 @@ public class PKIXCertPathValidator extends CertPathValidatorSpi {
if (pkixParam.isRevocationEnabled()) {
// Examine OCSP security property
ocspProperty = AccessController.doPrivileged(
new PrivilegedAction<String>() {
public String run() {
return
Security.getProperty(OCSPChecker.OCSP_ENABLE_PROP);
}
});
ocspEnabled = AccessController.doPrivileged(
new GetBooleanSecurityPropertyAction
(OCSPChecker.OCSP_ENABLE_PROP));
onlyEECert = AccessController.doPrivileged(
new GetBooleanSecurityPropertyAction
("com.sun.security.onlyCheckRevocationOfEECert"));
}
}
......@@ -301,15 +300,15 @@ public class PKIXCertPathValidator extends CertPathValidatorSpi {
if (pkixParam.isRevocationEnabled()) {
// Use OCSP if it has been enabled
if ("true".equalsIgnoreCase(ocspProperty)) {
if (ocspEnabled) {
OCSPChecker ocspChecker =
new OCSPChecker(cpOriginal, pkixParam);
new OCSPChecker(cpOriginal, pkixParam, onlyEECert);
certPathCheckers.add(ocspChecker);
}
// Always use CRLs
CrlRevocationChecker revocationChecker =
new CrlRevocationChecker(anchor, pkixParam, certList);
CrlRevocationChecker revocationChecker = new
CrlRevocationChecker(anchor, pkixParam, certList, onlyEECert);
certPathCheckers.add(revocationChecker);
}
......
/*
* Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved.
* Copyright 2000-2009 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
......@@ -26,6 +26,7 @@
package sun.security.provider.certpath;
import java.io.IOException;
import java.security.AccessController;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.Principal;
......@@ -44,6 +45,7 @@ import java.util.LinkedList;
import java.util.Set;
import javax.security.auth.x500.X500Principal;
import sun.security.action.GetBooleanSecurityPropertyAction;
import sun.security.x509.X500Name;
import sun.security.x509.PKIXExtensions;
import sun.security.util.Debug;
......@@ -85,6 +87,7 @@ public final class SunCertPathBuilder extends CertPathBuilderSpi {
private PublicKey finalPublicKey;
private X509CertSelector targetSel;
private List<CertStore> orderedCertStores;
private boolean onlyEECert = false;
/**
* Create an instance of <code>SunCertPathBuilder</code>.
......@@ -97,6 +100,9 @@ public final class SunCertPathBuilder extends CertPathBuilderSpi {
} catch (CertificateException e) {
throw new CertPathBuilderException(e);
}
onlyEECert = AccessController.doPrivileged(
new GetBooleanSecurityPropertyAction
("com.sun.security.onlyCheckRevocationOfEECert"));
}
/**
......@@ -256,7 +262,6 @@ public final class SunCertPathBuilder extends CertPathBuilderSpi {
/*
* Private build reverse method.
*
*/
private void buildReverse(List<List<Vertex>> adjacencyList,
LinkedList<X509Certificate> certPathList) throws Exception
......@@ -296,7 +301,7 @@ public final class SunCertPathBuilder extends CertPathBuilderSpi {
currentState.updateState(anchor);
// init the crl checker
currentState.crlChecker =
new CrlRevocationChecker(null, buildParams);
new CrlRevocationChecker(null, buildParams, null, onlyEECert);
try {
depthFirstSearchReverse(null, currentState,
new ReverseBuilder(buildParams, targetSubjectDN), adjacencyList,
......@@ -341,10 +346,12 @@ public final class SunCertPathBuilder extends CertPathBuilderSpi {
adjacencyList.add(new LinkedList<Vertex>());
// init the crl checker
currentState.crlChecker = new CrlRevocationChecker(null, buildParams);
currentState.crlChecker
= new CrlRevocationChecker(null, buildParams, null, onlyEECert);
depthFirstSearchForward(targetSubjectDN, currentState,
new ForwardBuilder(buildParams, targetSubjectDN, searchAllCertStores),
new ForwardBuilder
(buildParams, targetSubjectDN, searchAllCertStores, onlyEECert),
adjacencyList, certPathList);
}
......@@ -486,8 +493,8 @@ public final class SunCertPathBuilder extends CertPathBuilderSpi {
userCheckers.add(mustCheck, basicChecker);
mustCheck++;
if (buildParams.isRevocationEnabled()) {
userCheckers.add(mustCheck,
new CrlRevocationChecker(anchor, buildParams));
userCheckers.add(mustCheck, new CrlRevocationChecker
(anchor, buildParams, null, onlyEECert));
mustCheck++;
}
}
......
......@@ -113,7 +113,7 @@ public final class AccessDescription {
} else {
method = accessMethod.toString();
}
return ("accessMethod: " + method +
return ("\n accessMethod: " + method +
"\n accessLocation: " + accessLocation.toString() + "\n");
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册