Search in sources :

Example 6 with CRLEntry

use of org.bouncycastle.asn1.x509.TBSCertList.CRLEntry in project candlepin by candlepin.

the class X509CRLStreamWriterTest method testDeleteEntryFromCRL.

@Test
public void testDeleteEntryFromCRL() throws Exception {
    X509v2CRLBuilder crlBuilder = createCRLBuilder();
    crlBuilder.addCRLEntry(new BigInteger("101"), new Date(), CRLReason.unspecified);
    X509CRLHolder holder = crlBuilder.build(signer);
    File crlToChange = writeCRL(holder);
    CRLEntryValidator validator = new CRLEntryValidator() {

        @Override
        public boolean shouldDelete(CRLEntry entry) {
            return entry.getUserCertificate().getValue().equals(new BigInteger("101"));
        }
    };
    X509CRLStreamWriter stream = new X509CRLStreamWriter(crlToChange, (RSAPrivateKey) keyPair.getPrivate(), (RSAPublicKey) keyPair.getPublic());
    stream.add(new BigInteger("9000"), new Date(), 0);
    stream.preScan(crlToChange, validator).lock();
    OutputStream o = new BufferedOutputStream(new FileOutputStream(outfile));
    stream.write(o);
    o.close();
    X509CRL changedCrl = readCRL();
    Set<BigInteger> discoveredSerials = new HashSet<>();
    for (X509CRLEntry entry : changedCrl.getRevokedCertificates()) {
        discoveredSerials.add(entry.getSerialNumber());
    }
    Set<BigInteger> expected = new HashSet<>();
    expected.add(new BigInteger("100"));
    expected.add(new BigInteger("9000"));
    assertEquals(expected, discoveredSerials);
}
Also used : X509CRL(java.security.cert.X509CRL) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) X509CRLEntry(java.security.cert.X509CRLEntry) CRLEntry(org.bouncycastle.asn1.x509.TBSCertList.CRLEntry) Date(java.util.Date) X509CRLEntry(java.security.cert.X509CRLEntry) FileOutputStream(java.io.FileOutputStream) X509CRLHolder(org.bouncycastle.cert.X509CRLHolder) BigInteger(java.math.BigInteger) X509v2CRLBuilder(org.bouncycastle.cert.X509v2CRLBuilder) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 7 with CRLEntry

use of org.bouncycastle.asn1.x509.TBSCertList.CRLEntry in project XobotOS by xamarin.

the class X509CRLObject method loadCRLEntries.

private Set loadCRLEntries() {
    Set entrySet = new HashSet();
    Enumeration certs = c.getRevokedCertificateEnumeration();
    X500Principal previousCertificateIssuer = getIssuerX500Principal();
    while (certs.hasMoreElements()) {
        TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry) certs.nextElement();
        X509CRLEntryObject crlEntry = new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer);
        entrySet.add(crlEntry);
        previousCertificateIssuer = crlEntry.getCertificateIssuer();
    }
    return entrySet;
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) Enumeration(java.util.Enumeration) X500Principal(javax.security.auth.x500.X500Principal) TBSCertList(org.bouncycastle.asn1.x509.TBSCertList) X509CRLEntry(java.security.cert.X509CRLEntry) HashSet(java.util.HashSet)

Example 8 with CRLEntry

use of org.bouncycastle.asn1.x509.TBSCertList.CRLEntry in project robovm by robovm.

the class X509CRLObject method loadCRLEntries.

private Set loadCRLEntries() {
    Set entrySet = new HashSet();
    Enumeration certs = c.getRevokedCertificateEnumeration();
    // the issuer
    X500Name previousCertificateIssuer = null;
    while (certs.hasMoreElements()) {
        TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry) certs.nextElement();
        X509CRLEntryObject crlEntry = new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer);
        entrySet.add(crlEntry);
        if (isIndirect && entry.hasExtensions()) {
            Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer);
            if (currentCaName != null) {
                previousCertificateIssuer = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName());
            }
        }
    }
    return entrySet;
}
Also used : Extension(org.bouncycastle.asn1.x509.Extension) HashSet(java.util.HashSet) Set(java.util.Set) Enumeration(java.util.Enumeration) TBSCertList(org.bouncycastle.asn1.x509.TBSCertList) X500Name(org.bouncycastle.asn1.x500.X500Name) X509CRLEntry(java.security.cert.X509CRLEntry) HashSet(java.util.HashSet)

Example 9 with CRLEntry

use of org.bouncycastle.asn1.x509.TBSCertList.CRLEntry in project candlepin by candlepin.

the class X509CRLStreamWriter method preScan.

public synchronized X509CRLStreamWriter preScan(InputStream crlToChange, CRLEntryValidator validator) throws IOException {
    if (locked) {
        throw new IllegalStateException("Cannot modify a locked stream.");
    }
    if (preScanned) {
        throw new IllegalStateException("preScan has already been run.");
    }
    X509CRLEntryStream reaperStream = null;
    ASN1InputStream asn1In = null;
    try {
        reaperStream = new X509CRLEntryStream(crlToChange);
        if (!reaperStream.hasNext()) {
            emptyCrl = true;
            preScanned = true;
            return this;
        }
        while (reaperStream.hasNext()) {
            CRLEntry entry = reaperStream.next();
            if (validator != null && validator.shouldDelete(entry)) {
                // Get the serial number
                deletedEntries.add(entry.getUserCertificate().getValue());
                deletedEntriesLength += entry.getEncoded().length;
            }
        }
        /* At this point, crlToChange is at the point where the crlExtensions would
             * be.  RFC 5280 says that "Conforming CRL issuers are REQUIRED to include
             * the authority key identifier (Section 5.2.1) and the CRL number (Section 5.2.3)
             * extensions in all CRLs issued.
             */
        byte[] oldExtensions = null;
        ASN1Primitive o;
        asn1In = new ASN1InputStream(crlToChange);
        while ((o = asn1In.readObject()) != null) {
            if (o instanceof ASN1Sequence) {
                // Now we are at the signatureAlgorithm
                ASN1Sequence seq = (ASN1Sequence) o;
                if (seq.getObjectAt(0) instanceof ASN1ObjectIdentifier) {
                    // It's possible an algorithm has already been set using setSigningAlgorithm()
                    if (signingAlg == null) {
                        signingAlg = AlgorithmIdentifier.getInstance(seq);
                    }
                    try {
                        // Build the signer
                        this.signer = createContentSigner(signingAlg, key);
                    } catch (OperatorCreationException e) {
                        throw new IOException("Could not create ContentSigner for " + signingAlg.getAlgorithm());
                    }
                }
            } else if (o instanceof ASN1BitString) {
                oldSigLength = o.getEncoded().length;
            } else {
                if (oldExtensions != null) {
                    throw new IllegalStateException("Already read in CRL extensions.");
                }
                oldExtensions = o.getEncoded();
            }
        }
        if (oldExtensions == null) {
            /* v1 CRLs (defined in RFC 1422) don't require extensions but all new
                 * CRLs should be v2 (defined in RFC 5280).  In the extremely unlikely
                 * event that someone is working with a v1 CRL, we handle it here although
                 * we print a warning.
                 */
            preScanned = true;
            newExtensions = null;
            extensionsDelta = 0;
            log.warn("The CRL you are modifying is a version 1 CRL." + " Please investigate moving to a version 2 CRL by adding the CRL Number" + " and Authority Key Identifier extensions.");
            return this;
        }
        newExtensions = updateExtensions(oldExtensions);
        // newExtension and oldExtensions have already been converted to DER so any difference
        // in the length of the L bytes will be accounted for in the overall difference between
        // the length of the two byte arrays.
        extensionsDelta = newExtensions.length - oldExtensions.length;
    } finally {
        if (reaperStream != null) {
            reaperStream.close();
        }
        IOUtils.closeQuietly(asn1In);
    }
    preScanned = true;
    return this;
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) CRLEntry(org.bouncycastle.asn1.x509.TBSCertList.CRLEntry) IOException(java.io.IOException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) ASN1BitString(org.bouncycastle.asn1.ASN1BitString)

Example 10 with CRLEntry

use of org.bouncycastle.asn1.x509.TBSCertList.CRLEntry in project candlepin by candlepin.

the class CrlFileUtil method updateCRLFile.

/**
 * Updates the specified CRL file by adding or removing entries. If both lists are either null
 * or empty, the CRL file will not be modified by this method. If the file does not exist or
 * appears to be empty, it will be initialized before processing the lists.
 *
 * @param file
 *  The CRL file to update
 *
 * @param revoke
 *  A collection of serials to revoke (add)
 *
 * @param unrevoke
 *  A collection of serials to unrevoke (remove)
 *
 * @throws IOException
 *  if an IO error occurs while updating the CRL file
 */
public void updateCRLFile(File file, final Collection<BigInteger> revoke, final Collection<BigInteger> unrevoke) throws IOException {
    if (!file.exists() || file.length() == 0) {
        this.initializeCRLFile(file, revoke);
        return;
    }
    File strippedFile = stripCRLFile(file);
    InputStream input = null;
    InputStream reaper = null;
    BufferedOutputStream output = null;
    OutputStream filter = null;
    OutputStream encoder = null;
    try {
        // Impl note:
        // Due to the way the X509CRLStreamWriter works (and the DER format in general), we have
        // to make two passes through the file.
        input = new Base64InputStream(new FileInputStream(strippedFile));
        reaper = new Base64InputStream(new FileInputStream(strippedFile));
        // Note: This will break if we ever stop using RSA keys
        PrivateKey key = this.certificateReader.getCaKey();
        X509CRLStreamWriter writer = new X509CRLStreamWriter(input, (RSAPrivateKey) key, this.certificateReader.getCACert());
        // Add new entries
        if (revoke != null) {
            Date now = new Date();
            for (BigInteger serial : revoke) {
                writer.add(serial, now, CRLReason.privilegeWithdrawn);
            }
        }
        // or we could miss cases where we have entries to remove, but nothing to add.
        if (unrevoke != null && !unrevoke.isEmpty()) {
            writer.preScan(reaper, new CRLEntryValidator() {

                public boolean shouldDelete(CRLEntry entry) {
                    BigInteger certSerial = entry.getUserCertificate().getValue();
                    return unrevoke.contains(certSerial);
                }
            });
        } else {
            writer.preScan(reaper);
        }
        writer.setSigningAlgorithm(PKIUtility.SIGNATURE_ALGO);
        // Verify we actually have work to do now
        if (writer.hasChangesQueued()) {
            output = new BufferedOutputStream(new FileOutputStream(file));
            filter = new FilterOutputStream(output) {

                private boolean needsLineBreak = true;

                public void write(int b) throws IOException {
                    this.needsLineBreak = (b != (byte) '\n');
                    super.write(b);
                }

                public void write(byte[] buffer) throws IOException {
                    this.needsLineBreak = (buffer[buffer.length - 1] != (byte) '\n');
                    super.write(buffer);
                }

                public void write(byte[] buffer, int off, int len) throws IOException {
                    this.needsLineBreak = (buffer[off + len - 1] != (byte) '\n');
                    super.write(buffer, off, len);
                }

                public void close() throws IOException {
                    if (this.needsLineBreak) {
                        super.write((int) '\n');
                        this.needsLineBreak = false;
                    }
                // Impl note:
                // We're intentionally not propagating the call here.
                }
            };
            encoder = new Base64OutputStream(filter, true, 76, new byte[] { (byte) '\n' });
            output.write("-----BEGIN X509 CRL-----\n".getBytes());
            writer.lock();
            writer.write(encoder);
            encoder.close();
            filter.close();
            output.write("-----END X509 CRL-----\n".getBytes());
            output.close();
        }
    } catch (GeneralSecurityException e) {
        // This should never actually happen
        log.error("Unexpected security error occurred while retrieving CA key", e);
    } catch (CryptoException e) {
        // Something went horribly wrong with the stream writer
        log.error("Unexpected error occurred while writing new CRL file", e);
    } finally {
        for (Closeable stream : Arrays.asList(encoder, output, reaper, input)) {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    log.error("Unexpected exception occurred while closing stream: {}", stream, e);
                }
            }
        }
        if (!strippedFile.delete()) {
            log.error("Unable to delete temporary CRL file: {}", strippedFile);
        }
    }
}
Also used : RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) FileInputStream(java.io.FileInputStream) Base64InputStream(org.apache.commons.codec.binary.Base64InputStream) InputStream(java.io.InputStream) BufferedOutputStream(java.io.BufferedOutputStream) Base64OutputStream(org.apache.commons.codec.binary.Base64OutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FilterOutputStream(java.io.FilterOutputStream) GeneralSecurityException(java.security.GeneralSecurityException) Closeable(java.io.Closeable) CRLEntry(org.bouncycastle.asn1.x509.TBSCertList.CRLEntry) IOException(java.io.IOException) Base64OutputStream(org.apache.commons.codec.binary.Base64OutputStream) FileInputStream(java.io.FileInputStream) Date(java.util.Date) FileOutputStream(java.io.FileOutputStream) BigInteger(java.math.BigInteger) Base64InputStream(org.apache.commons.codec.binary.Base64InputStream) FilterOutputStream(java.io.FilterOutputStream) CryptoException(org.bouncycastle.crypto.CryptoException) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream)

Aggregations

X509CRLEntry (java.security.cert.X509CRLEntry)7 Enumeration (java.util.Enumeration)5 TBSCertList (org.bouncycastle.asn1.x509.TBSCertList)5 IOException (java.io.IOException)4 HashSet (java.util.HashSet)4 File (java.io.File)3 BigInteger (java.math.BigInteger)3 Date (java.util.Date)3 Set (java.util.Set)3 X500Principal (javax.security.auth.x500.X500Principal)3 BufferedOutputStream (java.io.BufferedOutputStream)2 FileOutputStream (java.io.FileOutputStream)2 OutputStream (java.io.OutputStream)2 X509CRL (java.security.cert.X509CRL)2 X509Certificate (java.security.cert.X509Certificate)2 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)2 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)2 DERIA5String (org.bouncycastle.asn1.DERIA5String)2 DEROctetString (org.bouncycastle.asn1.DEROctetString)2 X500Name (org.bouncycastle.asn1.x500.X500Name)2