use of java.security.cert.TrustAnchor in project Openfire by igniterealtime.
the class OCSPChecker method check.
@Override
public void check(Certificate cert, Collection<String> unresolvedCritExts) throws CertPathValidatorException {
Log.debug("OCSPChecker: check called");
InputStream in = null;
OutputStream out = null;
try {
// Examine OCSP properties
X509Certificate responderCert = null;
//defaults to issuers cert
boolean haveResponderCert = true;
X500Principal responderSubjectName = null;
boolean haveIssuerCert = false;
// If we set the subject name, we need to find the certificate
if (ocspServerSubject != null) {
haveResponderCert = false;
responderSubjectName = new X500Principal(ocspServerSubject);
}
X509Certificate issuerCert = null;
X509Certificate currCert = (X509Certificate) cert;
// Set the issuer certificate if we were passed a chain
if (certIndex != 0) {
issuerCert = certs[certIndex];
haveIssuerCert = true;
if (haveResponderCert) {
responderCert = certs[certIndex];
}
}
if (!haveIssuerCert || !haveResponderCert) {
if (!haveResponderCert) {
Log.debug("OCSPChecker: Looking for responder's certificate");
}
if (!haveIssuerCert) {
Log.debug("OCSPChecker: Looking for issuer's certificate");
}
// Extract the anchor certs
Iterator anchors = pkixParams.getTrustAnchors().iterator();
if (!anchors.hasNext()) {
throw new CertPathValidatorException("Must specify at least one trust anchor");
}
X500Principal certIssuerName = currCert.getIssuerX500Principal();
while (anchors.hasNext() && (!haveIssuerCert || !haveResponderCert)) {
TrustAnchor anchor = (TrustAnchor) anchors.next();
X509Certificate anchorCert = anchor.getTrustedCert();
X500Principal anchorSubjectName = anchorCert.getSubjectX500Principal();
// Check if this anchor cert is the issuer cert
if (!haveIssuerCert && certIssuerName.equals(anchorSubjectName)) {
issuerCert = anchorCert;
haveIssuerCert = true;
//If we have not set the responderCert at this point, set it to the issuer
if (haveResponderCert && responderCert == null) {
responderCert = anchorCert;
Log.debug("OCSPChecker: Responder's certificate = issuer certificate");
}
}
// Check if this anchor cert is the responder cert
if (!haveResponderCert) {
if (responderSubjectName != null && responderSubjectName.equals(anchorSubjectName)) {
responderCert = anchorCert;
haveResponderCert = true;
}
}
}
if (issuerCert == null) {
//No trust anchor was found matching the issuer
throw new CertPathValidatorException("No trusted certificate for " + currCert.getIssuerDN());
}
// Check cert stores if responder cert has not yet been found
if (!haveResponderCert) {
Log.debug("OCSPChecker: Searching cert stores for responder's certificate");
if (responderSubjectName != null) {
X509CertSelector filter = new X509CertSelector();
filter.setSubject(responderSubjectName.getName());
List<CertStore> certStores = pkixParams.getCertStores();
for (CertStore certStore : certStores) {
Iterator i = certStore.getCertificates(filter).iterator();
if (i.hasNext()) {
responderCert = (X509Certificate) i.next();
haveResponderCert = true;
break;
}
}
}
}
}
// Could not find the responder cert
if (!haveResponderCert) {
throw new CertPathValidatorException("Cannot find the responder's certificate.");
}
// Construct an OCSP Request
OCSPReqBuilder gen = new OCSPReqBuilder();
CertificateID certID = new CertificateID(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1), new X509CertificateHolder(issuerCert.getEncoded()), currCert.getSerialNumber());
gen.addRequest(certID);
OCSPReq ocspRequest = gen.build();
URL url;
if (ocspServerUrl != null) {
try {
url = new URL(ocspServerUrl);
} catch (MalformedURLException e) {
throw new CertPathValidatorException(e);
}
} else {
throw new CertPathValidatorException("Must set OCSP Server URL");
}
HttpURLConnection con = (HttpURLConnection) url.openConnection();
Log.debug("OCSPChecker: connecting to OCSP service at: " + url);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-type", "application/ocsp-request");
con.setRequestProperty("Accept", "application/ocsp-response");
byte[] bytes = ocspRequest.getEncoded();
con.setRequestProperty("Content-length", String.valueOf(bytes.length));
out = con.getOutputStream();
out.write(bytes);
out.flush();
// Check the response
if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.debug("OCSPChecker: Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage());
}
in = con.getInputStream();
OCSPResp ocspResponse = new OCSPResp(in);
BigInteger serialNumber = currCert.getSerialNumber();
BasicOCSPResp brep = (BasicOCSPResp) ocspResponse.getResponseObject();
try {
if (!brep.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(responderCert.getPublicKey()))) {
throw new CertPathValidatorException("OCSP response is not verified");
}
} catch (Exception e) {
throw new CertPathValidatorException("OCSP response could not be verified (" + e.getMessage() + ")", null, cp, certIndex);
}
SingleResp[] singleResp = brep.getResponses();
boolean foundResponse = false;
for (SingleResp resp : singleResp) {
CertificateID respCertID = resp.getCertID();
if (respCertID.equals(certID)) {
Object status = resp.getCertStatus();
if (status == CertificateStatus.GOOD) {
Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: good");
foundResponse = true;
break;
} else if (status instanceof org.bouncycastle.cert.ocsp.RevokedStatus) {
Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: revoked");
throw new CertPathValidatorException("Certificate has been revoked", null, cp, certIndex);
} else if (status instanceof org.bouncycastle.cert.ocsp.UnknownStatus) {
Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: unknown");
throw new CertPathValidatorException("Certificate's revocation status is unknown", null, cp, certIndex);
} else {
Log.debug("Status of certificate (with serial number " + serialNumber.toString() + ") is: not recognized");
throw new CertPathValidatorException("Unknown OCSP response for certificate", null, cp, certIndex);
}
}
}
// Check that response applies to the cert that was supplied
if (!foundResponse) {
throw new CertPathValidatorException("No certificates in the OCSP response match the " + "certificate supplied in the OCSP request.");
}
} catch (CertPathValidatorException cpve) {
throw cpve;
} 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);
}
}
}
}
use of java.security.cert.TrustAnchor in project jdk8u_jdk by JetBrains.
the class BuildEEBasicConstraints method main.
public static void main(String[] args) throws Exception {
// reset the security property to make sure that the algorithms
// and keys used in this test are not disabled.
Security.setProperty("jdk.certpath.disabledAlgorithms", "MD2");
X509Certificate rootCert = CertUtils.getCertFromFile("anchor.cer");
TrustAnchor anchor = new TrustAnchor(rootCert.getSubjectX500Principal(), rootCert.getPublicKey(), null);
X509CertSelector sel = new X509CertSelector();
sel.setBasicConstraints(-2);
PKIXBuilderParameters params = new PKIXBuilderParameters(Collections.singleton(anchor), sel);
params.setRevocationEnabled(false);
X509Certificate eeCert = CertUtils.getCertFromFile("ee.cer");
X509Certificate caCert = CertUtils.getCertFromFile("ca.cer");
ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>();
certs.add(caCert);
certs.add(eeCert);
CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(certs);
CertStore cs = CertStore.getInstance("Collection", ccsp);
params.addCertStore(cs);
PKIXCertPathBuilderResult res = CertUtils.build(params);
CertPath cp = res.getCertPath();
// check that first certificate is an EE cert
List<? extends Certificate> certList = cp.getCertificates();
X509Certificate cert = (X509Certificate) certList.get(0);
if (cert.getBasicConstraints() != -1) {
throw new Exception("Target certificate is not an EE certificate");
}
}
use of java.security.cert.TrustAnchor in project jdk8u_jdk by JetBrains.
the class ValidateTargetConstraints method createPath.
public static void createPath(String[] certs) throws Exception {
TrustAnchor anchor = new TrustAnchor(getCertFromFile(certs[0]), null);
List list = new ArrayList();
for (int i = 1; i < certs.length; i++) {
list.add(0, getCertFromFile(certs[i]));
}
CertificateFactory cf = CertificateFactory.getInstance("X509");
path = cf.generateCertPath(list);
Set anchors = Collections.singleton(anchor);
params = new PKIXParameters(anchors);
params.setRevocationEnabled(false);
X509CertSelector sel = new X509CertSelector();
sel.setSerialNumber(new BigInteger("1427"));
params.setTargetCertConstraints(sel);
}
use of java.security.cert.TrustAnchor in project jdk8u_jdk by JetBrains.
the class ValidateNC method createPath.
public static void createPath(String[] certs) throws Exception {
X509Certificate anchorCert = getCertFromFile(certs[0]);
byte[] nameConstraints = anchorCert.getExtensionValue("2.5.29.30");
if (nameConstraints != null) {
DerInputStream in = new DerInputStream(nameConstraints);
nameConstraints = in.getOctetString();
}
TrustAnchor anchor = new TrustAnchor(anchorCert, nameConstraints);
List list = new ArrayList();
for (int i = 1; i < certs.length; i++) {
list.add(0, getCertFromFile(certs[i]));
}
CertificateFactory cf = CertificateFactory.getInstance("X509");
path = cf.generateCertPath(list);
anchors = Collections.singleton(anchor);
params = new PKIXParameters(anchors);
params.setRevocationEnabled(false);
}
use of java.security.cert.TrustAnchor in project oxAuth by GluuFederation.
the class PathCertificateVerifier method verifyCertificate.
/**
* Attempts to build a certification chain for given certificate to verify
* it. Relies on a set of root CA certificates (trust anchors) and a set of
* intermediate certificates (to be used as part of the chain).
*/
private PKIXCertPathBuilderResult verifyCertificate(X509Certificate certificate, Set<X509Certificate> trustedRootCerts, Set<X509Certificate> intermediateCerts) throws GeneralSecurityException {
// Create the selector that specifies the starting certificate
X509CertSelector selector = new X509CertSelector();
selector.setBasicConstraints(-2);
selector.setCertificate(certificate);
// Create the trust anchors (set of root CA certificates)
Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
for (X509Certificate trustedRootCert : trustedRootCerts) {
trustAnchors.add(new TrustAnchor(trustedRootCert, null));
}
// Configure the PKIX certificate builder algorithm parameters
PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, selector);
// Turn off default revocation-checking mechanism
pkixParams.setRevocationEnabled(false);
// Specify a list of intermediate certificates
CertStore intermediateCertStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(intermediateCerts));
pkixParams.addCertStore(intermediateCertStore);
// Build and verify the certification chain
CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);
PKIXCertPathBuilderResult certPathBuilderResult = (PKIXCertPathBuilderResult) builder.build(pkixParams);
// Additional check to Verify cert path
CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);
PKIXCertPathValidatorResult certPathValidationResult = (PKIXCertPathValidatorResult) certPathValidator.validate(certPathBuilderResult.getCertPath(), pkixParams);
return certPathBuilderResult;
}
Aggregations