List of usage examples for java.security.cert TrustAnchor TrustAnchor
public TrustAnchor(X509Certificate trustedCert, byte[] nameConstraints)
From source file:com.cloudbees.jenkins.plugins.enterpriseplugins.CloudBeesUpdateSite.java
/** * Verifies the signature in the update center data file. *//*from w w w . j a va 2 s .c om*/ private FormValidation verifySignature(JSONObject o) throws IOException { try { FormValidation warning = null; JSONObject signature = o.getJSONObject("signature"); if (signature.isNullObject()) { return FormValidation.error("No signature block found in update center '" + getId() + "'"); } o.remove("signature"); List<X509Certificate> certs = new ArrayList<X509Certificate>(); {// load and verify certificates CertificateFactory cf = CertificateFactory.getInstance("X509"); for (Object cert : signature.getJSONArray("certificates")) { X509Certificate c = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray()))); try { c.checkValidity(); } catch (CertificateExpiredException e) { // even if the certificate isn't valid yet, // we'll proceed it anyway warning = FormValidation.warning(e, String.format( "Certificate %s has expired in update center '%s'", cert.toString(), getId())); } catch (CertificateNotYetValidException e) { warning = FormValidation.warning(e, String.format( "Certificate %s is not yet valid in update center '%s'", cert.toString(), getId())); } certs.add(c); } // all default root CAs in JVM are trusted, plus certs bundled in Jenkins Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); // CertificateUtil.getDefaultRootCAs(); ServletContext context = Hudson.getInstance().servletContext; anchors.add(new TrustAnchor(loadLicenseCaCertificate(), null)); for (String cert : (Set<String>) context.getResourcePaths("/WEB-INF/update-center-rootCAs")) { if (cert.endsWith(".txt")) { continue; // skip text files that are meant to be documentation } InputStream stream = context.getResourceAsStream(cert); if (stream != null) { try { anchors.add(new TrustAnchor((X509Certificate) cf.generateCertificate(stream), null)); } finally { IOUtils.closeQuietly(stream); } } } CertificateUtil.validatePath(certs, anchors); } // this is for computing a digest to check sanity MessageDigest sha1 = MessageDigest.getInstance("SHA1"); DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1); // this is for computing a signature Signature sig = Signature.getInstance("SHA1withRSA"); sig.initVerify(certs.get(0)); SignatureOutputStream sos = new SignatureOutputStream(sig); // until JENKINS-11110 fix, UC used to serve invalid digest (and therefore unverifiable signature) // that only covers the earlier portion of the file. This was caused by the lack of close() call // in the canonical writing, which apparently leave some bytes somewhere that's not flushed to // the digest output stream. This affects Jenkins [1.424,1,431]. // Jenkins 1.432 shipped with the "fix" (1eb0c64abb3794edce29cbb1de50c93fa03a8229) that made it // compute the correct digest, but it breaks all the existing UC json metadata out there. We then // quickly discovered ourselves in the catch-22 situation. If we generate UC with the correct signature, // it'll cut off [1.424,1.431] from the UC. But if we don't, we'll cut off [1.432,*). // // In 1.433, we revisited 1eb0c64abb3794edce29cbb1de50c93fa03a8229 so that the original "digest"/"signature" // pair continues to be generated in a buggy form, while "correct_digest"/"correct_signature" are generated // correctly. // // Jenkins should ignore "digest"/"signature" pair. Accepting it creates a vulnerability that allows // the attacker to inject a fragment at the end of the json. o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(dos, sos), "UTF-8")).close(); // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n // (which is more likely than someone tampering with update center), we can tell String computedDigest = new String(Base64.encode(sha1.digest())); String providedDigest = signature.optString("correct_digest"); if (providedDigest == null) { return FormValidation.error("No correct_digest parameter in update center '" + getId() + "'. This metadata appears to be old."); } if (!computedDigest.equalsIgnoreCase(providedDigest)) { return FormValidation.error("Digest mismatch: " + computedDigest + " vs " + providedDigest + " in update center '" + getId() + "'"); } String providedSignature = signature.getString("correct_signature"); if (!sig.verify(Base64.decode(providedSignature.toCharArray()))) { return FormValidation.error( "Signature in the update center doesn't match with the certificate in update center '" + getId() + "'"); } if (warning != null) { return warning; } return FormValidation.ok(); } catch (GeneralSecurityException e) { return FormValidation.error(e, "Signature verification failed in the update center '" + getId() + "'"); } }
From source file:com.alfaariss.oa.profile.aselect.ws.security.OACrypto.java
/** * Validate a given certificate chain.//from ww w .ja va 2 s. c o m * @see Crypto#validateCertPath(java.security.cert.X509Certificate[]) */ public boolean validateCertPath(X509Certificate[] certs) throws WSSecurityException { boolean ok = false; try { // Generate cert path List<X509Certificate> certList = Arrays.asList(certs); CertPath path = this.getCertificateFactory().generateCertPath(certList); HashSet<TrustAnchor> set = new HashSet<TrustAnchor>(); if (certs.length == 1) // Use factory certs { String alias = _factory.getAliasForX509Cert(certs[0].getIssuerDN().getName(), certs[0].getSerialNumber()); if (alias == null) { _logger.debug("Certificate not trusted"); return false; } X509Certificate cert = (X509Certificate) _factory.getCertificate(alias); TrustAnchor anchor = new TrustAnchor(cert, cert.getExtensionValue("2.5.29.30")); set.add(anchor); } else { // Add certificates from the keystore Enumeration aliases = _factory.getAliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); X509Certificate cert = (X509Certificate) _factory.getCertificate(alias); TrustAnchor anchor = new TrustAnchor(cert, cert.getExtensionValue("2.5.29.30")); set.add(anchor); } } PKIXParameters param = new PKIXParameters(set); param.setRevocationEnabled(false); Provider provider = _factory.getKeyStore().getProvider(); String sProvider = null; CertPathValidator certPathValidator = null; if (provider != null) { sProvider = provider.getName(); } if (sProvider == null || sProvider.length() == 0) { certPathValidator = CertPathValidator.getInstance("PKIX"); } else { certPathValidator = CertPathValidator.getInstance("PKIX", sProvider); } certPathValidator.validate(path, param); ok = true; } catch (NoSuchProviderException e) { _logger.warn("No such provider", e); throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (NoSuchAlgorithmException e) { _logger.warn("No such algorithm", e); throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (InvalidAlgorithmParameterException e) { _logger.warn("Invalid algorithm param", e); throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (CertificateException e) { _logger.warn("Invalid certificate", e); throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (ClassCastException e) { _logger.warn("Certificate is not an X509Certificate", e); throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (CertPathValidatorException e) { _logger.warn("Could not validate Cert Path", e); throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (CryptoException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } return ok; }
From source file:org.globus.security.stores.PEMKeyStore.java
/** * Add a certificate to the keystore./* w w w.j ava2 s . co m*/ * * @param alias * The certificate alias. * @param certificate * The certificate to store. * @throws KeyStoreException */ @Override public void engineSetCertificateEntry(String alias, Certificate certificate) throws KeyStoreException { if (!(certificate instanceof X509Certificate)) { throw new KeyStoreException("Certificate must be instance of X509Certificate"); } File file; ResourceTrustAnchor trustAnchor = getCertificateEntry(alias); if (trustAnchor != null) { file = trustAnchor.getFile(); } else { file = new File(defaultDirectory, alias); } X509Certificate x509Cert = (X509Certificate) certificate; try { writeCertificate(x509Cert, file); ResourceTrustAnchor anchor = new ResourceTrustAnchor(new FileSystemResource(file), new TrustAnchor(x509Cert, null)); this.aliasObjectMap.put(alias, anchor); this.certFilenameMap.put(x509Cert, alias); } catch (ResourceStoreException e) { throw new KeyStoreException(e); } catch (IOException e) { throw new KeyStoreException(e); } catch (CertificateEncodingException e) { throw new KeyStoreException(e); } }
From source file:org.apache.cloudstack.network.lb.CertServiceImpl.java
private void validateChain(List<Certificate> chain, Certificate cert) { List<Certificate> certs = new ArrayList<Certificate>(); Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); certs.add(cert); // adding for self signed certs certs.addAll(chain);/*from w w w .j av a 2 s . com*/ for (Certificate c : certs) { if (!(c instanceof X509Certificate)) throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate"); X509Certificate xCert = (X509Certificate) c; Principal subject = xCert.getSubjectDN(); Principal issuer = xCert.getIssuerDN(); anchors.add(new TrustAnchor(xCert, null)); } X509CertSelector target = new X509CertSelector(); target.setCertificate((X509Certificate) cert); PKIXBuilderParameters params = null; try { params = new PKIXBuilderParameters(anchors, target); params.setRevocationEnabled(false); params.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs))); CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC"); builder.build(params); } catch (InvalidAlgorithmParameterException e) { throw new IllegalArgumentException("Invalid certificate chain", e); } catch (CertPathBuilderException e) { throw new IllegalArgumentException("Invalid certificate chain", e); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("Invalid certificate chain", e); } catch (NoSuchProviderException e) { throw new CloudRuntimeException("No provider for certificate validation", e); } }
From source file:org.apache.cloudstack.network.ssl.CertServiceImpl.java
private void validateChain(final List<Certificate> chain, final Certificate cert) { final List<Certificate> certs = new ArrayList<Certificate>(); final Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); certs.add(cert); // adding for self signed certs certs.addAll(chain);//from www .j av a 2 s . co m for (final Certificate c : certs) { if (!(c instanceof X509Certificate)) { throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate"); } final X509Certificate xCert = (X509Certificate) c; anchors.add(new TrustAnchor(xCert, null)); } final X509CertSelector target = new X509CertSelector(); target.setCertificate((X509Certificate) cert); PKIXBuilderParameters params = null; try { params = new PKIXBuilderParameters(anchors, target); params.setRevocationEnabled(false); params.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs))); final CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC"); builder.build(params); } catch (final InvalidAlgorithmParameterException | CertPathBuilderException | NoSuchAlgorithmException e) { throw new IllegalStateException("Invalid certificate chain", e); } catch (final NoSuchProviderException e) { throw new CloudRuntimeException("No provider for certificate validation", e); } }
From source file:org.apache.synapse.transport.certificatevalidation.pathvalidation.CertificatePathValidator.java
/** * Certificate Path Validation process/*w w w.j a v a 2s . c o m*/ * * @throws CertificateVerificationException * if validation process fails. */ public void validatePath() throws CertificateVerificationException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); CollectionCertStoreParameters params = new CollectionCertStoreParameters(fullCertChain); try { CertStore store = CertStore.getInstance("Collection", params, "BC"); // create certificate path CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); CertPath certPath = fact.generateCertPath(certChain); TrustAnchor trustAnchor = new TrustAnchor(fullCertChain.get(fullCertChain.size() - 1), null); Set<TrustAnchor> trust = Collections.singleton(trustAnchor); // perform validation CertPathValidator validator = CertPathValidator.getInstance("PKIX", "BC"); PKIXParameters param = new PKIXParameters(trust); param.addCertPathChecker(pathChecker); param.setRevocationEnabled(false); param.addCertStore(store); param.setDate(new Date()); validator.validate(certPath, param); log.info("Certificate path validated"); } catch (CertPathValidatorException e) { throw new CertificateVerificationException("Certificate Path Validation failed on certificate number " + e.getIndex() + ", details: " + e.getMessage(), e); } catch (Exception e) { throw new CertificateVerificationException("Certificate Path Validation failed", e); } }
From source file:org.apache.synapse.transport.utils.sslcert.pathvalidation.CertificatePathValidator.java
/** * Certificate Path Validation process/*from w ww . j ava 2s . c o m*/ * * @throws CertificateVerificationException * if validation process fails. */ public void validatePath() throws CertificateVerificationException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); CollectionCertStoreParameters params = new CollectionCertStoreParameters(fullCertChain); try { CertStore store = CertStore.getInstance("Collection", params, "BC"); // create certificate path CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); CertPath certPath = fact.generateCertPath(certChain); TrustAnchor trustAnchor = new TrustAnchor(fullCertChain.get(fullCertChain.size() - 1), null); Set<TrustAnchor> trust = Collections.singleton(trustAnchor); // perform validation CertPathValidator validator = CertPathValidator.getInstance("PKIX", "BC"); PKIXParameters param = new PKIXParameters(trust); param.addCertPathChecker(pathChecker); param.setRevocationEnabled(false); param.addCertStore(store); param.setDate(new Date()); validator.validate(certPath, param); log.debug("Certificate path validated"); } catch (CertPathValidatorException e) { throw new CertificateVerificationException("Certificate Path Validation failed on " + "certificate number " + e.getIndex() + ", details: " + e.getMessage(), e); } catch (Exception e) { throw new CertificateVerificationException("Certificate Path Validation failed", e); } }
From source file:org.apache.ws.security.components.crypto.Merlin.java
/** * Evaluate whether a given certificate chain should be trusted. * Uses the CertPath API to validate a given certificate chain. * * @param certs Certificate chain to validate * @param enableRevocation whether to enable CRL verification or not * @return true if the certificate chain is valid, false otherwise * @throws WSSecurityException// www . j a v a 2s .c o m */ public boolean verifyTrust(X509Certificate[] certs, boolean enableRevocation) throws WSSecurityException { try { // Generate cert path List<X509Certificate> certList = Arrays.asList(certs); CertPath path = getCertificateFactory().generateCertPath(certList); Set<TrustAnchor> set = new HashSet<TrustAnchor>(); if (truststore != null) { Enumeration<String> truststoreAliases = truststore.aliases(); while (truststoreAliases.hasMoreElements()) { String alias = truststoreAliases.nextElement(); X509Certificate cert = (X509Certificate) truststore.getCertificate(alias); if (cert != null) { TrustAnchor anchor = new TrustAnchor(cert, cert.getExtensionValue(NAME_CONSTRAINTS_OID)); set.add(anchor); } } } // // Add certificates from the keystore - only if there is no TrustStore, apart from // the case that the truststore is the JDK CA certs. This behaviour is preserved // for backwards compatibility reasons // if (keystore != null && (truststore == null || loadCACerts)) { Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); X509Certificate cert = (X509Certificate) keystore.getCertificate(alias); if (cert != null) { TrustAnchor anchor = new TrustAnchor(cert, cert.getExtensionValue(NAME_CONSTRAINTS_OID)); set.add(anchor); } } } PKIXParameters param = new PKIXParameters(set); param.setRevocationEnabled(enableRevocation); if (enableRevocation && crlCertStore != null) { param.addCertStore(crlCertStore); } // Verify the trust path using the above settings String provider = getCryptoProvider(); CertPathValidator validator = null; if (provider == null || provider.length() == 0) { validator = CertPathValidator.getInstance("PKIX"); } else { validator = CertPathValidator.getInstance("PKIX", provider); } validator.validate(path, param); return true; } catch (java.security.NoSuchProviderException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (java.security.NoSuchAlgorithmException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (java.security.cert.CertificateException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (java.security.InvalidAlgorithmParameterException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (java.security.cert.CertPathValidatorException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (java.security.KeyStoreException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } catch (NullPointerException e) { // NPE thrown by JDK 1.7 for one of the test cases throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() }, e); } }
From source file:org.cesecore.util.CertTools.java
/** * Method to create certificate path and to check it's validity from a list of certificates. The list of certificates should only contain one root * certificate.//from w w w.ja v a 2 s. c om * * @param certlist * @return the certificatepath with the root CA at the end * @throws CertPathValidatorException if the certificate chain can not be constructed * @throws InvalidAlgorithmParameterException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws CertificateException */ public static List<Certificate> createCertChain(Collection<?> certlistin) throws CertPathValidatorException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, CertificateException { final List<Certificate> returnval = new ArrayList<Certificate>(); Collection<Certificate> certlist = orderCertificateChain(certlistin); // set certificate chain Certificate rootcert = null; ArrayList<Certificate> calist = new ArrayList<Certificate>(); for (Certificate next : certlist) { if (CertTools.isSelfSigned(next)) { rootcert = next; } else { calist.add(next); } } if (calist.isEmpty()) { // only one root cert, no certchain returnval.add(rootcert); } else { // We need a bit special handling for CV certificates because those can not be handled using a PKIX CertPathValidator Certificate test = calist.get(0); if (test.getType().equals("CVC")) { if (calist.size() == 1) { returnval.add(test); returnval.add(rootcert); } else { throw new CertPathValidatorException( "CVC certificate chain can not be of length longer than two."); } } else { // Normal X509 certificates HashSet<TrustAnchor> trustancors = new HashSet<TrustAnchor>(); TrustAnchor trustanchor = null; trustanchor = new TrustAnchor((X509Certificate) rootcert, null); trustancors.add(trustanchor); // Create the parameters for the validator PKIXParameters params = new PKIXParameters(trustancors); // Disable CRL checking since we are not supplying any CRLs params.setRevocationEnabled(false); params.setDate(new Date()); // Create the validator and validate the path CertPathValidator certPathValidator = CertPathValidator .getInstance(CertPathValidator.getDefaultType(), "BC"); CertificateFactory fact = CertTools.getCertificateFactory(); CertPath certpath = fact.generateCertPath(calist); CertPathValidatorResult result = certPathValidator.validate(certpath, params); // Get the certificates validate in the path PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result; returnval.addAll(certpath.getCertificates()); // Get the CA used to validate this path TrustAnchor ta = pkixResult.getTrustAnchor(); X509Certificate cert = ta.getTrustedCert(); returnval.add(cert); } } return returnval; }
From source file:org.ejbca.extra.db.ExtRAMsgHelper.java
/** * Method used to verify signed data.//from ww w. j a va 2 s . co m * * @param TrustedCACerts a Collection of trusted certificates, should contain the entire chains * @param TrustedCRLs a Collection of trusted CRLS, use null if no CRL check should be used. * @param signedData the data to verify * @param date the date used to check the validity against. * @return a ParsedSignatureResult. */ public static ParsedSignatureResult verifySignature(Collection cACertChain, Collection trustedCRLs, byte[] signedData, Date date) { boolean verifies = false; X509Certificate usercert = null; ParsedSignatureResult retval = new ParsedSignatureResult(false, null, null); byte[] content = null; try { // First verify the signature CMSSignedData sp = new CMSSignedData(signedData); CertStore certs = sp.getCertificatesAndCRLs("Collection", "BC"); SignerInformationStore signers = sp.getSignerInfos(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ((CMSProcessableByteArray) sp.getSignedContent()).write(baos); content = baos.toByteArray(); baos.close(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection certCollection = certs.getCertificates(signer.getSID()); Iterator certIt = certCollection.iterator(); usercert = (X509Certificate) certIt.next(); boolean validalg = signer.getDigestAlgOID().equals(signAlg); verifies = validalg && signer.verify(usercert.getPublicKey(), "BC"); } // Second validate the certificate X509Certificate rootCert = null; Iterator iter = cACertChain.iterator(); while (iter.hasNext()) { X509Certificate cert = (X509Certificate) iter.next(); if (cert.getIssuerDN().equals(cert.getSubjectDN())) { rootCert = cert; break; } } if (rootCert == null) { throw new CertPathValidatorException("Error Root CA cert not found in cACertChain"); } List list = new ArrayList(); list.add(usercert); list.add(cACertChain); if (trustedCRLs != null) { list.add(trustedCRLs); } CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list); CertStore store = CertStore.getInstance("Collection", ccsp); //validating path List certchain = new ArrayList(); certchain.addAll(cACertChain); certchain.add(usercert); CertPath cp = CertificateFactory.getInstance("X.509", "BC").generateCertPath(certchain); Set trust = new HashSet(); trust.add(new TrustAnchor(rootCert, null)); CertPathValidator cpv = CertPathValidator.getInstance("PKIX", "BC"); PKIXParameters param = new PKIXParameters(trust); param.addCertStore(store); param.setDate(date); if (trustedCRLs == null) { param.setRevocationEnabled(false); } else { param.setRevocationEnabled(true); } cpv.validate(cp, param); retval = new ParsedSignatureResult(verifies, usercert, content); } catch (Exception e) { log.error("Error verifying data : ", e); } return retval; }