/** * Creates a new test instance with given parameters. * * @param checker Revocation checker instance. * @param expiredCRLPolicy Policy instance for handling expired CRL data. * @param certFiles File names of certificates to check. * @param crlFile File name of CRL file to serve out. * @param expected Expected result of check; null to indicate expected success. */ public CRLDistributionPointRevocationCheckerTests( final CRLDistributionPointRevocationChecker checker, final RevocationPolicy<X509CRL> expiredCRLPolicy, final String[] certFiles, final String crlFile, final GeneralSecurityException expected) throws Exception { super(certFiles, expected); final File file = new File(System.getProperty("java.io.tmpdir"), "ca.crl"); if (file.exists()) { file.delete(); } final OutputStream out = new FileOutputStream(file); IOUtils.copy(new ClassPathResource(crlFile).getInputStream(), out); this.checker = checker; this.checker.setExpiredCRLPolicy(expiredCRLPolicy); this.webServer = new MockWebServer(8085, new FileSystemResource(file), "text/plain"); logger.debug("Web server listening on port 8085 serving file {}", crlFile); }
@Override protected boolean addCRL(final Object id, final X509CRL crl) { try { if (crl == null) { logger.debug("No CRL was passed. Removing {} from cache...", id); return this.crlCache.remove(id); } this.crlCache.put(new Element(id, crl.getEncoded())); return this.crlCache.get(id) != null; } catch (final Exception e) { logger.warn("Failed to add the crl entry [{}] to the cache", crl); throw new RuntimeException(e); } }
/** * return the issuer of the given CRL as an X509PrincipalObject. */ public static X509Principal getIssuerX509Principal( X509CRL crl) throws CRLException { try { ByteArrayInputStream bIn = new ByteArrayInputStream( crl.getTBSCertList()); ASN1InputStream aIn = new ASN1InputStream(bIn); TBSCertList tbsCertList = new TBSCertList( (ASN1Sequence)aIn.readObject()); return new X509Principal(tbsCertList.getIssuer()); } catch (IOException e) { throw new CRLException(e.toString()); } }
/** * Creates a new test instance with given parameters. * * @param checker Revocation checker instance. * @param expiredCRLPolicy Policy instance for handling expired CRL data. * @param certFiles File names of certificates to check. * @param crlFile File name of CRL file to serve out. * @param expected Expected result of check; null to indicate expected success. */ public CRLDistributionPointRevocationCheckerTests( final CRLDistributionPointRevocationChecker checker, final RevocationPolicy<X509CRL> expiredCRLPolicy, final String[] certFiles, final String crlFile, final GeneralSecurityException expected) throws Exception { super(certFiles, expected); final File file = new File(System.getProperty("java.io.tmpdir"), "ca.crl"); if (file.exists()) { file.delete(); } final OutputStream out = new FileOutputStream(file); IOUtils.copy(new ClassPathResource(crlFile).getInputStream(), out); this.checker = checker; this.checker.setExpiredCRLPolicy(expiredCRLPolicy); this.checker.init(); this.webServer = new MockWebServer(8085, new FileSystemResource(file), "text/plain"); logger.debug("Web server listening on port 8085 serving file {}", crlFile); }
/** * Creates a new test instance with given parameters. * * @param checker Revocation checker instance. * @param expiredCRLPolicy Policy instance for handling expired CRL data. * @param certFiles File names of certificates to check. * @param expected Expected result of check; null to indicate expected success. */ public ResourceCRLRevocationCheckerTests( final ResourceCRLRevocationChecker checker, final RevocationPolicy<X509CRL> expiredCRLPolicy, final String[] certFiles, final GeneralSecurityException expected) { super(certFiles, expected); this.checker = checker; this.checker.setExpiredCRLPolicy(expiredCRLPolicy); try { this.checker.init(); } catch (final Exception e) { throw new RuntimeException("ResourceCRLRevocationChecker initialization failed", e); } }
private void printCRL(CRL crl, PrintStream out) throws Exception { X509CRL xcrl = (X509CRL)crl; if (rfc) { out.println("-----BEGIN X509 CRL-----"); out.println(Base64.getMimeEncoder(64, CRLF).encodeToString(xcrl.getEncoded())); out.println("-----END X509 CRL-----"); } else { String s; if (crl instanceof X509CRLImpl) { X509CRLImpl x509crl = (X509CRLImpl) crl; s = x509crl.toStringWithAlgName(withWeak("" + x509crl.getSigAlgId())); } else { s = crl.toString(); } out.println(s); } }
@Override public X509CRL fetch(final Object crl) throws Exception { final Set<X509CRL> results = fetch(Collections.singleton(crl)); if (!results.isEmpty()) { return results.iterator().next(); } logger.warn("Unable to fetch {}", crl); return null; }
/** * {@inheritDoc} * The CRL next update time is compared against the current time with the threshold * applied and rejected if and only if the next update time is in the past. * * @param crl CRL instance to evaluate. * * @throws GeneralSecurityException On expired CRL data. Check the exception type for exact details * * @see org.jasig.cas.adaptors.x509.authentication.handler.support.RevocationPolicy#apply(java.lang.Object) */ @Override public void apply(final X509CRL crl) throws GeneralSecurityException { final Calendar cutoff = Calendar.getInstance(); if (CertUtils.isExpired(crl, cutoff.getTime())) { cutoff.add(Calendar.SECOND, -this.threshold); if (CertUtils.isExpired(crl, cutoff.getTime())) { throw new ExpiredCRLException(crl.toString(), cutoff.getTime(), this.threshold); } logger.info(String.format("CRL expired on %s but is within threshold period, %s seconds.", crl.getNextUpdate(), this.threshold)); } }
/** * Creates a new test instance with given parameters. * * @param policy Policy to test. * @param crl CRL instance to apply policy to. * @param expected Expected result of policy application; null to indicate expected success. */ public ThresholdExpiredCRLRevocationPolicyTests( final ThresholdExpiredCRLRevocationPolicy policy, final X509CRL crl, final GeneralSecurityException expected) { this.policy = policy; this.expected = expected; this.crl = crl; }
/** * Creates a new test instance with given parameters. * * @param checker Revocation checker instance. * @param expiredCRLPolicy Policy instance for handling expired CRL data. * @param certFiles File names of certificates to check. * @param expected Expected result of check; null to indicate expected success. */ public ResourceCRLRevocationCheckerTests( final ResourceCRLRevocationChecker checker, final RevocationPolicy<X509CRL> expiredCRLPolicy, final String[] certFiles, final GeneralSecurityException expected) { super(certFiles, expected); this.checker = checker; this.checker.setExpiredCRLPolicy(expiredCRLPolicy); try { this.checker.afterPropertiesSet(); } catch (final Exception e) { throw new RuntimeException("ResourceCRLRevocationChecker initialization failed", e); } }
@Override protected boolean addCRL(final Object id, final X509CRL crl) { try { if (crl == null) { LOGGER.debug("No CRL was passed. Removing [{}] from cache...", id); return this.crlCache.remove(id); } this.crlCache.put(new Element(id, crl.getEncoded())); return this.crlCache.get(id) != null; } catch (final Exception e) { LOGGER.warn("Failed to add the crl entry [{}] to the cache", crl); throw Throwables.propagate(e); } }
/** * Reads in a X509CRL. * * @return the X509Certificate * @throws IOException if an I/O error occured */ private X509CRL readCRL( String endMarker) throws IOException { ByteArrayInputStream bIn = new ByteArrayInputStream(readBytes(endMarker)); try { CertificateFactory certFact = CertificateFactory.getInstance("X.509", provider); return (X509CRL)certFact.generateCRL(bIn); } catch (Exception e) { throw new IOException("problem parsing cert: " + e.toString()); } }
/** * Extract the issuer X500Principal from an X509CRL. Parses the encoded * form of the CRL to preserve the principal's ASN.1 encoding. * * Called by java.security.cert.X509CRL.getIssuerX500Principal(). */ public static X500Principal getIssuerX500Principal(X509CRL crl) { try { byte[] encoded = crl.getEncoded(); DerInputStream derIn = new DerInputStream(encoded); DerValue tbsCert = derIn.getSequence(3)[0]; DerInputStream tbsIn = tbsCert.data; DerValue tmp; // skip version number if present byte nextByte = (byte)tbsIn.peekByte(); if (nextByte == DerValue.tag_Integer) { tmp = tbsIn.getDerValue(); } tmp = tbsIn.getDerValue(); // skip signature tmp = tbsIn.getDerValue(); // issuer byte[] principalBytes = tmp.toByteArray(); return new X500Principal(principalBytes); } catch (Exception e) { throw new RuntimeException("Could not parse issuer", e); } }
static void test_create_signature_x509_crt_crl() throws Exception { System.out.println("* Generating signature-x509-crt-crl.xml"); List<Object> xds = new ArrayList<>(); CertificateFactory cf = CertificateFactory.getInstance("X.509"); xds.add(signingCert); FileInputStream fis = new FileInputStream(CRL); X509CRL crl = (X509CRL) cf.generateCRL(fis); fis.close(); xds.add(crl); KeyInfo crt_crl = kifac.newKeyInfo(Collections.singletonList (kifac.newX509Data(xds))); test_create_signature_external(dsaSha1, crt_crl, signingKey, new X509KeySelector(ks), false); System.out.println(); }
/** * Add the CRLEntry objects contained in a previous CRL. * * @param other the X509CRL to source the other entries from. */ public void addCRL(X509CRL other) throws CRLException { Set revocations = other.getRevokedCertificates(); if (revocations != null) { Iterator it = revocations.iterator(); while (it.hasNext()) { X509CRLEntry entry = (X509CRLEntry)it.next(); ASN1InputStream aIn = new ASN1InputStream(entry.getEncoded()); try { tbsGen.addCRLEntry(ASN1Sequence.getInstance(aIn.readObject())); } catch (IOException e) { throw new CRLException("exception processing encoding of CRL: " + e.toString()); } } } }
/** * generate an X509 CRL, based on the current issuer and subject * using the default provider and an user defined SecureRandom object as * source of randomness. * <p> * <b>Note:</b> this differs from the deprecated method in that the default provider is * used - not "BC". * </p> */ public X509CRL generate( PrivateKey key, SecureRandom random) throws CRLException, IllegalStateException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { TBSCertList tbsCrl = generateCertList(); byte[] signature; try { signature = X509Util.calculateSignature(sigOID, signatureAlgorithm, key, random, tbsCrl); } catch (IOException e) { throw new ExtCRLException("cannot generate CRL encoding", e); } return generateJcaObject(tbsCrl, signature); }
/** {@inheritDoc} */ @Override public void check(final X509Certificate cert) throws GeneralSecurityException { if (cert == null) { throw new IllegalArgumentException("Certificate cannot be null."); } logger.debug("Evaluating certificate revocation status for {}", CertUtils.toString(cert)); final X509CRL crl = getCRL(cert); if (crl == null) { logger.warn("CRL data is not available for {}", CertUtils.toString(cert)); this.unavailableCRLPolicy.apply(null); return; } if (CertUtils.isExpired(crl)) { logger.warn("CRL data expired on ", crl.getNextUpdate()); this.expiredCRLPolicy.apply(crl); } final X509CRLEntry entry = crl.getRevokedCertificate(cert); if (entry != null) { throw new RevokedCertificateException(entry); } }
protected static PublicKey processCRLG( X509CRL crl, Set keys) throws AnnotatedException { Exception lastException = null; for (Iterator it = keys.iterator(); it.hasNext();) { PublicKey key = (PublicKey)it.next(); try { crl.verify(key); return key; } catch (Exception e) { lastException = e; } } throw new AnnotatedException("Cannot verify CRL.", lastException); }
/** * Read a bunch of CRLs from files and create a CertStore from them. * * @param relPath relative path containing CRLs (must end in file.separator) * @param fileNames an array of <code>String</code>s that are file names * @return the <code>CertStore</code> created * @throws Exception on error */ public static CertStore createCRLStore(String relPath, String [] fileNames) throws Exception { Set<X509CRL> crls = new HashSet<X509CRL>(); for (int i = 0; i < fileNames.length; i++) { crls.add(getCRLFromFile(relPath + fileNames[i])); } return CertStore.getInstance("Collection", new CollectionCertStoreParameters(crls)); }
/** * Checks if the specified X509CRL matches the criteria specified in the * CRLSelector. */ private static Collection<X509CRL> getMatchingCRLs (X509CRL crl, CRLSelector selector) { if (selector == null || (crl != null && selector.match(crl))) { return Collections.singletonList(crl); } else { return Collections.emptyList(); } }
/** * Get a DER-encoded X.509 CRL from a file. * * @param crlFilePath path to file containing DER-encoded CRL * @return the X509CRL * @throws CertificateException if the crl type is not supported * @throws CRLException if the crl cannot be parsed * @throws IOException if the file cannot be opened */ public static X509CRL getCRLFromFile(String crlFilePath) throws CertificateException, CRLException, IOException { File crlFile = new File(System.getProperty("test.src", "."), crlFilePath); try (FileInputStream fis = new FileInputStream(crlFile)) { return (X509CRL) CertificateFactory.getInstance("X.509").generateCRL(fis); } }
/** * Gets the first fetched CRL for the given certificate. * * @param cert Certificate for which the CRL of the issuing CA should be retrieved. * * @return CRL for given cert, or null */ public final X509CRL getCRL(final X509Certificate cert) { final Collection<X509CRL> list = getCRLs(cert); if (list != null && !list.isEmpty()) { return list.iterator().next(); } logger.debug("No CRL could be found for {}", CertUtils.toString(cert)); return null; }
@Override protected X509CRL fetchInternal(final Object r) throws Exception { if (r.toString().toLowerCase().startsWith("ldap")) { return fetchCRLFromLdap(r); } return super.fetchInternal(r); }
/** * Add CRL's from the specified collection to the list of certs and CRL's being collected * for the CertStore. * * @param storeMaterial list of certs and CRL's to be updated. * @param crls collection of CRL's to be processed * @param now current date/time */ protected void addCRLsToStoreMaterial(List<Object> storeMaterial, Collection<X509CRL> crls, Date now) { for (X509CRL crl : crls) { boolean isEmpty = crl.getRevokedCertificates() == null || crl.getRevokedCertificates().isEmpty(); boolean isExpired = crl.getNextUpdate().before(now); if (!isEmpty || options.isProcessEmptyCRLs()) { if (!isExpired || options.isProcessExpiredCRLs()) { storeMaterial.add(crl); if (log.isTraceEnabled()) { log.trace("Added X509CRL to cert store from issuer {} dated {}", x500DNHandler.getName(crl.getIssuerX500Principal()), crl.getThisUpdate()); if (isEmpty) { log.trace("X509CRL added to cert store from issuer {} dated {} was empty", x500DNHandler.getName(crl.getIssuerX500Principal()), crl.getThisUpdate()); } } if (isExpired) { log.warn("Using X509CRL from issuer {} with a nextUpdate in the past: {}", x500DNHandler.getName(crl.getIssuerX500Principal()), crl.getNextUpdate()); } } else { if (log.isTraceEnabled()) { log.trace("Expired X509CRL not added to cert store, from issuer {} nextUpdate {}", x500DNHandler.getName(crl.getIssuerX500Principal()), crl.getNextUpdate()); } } } else { if (log.isTraceEnabled()) { log.trace("Empty X509CRL not added to cert store, from issuer {} dated {}", x500DNHandler.getName(crl.getIssuerX500Principal()), crl.getThisUpdate()); } } } }
@Override public final Set<X509CRL> fetch(final Set<? extends Object> crls) throws Exception { final Set<X509CRL> results = new HashSet<>(); for (final Object r : crls) { logger.debug("Fetching CRL data from {}", r); final X509CRL crl = fetchInternal(r); if (crl != null) { results.add(crl); } } return results; }
public static X509CRL parseCrl(InputStream crlStream) throws CertificateException, CRLException { ParamUtil.requireNonNull("crlStream", crlStream); X509CRL crl = (X509CRL) getCertFactory().generateCRL(crlStream); if (crl == null) { throw new CRLException("the given one is not a valid X.509 CRL"); } return crl; }
/** * Returns the X.509 crls listed in this PKCS7 block. * @return a clone of the array of X.509 crls or null if none * are specified for the content type. */ public X509CRL[] getCRLs() { if (crls != null) return crls.clone(); else return null; }
/** * Returns CRLs described in a X509Certificate's CRLDistributionPoints * Extension. Only those containing a general name of type URI are read. */ public static List<CRL> readCRLsFromCert(X509Certificate cert) throws Exception { List<CRL> crls = new ArrayList<>(); CRLDistributionPointsExtension ext = X509CertImpl.toImpl(cert).getCRLDistributionPointsExtension(); if (ext == null) return crls; List<DistributionPoint> distPoints = ext.get(CRLDistributionPointsExtension.POINTS); for (DistributionPoint o: distPoints) { GeneralNames names = o.getFullName(); if (names != null) { for (GeneralName name: names.names()) { if (name.getType() == GeneralNameInterface.NAME_URI) { URIName uriName = (URIName)name.getName(); for (CRL crl: loadCRLs(uriName.getName())) { if (crl instanceof X509CRL) { crls.add((X509CRL)crl); } } break; // Different name should point to same CRL } } } } return crls; }
/** * Add fetched crls to the map. * * @param results the results */ private void addCrls(final Set<X509CRL> results) { final Iterator<X509CRL> it = results.iterator(); while (it.hasNext()) { final X509CRL entry = it.next(); addCRL(entry.getIssuerX500Principal(), entry); } }
/** * Builds an {@link org.opensaml.xml.signature.X509CRL} XMLObject from * a native Java {@link java.security.cert.X509CRL}. * * @param crl the Java {@link java.security.cert.X509CRL} to convert * @return a {@link org.opensaml.xml.signature.X509CRL} XMLObject * @throws CRLException thrown when there is an error converting the Java * CRL representation to the XMLObject representation */ public static org.opensaml.xml.signature.X509CRL buildX509CRL(X509CRL crl) throws CRLException { org.opensaml.xml.signature.X509CRL xmlCRL = (org.opensaml.xml.signature.X509CRL) Configuration.getBuilderFactory() .getBuilder(org.opensaml.xml.signature.X509CRL.DEFAULT_ELEMENT_NAME) .buildObject(org.opensaml.xml.signature.X509CRL.DEFAULT_ELEMENT_NAME); xmlCRL.setValue(Base64.encodeBytes(crl.getEncoded())); return xmlCRL; }
@Override public X509CRL fetch(final Object crl) throws Exception { final Set<X509CRL> results = fetch(Collections.singleton(crl)); if (results.size() > 0) { return results.iterator().next(); } logger.warn("Unable to fetch {}", crl); return null; }
/** * generate an X509 certificate, based on the current issuer and subject * using the passed in provider for the signing. */ public X509CRL generateX509CRL( PrivateKey key, String provider) throws NoSuchProviderException, SecurityException, SignatureException, InvalidKeyException { return generateX509CRL(key, provider, null); }
public CRLDistributionPointRevocationChecker(final boolean checkAll, final RevocationPolicy<Void> unavailableCRLPolicy, final RevocationPolicy<X509CRL> expiredCRLPolicy, final Cache crlCache, final CRLFetcher fetcher, final boolean throwOnFetchFailure) { super(checkAll, unavailableCRLPolicy, expiredCRLPolicy); this.crlCache = crlCache; this.fetcher = fetcher; this.throwOnFetchFailure = throwOnFetchFailure; }