use of java.security.cert.CertPathValidator in project Openfire by igniterealtime.
the class ClientTrustManager method checkClientTrusted.
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String string) throws CertificateException {
Log.debug("ClientTrustManager: checkClientTrusted(x509Certificates," + string + ") called");
loadCRL();
ArrayList<X509Certificate> certs = new ArrayList<>();
for (int i = 0; i < x509Certificates.length; i++) {
certs.add(x509Certificates[i]);
}
boolean verify = JiveGlobals.getBooleanProperty("xmpp.client.certificate.verify", true);
if (verify) {
int nSize = x509Certificates.length;
List<String> peerIdentities = CertificateManager.getClientIdentities(x509Certificates[0]);
if (JiveGlobals.getBooleanProperty("xmpp.client.certificate.verify.chain", true)) {
// Working down the chain, for every certificate in the chain,
// verify that the subject of the certificate is the issuer of the
// next certificate in the chain.
Principal principalLast = null;
for (int i = nSize - 1; i >= 0; i--) {
X509Certificate x509certificate = x509Certificates[i];
Principal principalIssuer = x509certificate.getIssuerDN();
Principal principalSubject = x509certificate.getSubjectDN();
if (principalLast != null) {
if (principalIssuer.equals(principalLast)) {
try {
PublicKey publickey = x509Certificates[i + 1].getPublicKey();
x509Certificates[i].verify(publickey);
} catch (GeneralSecurityException generalsecurityexception) {
throw new CertificateException("signature verification failed of " + peerIdentities);
}
} else {
throw new CertificateException("subject/issuer verification failed of " + peerIdentities);
}
}
principalLast = principalSubject;
}
}
if (JiveGlobals.getBooleanProperty("xmpp.client.certificate.verify.root", true)) {
// Verify that the the last certificate in the chain was issued
// by a third-party that the client trusts, or is trusted itself
boolean trusted = false;
try {
Enumeration<String> aliases = trustStore.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
X509Certificate tCert = (X509Certificate) trustStore.getCertificate(alias);
if (x509Certificates[nSize - 1].equals(tCert)) {
try {
PublicKey publickey = tCert.getPublicKey();
x509Certificates[nSize - 1].verify(publickey);
} catch (GeneralSecurityException generalsecurityexception) {
throw new CertificateException("signature verification failed of " + peerIdentities);
}
trusted = true;
break;
} else {
if (x509Certificates[nSize - 1].getIssuerDN().equals(tCert.getSubjectDN())) {
try {
PublicKey publickey = tCert.getPublicKey();
x509Certificates[nSize - 1].verify(publickey);
} catch (GeneralSecurityException generalsecurityexception) {
throw new CertificateException("signature verification failed of " + peerIdentities);
}
trusted = true;
break;
}
}
}
} catch (KeyStoreException e) {
Log.error(e.getMessage(), e);
}
if (!trusted) {
//Log.debug("certificate not trusted of "+peerIdentities);
throw new CertificateException("root certificate not trusted of " + peerIdentities);
}
}
if (JiveGlobals.getBooleanProperty("xmpp.client.certificate.verify.validity", true)) {
// For every certificate in the chain, verify that the certificate
// is valid at the current time.
Date date = new Date();
for (int i = 0; i < nSize; i++) {
try {
x509Certificates[i].checkValidity(date);
} catch (GeneralSecurityException generalsecurityexception) {
throw new CertificateException("invalid date of " + peerIdentities);
}
}
}
//Verify certificate path
try {
CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
CertPathBuilder cpb = CertPathBuilder.getInstance("PKIX");
X509CertSelector certSelector = new X509CertSelector();
certSelector.setCertificate(x509Certificates[0]);
PKIXBuilderParameters params = new PKIXBuilderParameters(trustStore, certSelector);
if (useCRLs) {
params.addCertStore(crlStore);
} else {
Log.debug("ClientTrustManager: no CRL's found, so setRevocationEnabled(false)");
params.setRevocationEnabled(false);
}
CertPathBuilderResult cpbr = cpb.build(params);
CertPath cp = cpbr.getCertPath();
if (JiveGlobals.getBooleanProperty("ocsp.enable", false)) {
Log.debug("ClientTrustManager: OCSP requested");
OCSPChecker ocspChecker = new OCSPChecker(cp, params);
params.addCertPathChecker(ocspChecker);
}
PKIXCertPathValidatorResult cpvResult = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
X509Certificate trustedCert = cpvResult.getTrustAnchor().getTrustedCert();
if (trustedCert == null) {
throw new CertificateException("certificate path failed: Trusted CA is NULL");
} else {
Log.debug("ClientTrustManager: Trusted CA: " + trustedCert.getSubjectDN());
}
} catch (CertPathBuilderException | CertPathValidatorException e) {
Log.debug("ClientTrustManager:", e);
throw new CertificateException("certificate path failed: " + e.getMessage());
} catch (Exception e) {
Log.debug("ClientTrustManager:", e);
throw new CertificateException("unexpected error: " + e.getMessage());
}
}
}
use of java.security.cert.CertPathValidator 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.CertPathValidator in project robovm by robovm.
the class PKIXCertPathBuilderSpi method build.
protected CertPathBuilderResult build(X509Certificate tbvCert, ExtendedPKIXBuilderParameters pkixParams, List tbvPath) {
// PKI graph.
if (tbvPath.contains(tbvCert)) {
return null;
}
// chain.
if (pkixParams.getExcludedCerts().contains(tbvCert)) {
return null;
}
// test if certificate path exceeds maximum length
if (pkixParams.getMaxPathLength() != -1) {
if (tbvPath.size() - 1 > pkixParams.getMaxPathLength()) {
return null;
}
}
tbvPath.add(tbvCert);
CertificateFactory cFact;
CertPathValidator validator;
CertPathBuilderResult builderResult = null;
try {
cFact = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME);
validator = CertPathValidator.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);
} catch (Exception e) {
// cannot happen
throw new RuntimeException("Exception creating support classes.");
}
try {
// check whether the issuer of <tbvCert> is a TrustAnchor
if (CertPathValidatorUtilities.findTrustAnchor(tbvCert, pkixParams.getTrustAnchors(), pkixParams.getSigProvider()) != null) {
// exception message from possibly later tried certification
// chains
CertPath certPath = null;
PKIXCertPathValidatorResult result = null;
try {
certPath = cFact.generateCertPath(tbvPath);
} catch (Exception e) {
throw new AnnotatedException("Certification path could not be constructed from certificate list.", e);
}
try {
result = (PKIXCertPathValidatorResult) validator.validate(certPath, pkixParams);
} catch (Exception e) {
throw new AnnotatedException("Certification path could not be validated.", e);
}
return new PKIXCertPathBuilderResult(certPath, result.getTrustAnchor(), result.getPolicyTree(), result.getPublicKey());
} else {
// add additional X.509 stores from locations in certificate
try {
CertPathValidatorUtilities.addAdditionalStoresFromAltNames(tbvCert, pkixParams);
} catch (CertificateParsingException e) {
throw new AnnotatedException("No additiontal X.509 stores can be added from certificate locations.", e);
}
Collection issuers = new HashSet();
// of the stores
try {
issuers.addAll(CertPathValidatorUtilities.findIssuerCerts(tbvCert, pkixParams));
} catch (AnnotatedException e) {
throw new AnnotatedException("Cannot find issuer certificate for certificate in certification path.", e);
}
if (issuers.isEmpty()) {
throw new AnnotatedException("No issuer certificate for certificate in certification path found.");
}
Iterator it = issuers.iterator();
while (it.hasNext() && builderResult == null) {
X509Certificate issuer = (X509Certificate) it.next();
builderResult = build(issuer, pkixParams, tbvPath);
}
}
} catch (AnnotatedException e) {
certPathException = e;
}
if (builderResult == null) {
tbvPath.remove(tbvCert);
}
return builderResult;
}
use of java.security.cert.CertPathValidator in project robovm by robovm.
the class CertPathValidatorTest method testCertPathValidator.
public void testCertPathValidator() throws Exception {
CertPathValidator certPathValidator = CertPathValidator.getInstance(algorithmName);
CertPathValidatorResult validatorResult = certPathValidator.validate(getCertPath(), getParams());
validateResult(validatorResult);
}
use of java.security.cert.CertPathValidator in project robovm by robovm.
the class invalidParams method testCertPathValidator12.
/**
* Test for
* <code>CertPathValidator</code> constructor
* Assertion: returns CertPathValidator object
*/
public void testCertPathValidator12() throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, CertPathValidatorException, InvalidAlgorithmParameterException {
if (!PKIXSupport) {
fail(NotSupportMsg);
return;
}
CertPathValidatorSpi spi = new MyCertPathValidatorSpi();
CertPathValidator certPV = new myCertPathValidator(spi, defaultProvider, defaultType);
assertEquals("Incorrect algorithm", certPV.getAlgorithm(), defaultType);
assertEquals("Incorrect provider", certPV.getProvider(), defaultProvider);
certPV.validate(null, null);
try {
certPV.validate(null, null);
fail("CertPathValidatorException must be thrown");
} catch (CertPathValidatorException e) {
}
certPV = new myCertPathValidator(null, null, null);
assertNull("Incorrect algorithm", certPV.getAlgorithm());
assertNull("Incorrect provider", certPV.getProvider());
try {
certPV.validate(null, null);
fail("NullPointerException must be thrown");
} catch (NullPointerException e) {
}
}
Aggregations