use of java.security.cert.CertPathValidatorException in project Openfire by igniterealtime.
the class CertificateManager method getEndEntityCertificate.
/**
* Decide whether or not to trust the given supplied certificate chain, returning the
* End Entity Certificate in this case where it can, and null otherwise.
* A self-signed certificate will, for example, return null.
* For certain failures, we SHOULD generate an exception - revocations and the like,
* but we currently do not.
*
* @param chain an array of X509Certificate where the first one is the endEntityCertificate.
* @param certStore a keystore containing untrusted certificates (including ICAs, etc).
* @param trustStore a keystore containing Trust Anchors (most-trusted CA certificates).
* @return trusted end-entity certificate, or null.
*/
public static X509Certificate getEndEntityCertificate(Certificate[] chain, KeyStore certStore, KeyStore trustStore) {
if (chain.length == 0) {
return null;
}
X509Certificate first = (X509Certificate) chain[0];
try {
first.checkValidity();
} catch (CertificateException e) {
Log.warn("EE Certificate not valid: " + e.getMessage());
return null;
}
if (chain.length == 1 && first.getSubjectX500Principal().equals(first.getIssuerX500Principal())) {
// Chain is single cert, and self-signed.
try {
if (trustStore.getCertificateAlias(first) != null) {
// Interesting case: trusted self-signed cert.
return first;
}
} catch (KeyStoreException e) {
Log.warn("Keystore error while looking for self-signed cert; assuming untrusted.");
}
return null;
}
final List<Certificate> all_certs = new ArrayList<>();
try {
// It's a mystery why these objects are different.
for (Enumeration<String> aliases = certStore.aliases(); aliases.hasMoreElements(); ) {
String alias = aliases.nextElement();
if (certStore.isCertificateEntry(alias)) {
X509Certificate cert = (X509Certificate) certStore.getCertificate(alias);
all_certs.add(cert);
}
}
// Now add the trusted certs.
for (Enumeration<String> aliases = trustStore.aliases(); aliases.hasMoreElements(); ) {
String alias = aliases.nextElement();
if (trustStore.isCertificateEntry(alias)) {
X509Certificate cert = (X509Certificate) trustStore.getCertificate(alias);
all_certs.add(cert);
}
}
// Finally, add all the certs in the chain:
for (int i = 0; i < chain.length; ++i) {
all_certs.add(chain[i]);
}
CertStore cs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(all_certs));
X509CertSelector selector = new X509CertSelector();
selector.setCertificate(first);
// / selector.setSubject(first.getSubjectX500Principal());
PKIXBuilderParameters params = new PKIXBuilderParameters(trustStore, selector);
params.addCertStore(cs);
params.setDate(new Date());
params.setRevocationEnabled(false);
/* Code here is the right way to do things. */
CertPathBuilder pathBuilder = CertPathBuilder.getInstance(CertPathBuilder.getDefaultType());
CertPath cp = pathBuilder.build(params).getCertPath();
/**
* This section is an alternative to using CertPathBuilder which is
* not as complete (or safe), but will emit much better errors. If
* things break, swap around the code.
*
**** COMMENTED OUT. ****
ArrayList<X509Certificate> ls = new ArrayList<X509Certificate>();
for (int i = 0; i < chain.length; ++i) {
ls.add((X509Certificate) chain[i]);
}
for (X509Certificate last = ls.get(ls.size() - 1); !last
.getIssuerX500Principal().equals(last.getSubjectX500Principal()); last = ls
.get(ls.size() - 1)) {
X509CertSelector sel = new X509CertSelector();
sel.setSubject(last.getIssuerX500Principal());
ls.add((X509Certificate) cs.getCertificates(sel).toArray()[0]);
}
CertPath cp = CertificateFactory.getInstance("X.509").generateCertPath(ls);
****** END ALTERNATIVE. ****
*/
// Not entirely sure if I need to do this with CertPathBuilder.
// Can't hurt.
CertPathValidator pathValidator = CertPathValidator.getInstance("PKIX");
pathValidator.validate(cp, params);
return (X509Certificate) cp.getCertificates().get(0);
} catch (CertPathBuilderException e) {
Log.warn("Path builder: " + e.getMessage());
} catch (CertPathValidatorException e) {
Log.warn("Path validator: " + e.getMessage());
} catch (Exception e) {
Log.warn("Unkown exception while validating certificate chain: " + e.getMessage());
}
return null;
}
use of java.security.cert.CertPathValidatorException in project XobotOS by xamarin.
the class RFC3280CertPathUtilities method processCRLF.
/**
* Obtain and validate the certification path for the complete CRL issuer.
* If a key usage extension is present in the CRL issuer's certificate,
* verify that the cRLSign bit is set.
*
* @param crl CRL which contains revocation information for the certificate
* <code>cert</code>.
* @param cert The attribute certificate or certificate to check if it is
* revoked.
* @param defaultCRLSignCert The issuer certificate of the certificate <code>cert</code>.
* @param defaultCRLSignKey The public key of the issuer certificate
* <code>defaultCRLSignCert</code>.
* @param paramsPKIX paramsPKIX PKIX parameters.
* @param certPathCerts The certificates on the certification path.
* @return A <code>Set</code> with all keys of possible CRL issuer
* certificates.
* @throws AnnotatedException if the CRL is not valid or the status cannot be checked or
* some error occurs.
*/
protected static Set processCRLF(X509CRL crl, Object cert, X509Certificate defaultCRLSignCert, PublicKey defaultCRLSignKey, ExtendedPKIXParameters paramsPKIX, List certPathCerts) throws AnnotatedException {
// (f)
// get issuer from CRL
X509CertStoreSelector selector = new X509CertStoreSelector();
try {
byte[] issuerPrincipal = CertPathValidatorUtilities.getIssuerPrincipal(crl).getEncoded();
selector.setSubject(issuerPrincipal);
} catch (IOException e) {
throw new AnnotatedException("Subject criteria for certificate selector to find issuer certificate for CRL could not be set.", e);
}
// get CRL signing certs
Collection coll;
try {
coll = CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getStores());
coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getAdditionalStores()));
coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getCertStores()));
} catch (AnnotatedException e) {
throw new AnnotatedException("Issuer certificate for CRL cannot be searched.", e);
}
coll.add(defaultCRLSignCert);
Iterator cert_it = coll.iterator();
List validCerts = new ArrayList();
List validKeys = new ArrayList();
while (cert_it.hasNext()) {
X509Certificate signingCert = (X509Certificate) cert_it.next();
/*
* CA of the certificate, for which this CRL is checked, has also
* signed CRL, so skip the path validation, because is already done
*/
if (signingCert.equals(defaultCRLSignCert)) {
validCerts.add(signingCert);
validKeys.add(defaultCRLSignKey);
continue;
}
try {
CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);
selector = new X509CertStoreSelector();
selector.setCertificate(signingCert);
ExtendedPKIXParameters temp = (ExtendedPKIXParameters) paramsPKIX.clone();
temp.setTargetCertConstraints(selector);
ExtendedPKIXBuilderParameters params = (ExtendedPKIXBuilderParameters) ExtendedPKIXBuilderParameters.getInstance(temp);
/*
* if signingCert is placed not higher on the cert path a
* dependency loop results. CRL for cert is checked, but
* signingCert is needed for checking the CRL which is dependent
* on checking cert because it is higher in the cert path and so
* signing signingCert transitively. so, revocation is disabled,
* forgery attacks of the CRL are detected in this outer loop
* for all other it must be enabled to prevent forgery attacks
*/
if (certPathCerts.contains(signingCert)) {
params.setRevocationEnabled(false);
} else {
params.setRevocationEnabled(true);
}
List certs = builder.build(params).getCertPath().getCertificates();
validCerts.add(signingCert);
validKeys.add(CertPathValidatorUtilities.getNextWorkingKey(certs, 0));
} catch (CertPathBuilderException e) {
throw new AnnotatedException("Internal error.", e);
} catch (CertPathValidatorException e) {
throw new AnnotatedException("Public key of issuer certificate of CRL could not be retrieved.", e);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
Set checkKeys = new HashSet();
AnnotatedException lastException = null;
for (int i = 0; i < validCerts.size(); i++) {
X509Certificate signCert = (X509Certificate) validCerts.get(i);
boolean[] keyusage = signCert.getKeyUsage();
if (keyusage != null && (keyusage.length < 7 || !keyusage[CRL_SIGN])) {
lastException = new AnnotatedException("Issuer certificate key usage extension does not permit CRL signing.");
} else {
checkKeys.add(validKeys.get(i));
}
}
if (checkKeys.isEmpty() && lastException == null) {
throw new AnnotatedException("Cannot find a valid issuer certificate.");
}
if (checkKeys.isEmpty() && lastException != null) {
throw lastException;
}
return checkKeys;
}
use of java.security.cert.CertPathValidatorException in project XobotOS by xamarin.
the class RFC3280CertPathUtilities method wrapupCertF.
protected static void wrapupCertF(CertPath certPath, int index, List pathCheckers, Set criticalExtensions) throws CertPathValidatorException {
List certs = certPath.getCertificates();
X509Certificate cert = (X509Certificate) certs.get(index);
Iterator tmpIter;
tmpIter = pathCheckers.iterator();
while (tmpIter.hasNext()) {
try {
((PKIXCertPathChecker) tmpIter.next()).check(cert, criticalExtensions);
} catch (CertPathValidatorException e) {
throw new ExtCertPathValidatorException("Additional certificate path checker failed.", e, certPath, index);
}
}
if (!criticalExtensions.isEmpty()) {
throw new ExtCertPathValidatorException("Certificate has unsupported critical extension", null, certPath, index);
}
}
use of java.security.cert.CertPathValidatorException in project XobotOS by xamarin.
the class RFC3280CertPathUtilities method wrapupCertB.
protected static int wrapupCertB(CertPath certPath, int index, int explicitPolicy) throws CertPathValidatorException {
List certs = certPath.getCertificates();
X509Certificate cert = (X509Certificate) certs.get(index);
//
// (b)
//
int tmpInt;
ASN1Sequence pc = null;
try {
pc = DERSequence.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, RFC3280CertPathUtilities.POLICY_CONSTRAINTS));
} catch (AnnotatedException e) {
throw new ExtCertPathValidatorException("Policy constraints could not be decoded.", e, certPath, index);
}
if (pc != null) {
Enumeration policyConstraints = pc.getObjects();
while (policyConstraints.hasMoreElements()) {
ASN1TaggedObject constraint = (ASN1TaggedObject) policyConstraints.nextElement();
switch(constraint.getTagNo()) {
case 0:
try {
tmpInt = DERInteger.getInstance(constraint, false).getValue().intValue();
} catch (Exception e) {
throw new ExtCertPathValidatorException("Policy constraints requireExplicitPolicy field could not be decoded.", e, certPath, index);
}
if (tmpInt == 0) {
return 0;
}
break;
}
}
}
return explicitPolicy;
}
use of java.security.cert.CertPathValidatorException in project XobotOS by xamarin.
the class RFC3280CertPathUtilities method processCertBC.
protected static void processCertBC(CertPath certPath, int index, PKIXNameConstraintValidator nameConstraintValidator) throws CertPathValidatorException {
List certs = certPath.getCertificates();
X509Certificate cert = (X509Certificate) certs.get(index);
int n = certs.size();
// i as defined in the algorithm description
int i = n - index;
//
if (!(CertPathValidatorUtilities.isSelfIssued(cert) && (i < n))) {
X500Principal principal = CertPathValidatorUtilities.getSubjectPrincipal(cert);
ASN1InputStream aIn = new ASN1InputStream(principal.getEncoded());
ASN1Sequence dns;
try {
dns = DERSequence.getInstance(aIn.readObject());
} catch (Exception e) {
throw new CertPathValidatorException("Exception extracting subject name when checking subtrees.", e, certPath, index);
}
try {
nameConstraintValidator.checkPermittedDN(dns);
nameConstraintValidator.checkExcludedDN(dns);
} catch (PKIXNameConstraintValidatorException e) {
throw new CertPathValidatorException("Subtree check for certificate subject failed.", e, certPath, index);
}
GeneralNames altName = null;
try {
altName = GeneralNames.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME));
} catch (Exception e) {
throw new CertPathValidatorException("Subject alternative name extension could not be decoded.", e, certPath, index);
}
Vector emails = new X509Name(dns).getValues(X509Name.EmailAddress);
for (Enumeration e = emails.elements(); e.hasMoreElements(); ) {
String email = (String) e.nextElement();
GeneralName emailAsGeneralName = new GeneralName(GeneralName.rfc822Name, email);
try {
nameConstraintValidator.checkPermitted(emailAsGeneralName);
nameConstraintValidator.checkExcluded(emailAsGeneralName);
} catch (PKIXNameConstraintValidatorException ex) {
throw new CertPathValidatorException("Subtree check for certificate subject alternative email failed.", ex, certPath, index);
}
}
if (altName != null) {
GeneralName[] genNames = null;
try {
genNames = altName.getNames();
} catch (Exception e) {
throw new CertPathValidatorException("Subject alternative name contents could not be decoded.", e, certPath, index);
}
for (int j = 0; j < genNames.length; j++) {
try {
nameConstraintValidator.checkPermitted(genNames[j]);
nameConstraintValidator.checkExcluded(genNames[j]);
} catch (PKIXNameConstraintValidatorException e) {
throw new CertPathValidatorException("Subtree check for certificate subject alternative name failed.", e, certPath, index);
}
}
}
}
}
Aggregations