Search in sources :

Example 1 with Attribute

use of org.bouncycastle.asn1.x509.Attribute in project OpenAttestation by OpenAttestation.

the class X509AttributeCertificate method valueOf.

/**
     *
     * @param encodedCertificate
     * @return
     */
@JsonCreator
public static X509AttributeCertificate valueOf(@JsonProperty("encoded") byte[] encodedCertificate) {
    X509AttributeCertificate result = new X509AttributeCertificate(encodedCertificate);
    X509AttributeCertificateHolder cert;
    try {
        cert = new X509AttributeCertificateHolder(encodedCertificate);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
    // calls toString() on each X500Name so we get the default representation; we can do it ourselves for custom display;  output example: CN=Attr CA,OU=CPG,OU=DCSG,O=Intel,ST=CA,C=US
    log.debug("issuer: {}", StringUtils.join(cert.getIssuer().getNames(), "; "));
    // but expected to be only one
    result.issuer = StringUtils.join(cert.getIssuer().getNames(), "; ");
    // output example:   1
    log.debug("serial number: {}", cert.getSerialNumber().toString());
    result.serialNumber = cert.getSerialNumber();
    // output example:  2.25=#041092a71a228c174522a18bfd3ed3d00b39
    log.debug("holder: {}", StringUtils.join(cert.getHolder().getEntityNames(), ", "));
    // now let's get the UUID specifically out of this
    log.debug("holder has {} entity names", cert.getHolder().getEntityNames().length);
    for (X500Name entityName : cert.getHolder().getEntityNames()) {
        log.debug("holder entity name has {} rdns", entityName.getRDNs().length);
        for (RDN rdn : entityName.getRDNs()) {
            log.debug("entity rdn is multivalued? {}", rdn.isMultiValued());
            AttributeTypeAndValue attr = rdn.getFirst();
            if (attr.getType().toString().equals(OID.HOST_UUID)) {
                UUID uuid = UUID.valueOf(DEROctetString.getInstance(attr.getValue()).getOctets());
                log.debug("holder uuid: {}", uuid);
                // example: 33766a63-5c55-4461-8a84-5936577df450
                result.subject = uuid.toString();
            }
        }
    }
    // if we ddin't identify the UUID,  just display the subject same way we did the issuer... concat all the entity names. example: 2.25=#041033766a635c5544618a845936577df450  (notice that in the value, there's a #0410 prepended to the uuid 33766a635c5544618a845936577df450)
    if (result.subject == null) {
        result.subject = StringUtils.join(cert.getHolder().getEntityNames(), "; ");
    }
    // output example: Thu Aug 08 15:21:13 PDT 2013
    log.debug("not before: {}", cert.getNotBefore());
    // output example: Sun Sep 08 15:21:13 PDT 2013
    log.debug("not after: {}", cert.getNotAfter());
    result.notBefore = cert.getNotBefore();
    result.notAfter = cert.getNotAfter();
    Attribute[] attributes = cert.getAttributes();
    result.tags1 = new ArrayList<UTF8NameValueMicroformat>();
    result.tags2 = new ArrayList<UTF8NameValueSequence>();
    result.tagsOther = new ArrayList<ASN1Encodable>();
    for (Attribute attr : attributes) {
        log.debug("attr {} is {}", attr.hashCode(), attr.toString());
        result.attributes.add(attr);
        for (ASN1Encodable value : attr.getAttributeValues()) {
            //                result.tags.add(new AttributeOidAndValue(attr.getAttrType().toString(), DERUTF8String.getInstance(value).getString()));
            if (attr.getAttrType().toString().equals(UTF8NameValueMicroformat.OID)) {
                // our values are just UTF-8 strings  but if you use new String(value.getEncoded())  you will get two extra spaces at the beginning of the string                    
                log.debug("name-value microformat attribute: {}", DERUTF8String.getInstance(value).getString());
                UTF8NameValueMicroformat microformat = new UTF8NameValueMicroformat(DERUTF8String.getInstance(value));
                log.debug("name-value microformat attribute (2)  name {} value {}", microformat.getName(), microformat.getValue());
                result.tags1.add(microformat);
            } else if (attr.getAttrType().toString().equals(UTF8NameValueSequence.OID)) {
                UTF8NameValueSequence sequence = new UTF8NameValueSequence(ASN1Sequence.getInstance(value));
                String name = sequence.getName();
                List<String> values = sequence.getValues();
                log.debug("name-values asn.1 attribute {} values {}", name, values);
                result.tags2.add(sequence);
            } else {
                log.debug("unrecognzied attribute type {}", attr.getAttrType().toString());
                result.tagsOther.add(value);
            }
        /*
                 * output examples:
                 * attribute: 1.3.6.1.4.1.99999.1.1.1.1 is US
                 * attribute: 1.3.6.1.4.1.99999.2.2.2.2 is CA
                 * attribute: 1.3.6.1.4.1.99999.3.3.3.3 is Folsom
                 */
        }
    }
    log.debug("valueOf ok");
    return result;
}
Also used : Attribute(org.bouncycastle.asn1.x509.Attribute) X509AttributeCertificateHolder(org.bouncycastle.cert.X509AttributeCertificateHolder) IOException(java.io.IOException) X500Name(org.bouncycastle.asn1.x500.X500Name) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) AttributeTypeAndValue(org.bouncycastle.asn1.x500.AttributeTypeAndValue) ArrayList(java.util.ArrayList) List(java.util.List) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) UUID(com.intel.mtwilson.util.io.UUID) RDN(org.bouncycastle.asn1.x500.RDN) JsonCreator(org.codehaus.jackson.annotate.JsonCreator)

Example 2 with Attribute

use of org.bouncycastle.asn1.x509.Attribute in project OpenAttestation by OpenAttestation.

the class CertificateRepository method create.

@Override
public //    @RequiresPermissions("tag_certificates:create") 
void create(Certificate item) {
    log.debug("Certificate:Create - Got request to create a new Certificate {}.", item.getId().toString());
    CertificateLocator locator = new CertificateLocator();
    locator.id = item.getId();
    try (CertificateDAO dao = TagJdbi.certificateDao()) {
        Certificate newCert = dao.findById(item.getId());
        if (newCert == null) {
            newCert = Certificate.valueOf(item.getCertificate());
            dao.insert(item.getId(), newCert.getCertificate(), newCert.getSha1().toHexString(), newCert.getSha256().toHexString(), newCert.getSubject(), newCert.getIssuer(), newCert.getNotBefore(), newCert.getNotAfter());
            log.debug("Certificate:Create - Created the Certificate {} successfully.", item.getId().toString());
        } else {
            log.error("Certificate:Create - Certificate {} will not be created since a duplicate Certificate already exists.", item.getId().toString());
            throw new RepositoryCreateConflictException(locator);
        }
    } catch (RepositoryException re) {
        throw re;
    } catch (Exception ex) {
        log.error("Certificate:Create - Error during certificate creation.", ex);
        throw new RepositoryCreateException(ex, locator);
    }
    //Store tag values from Certificate
    try {
        log.info("Tags from certificate will now be stored");
        KvAttributeRepository repository = new KvAttributeRepository();
        KvAttribute kvAttrib = new KvAttribute();
        if (kvAttrib == null || repository == null)
            log.debug("kvAttrib or repository Obj is null, unable to store certificate tags");
        else {
            List<Attribute> certAttributes = X509AttributeCertificate.valueOf(item.getCertificate()).getAttribute();
            for (Attribute attr : certAttributes) {
                for (ASN1Encodable value : attr.getAttributeValues()) {
                    if (attr.getAttrType().toString().equals(UTF8NameValueMicroformat.OID)) {
                        UTF8NameValueMicroformat microformat = new UTF8NameValueMicroformat(DERUTF8String.getInstance(value));
                        // Check if that tag with same value already exists
                        KvAttributeFilterCriteria criteria = new KvAttributeFilterCriteria();
                        criteria.nameEqualTo = microformat.getName();
                        criteria.valueEqualTo = microformat.getValue();
                        KvAttributeCollection results = repository.search(criteria);
                        if (results.getDocuments().isEmpty()) {
                            kvAttrib.setId(new UUID());
                            kvAttrib.setName(microformat.getName());
                            kvAttrib.setValue(microformat.getValue());
                            repository.create(kvAttrib);
                        } else
                            log.debug("Tag with Name:{} & Value:{} is already stored.", microformat.getName(), microformat.getValue());
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error("Certificate:Create - Error during attribute scan", e);
    }
}
Also used : CertificateLocator(com.intel.mtwilson.datatypes.CertificateLocator) CertificateDAO(com.intel.mtwilson.tag.dao.jdbi.CertificateDAO) KvAttribute(com.intel.mtwilson.datatypes.KvAttribute) Attribute(org.bouncycastle.asn1.x509.Attribute) KvAttribute(com.intel.mtwilson.datatypes.KvAttribute) RepositoryException(com.intel.mtwilson.tag.repository.RepositoryException) RepositoryCreateConflictException(com.intel.mtwilson.tag.repository.RepositoryCreateConflictException) RepositoryCreateException(com.intel.mtwilson.tag.repository.RepositoryCreateException) RepositoryDeleteException(com.intel.mtwilson.tag.repository.RepositoryDeleteException) RepositoryStoreException(com.intel.mtwilson.tag.repository.RepositoryStoreException) RepositoryStoreConflictException(com.intel.mtwilson.tag.repository.RepositoryStoreConflictException) RepositoryRetrieveException(com.intel.mtwilson.tag.repository.RepositoryRetrieveException) RepositoryException(com.intel.mtwilson.tag.repository.RepositoryException) RepositorySearchException(com.intel.mtwilson.tag.repository.RepositorySearchException) RepositoryCreateConflictException(com.intel.mtwilson.tag.repository.RepositoryCreateConflictException) KvAttributeCollection(com.intel.mtwilson.datatypes.KvAttributeCollection) KvAttributeRepository(com.intel.mtwilson.tag.repository.KvAttributeRepository) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) KvAttributeFilterCriteria(com.intel.mtwilson.datatypes.KvAttributeFilterCriteria) UUID(com.intel.mtwilson.util.io.UUID) UTF8NameValueMicroformat(com.intel.mtwilson.datatypes.UTF8NameValueMicroformat) Certificate(com.intel.mtwilson.datatypes.Certificate) X509AttributeCertificate(com.intel.mtwilson.datatypes.X509AttributeCertificate) RepositoryCreateException(com.intel.mtwilson.tag.repository.RepositoryCreateException)

Example 3 with Attribute

use of org.bouncycastle.asn1.x509.Attribute in project OpenAttestation by OpenAttestation.

the class ProvisionTagCertificate method certificateAttributesEqual.

//    
//    /**
//     * Check that the attributes in the certificate are the same as the attributes in the given selection.
//     * The order is not considered so they do not have to be in the same order.
//     * 
//     * The given selection must have inline attributes (not requiring any lookup by id or name).
//     * 
//     * @return true if the attribute certificate has exactly the same attributes as in the given selection
//     */
protected boolean certificateAttributesEqual(X509AttributeCertificate certificate, SelectionType selection) throws IOException {
    List<Attribute> certAttributes = certificate.getAttribute();
    // initialized with all false, later we mark individual elements true if they are found within the given selection, so that if any are left false at the end we know that there are attributes in the cert that were not in the selection
    boolean[] certAttrMatch = new boolean[certAttributes.size()];
    // for every attribute in the selection, check if it's present in the certificate 
    for (AttributeType xmlAttribute : selection.getAttribute()) {
        X509AttrBuilder.Attribute oidAndValue = Util.toAttributeOidValue(xmlAttribute);
        // look through the certificate for same oid and value
        boolean found = false;
        for (int i = 0; i < certAttrMatch.length; i++) {
            if (Arrays.equals(certAttributes.get(i).getAttrType().getDEREncoded(), oidAndValue.oid.getDEREncoded())) {
                if (Arrays.equals(certAttributes.get(i).getAttributeValues()[0].getDEREncoded(), oidAndValue.value.getDEREncoded())) {
                    certAttrMatch[i] = true;
                    found = true;
                }
            }
        }
        if (!found) {
            log.debug("Certificate does not have attribute oid {} and value {}", Hex.encodeHexString(oidAndValue.oid.getDEREncoded()), Hex.encodeHexString(oidAndValue.value.getDEREncoded()));
            return false;
        }
    }
    // check if the certificate has any attributes that are not in the selection 
    for (int i = 0; i < certAttrMatch.length; i++) {
        if (!certAttrMatch[i]) {
            log.debug("Selection does not have attribute oid {} and value {}", Hex.encodeHexString(certAttributes.get(i).getAttrType().getDEREncoded()), Hex.encodeHexString(certAttributes.get(i).getAttributeValues()[0].getDEREncoded()));
            return false;
        }
    }
    // certificate and selection have same set of attribute (oid,value) pairs
    return true;
}
Also used : Attribute(org.bouncycastle.asn1.x509.Attribute) AttributeType(com.intel.mtwilson.tag.selection.xml.AttributeType) X509AttrBuilder(com.intel.mtwilson.tag.common.X509AttrBuilder)

Example 4 with Attribute

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

the class RFC3280CertPathUtilities method processCRLF.

/**
     * Obtain and validate the certification path for the complete CRL issuer.
     * If a key usage extension is present in the CRL issuer's certificate,
     * verify that the cRLSign bit is set.
     *
     * @param crl                CRL which contains revocation information for the certificate
     *                           <code>cert</code>.
     * @param cert               The attribute certificate or certificate to check if it is
     *                           revoked.
     * @param defaultCRLSignCert The issuer certificate of the certificate <code>cert</code>.
     * @param defaultCRLSignKey  The public key of the issuer certificate
     *                           <code>defaultCRLSignCert</code>.
     * @param paramsPKIX         paramsPKIX PKIX parameters.
     * @param certPathCerts      The certificates on the certification path.
     * @return A <code>Set</code> with all keys of possible CRL issuer
     *         certificates.
     * @throws AnnotatedException if the CRL is not valid or the status cannot be checked or
     *                            some error occurs.
     */
protected static Set processCRLF(X509CRL crl, Object cert, X509Certificate defaultCRLSignCert, PublicKey defaultCRLSignKey, ExtendedPKIXParameters paramsPKIX, List certPathCerts) throws AnnotatedException {
    // (f)
    // get issuer from CRL
    X509CertStoreSelector selector = new X509CertStoreSelector();
    try {
        byte[] issuerPrincipal = CertPathValidatorUtilities.getIssuerPrincipal(crl).getEncoded();
        selector.setSubject(issuerPrincipal);
    } catch (IOException e) {
        throw new AnnotatedException("Subject criteria for certificate selector to find issuer certificate for CRL could not be set.", e);
    }
    // get CRL signing certs
    Collection coll;
    try {
        coll = CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getStores());
        coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getAdditionalStores()));
        coll.addAll(CertPathValidatorUtilities.findCertificates(selector, paramsPKIX.getCertStores()));
    } catch (AnnotatedException e) {
        throw new AnnotatedException("Issuer certificate for CRL cannot be searched.", e);
    }
    coll.add(defaultCRLSignCert);
    Iterator cert_it = coll.iterator();
    List validCerts = new ArrayList();
    List validKeys = new ArrayList();
    while (cert_it.hasNext()) {
        X509Certificate signingCert = (X509Certificate) cert_it.next();
        /*
             * CA of the certificate, for which this CRL is checked, has also
             * signed CRL, so skip the path validation, because is already done
             */
        if (signingCert.equals(defaultCRLSignCert)) {
            validCerts.add(signingCert);
            validKeys.add(defaultCRLSignKey);
            continue;
        }
        try {
            CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BouncyCastleProvider.PROVIDER_NAME);
            selector = new X509CertStoreSelector();
            selector.setCertificate(signingCert);
            ExtendedPKIXParameters temp = (ExtendedPKIXParameters) paramsPKIX.clone();
            temp.setTargetCertConstraints(selector);
            ExtendedPKIXBuilderParameters params = (ExtendedPKIXBuilderParameters) ExtendedPKIXBuilderParameters.getInstance(temp);
            /*
                 * if signingCert is placed not higher on the cert path a
                 * dependency loop results. CRL for cert is checked, but
                 * signingCert is needed for checking the CRL which is dependent
                 * on checking cert because it is higher in the cert path and so
                 * signing signingCert transitively. so, revocation is disabled,
                 * forgery attacks of the CRL are detected in this outer loop
                 * for all other it must be enabled to prevent forgery attacks
                 */
            if (certPathCerts.contains(signingCert)) {
                params.setRevocationEnabled(false);
            } else {
                params.setRevocationEnabled(true);
            }
            List certs = builder.build(params).getCertPath().getCertificates();
            validCerts.add(signingCert);
            validKeys.add(CertPathValidatorUtilities.getNextWorkingKey(certs, 0));
        } catch (CertPathBuilderException e) {
            throw new AnnotatedException("Internal error.", e);
        } catch (CertPathValidatorException e) {
            throw new AnnotatedException("Public key of issuer certificate of CRL could not be retrieved.", e);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
    Set checkKeys = new HashSet();
    AnnotatedException lastException = null;
    for (int i = 0; i < validCerts.size(); i++) {
        X509Certificate signCert = (X509Certificate) validCerts.get(i);
        boolean[] keyusage = signCert.getKeyUsage();
        if (keyusage != null && (keyusage.length < 7 || !keyusage[CRL_SIGN])) {
            lastException = new AnnotatedException("Issuer certificate key usage extension does not permit CRL signing.");
        } else {
            checkKeys.add(validKeys.get(i));
        }
    }
    if (checkKeys.isEmpty() && lastException == null) {
        throw new AnnotatedException("Cannot find a valid issuer certificate.");
    }
    if (checkKeys.isEmpty() && lastException != null) {
        throw lastException;
    }
    return checkKeys;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) ExtendedPKIXBuilderParameters(org.bouncycastle.x509.ExtendedPKIXBuilderParameters) X509CertStoreSelector(org.bouncycastle.x509.X509CertStoreSelector) ArrayList(java.util.ArrayList) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) CertificateExpiredException(java.security.cert.CertificateExpiredException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertPathBuilderException(java.security.cert.CertPathBuilderException) IOException(java.io.IOException) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) ExtendedPKIXParameters(org.bouncycastle.x509.ExtendedPKIXParameters) CertPathBuilderException(java.security.cert.CertPathBuilderException) Iterator(java.util.Iterator) Collection(java.util.Collection) List(java.util.List) ArrayList(java.util.ArrayList) CertPathBuilder(java.security.cert.CertPathBuilder) HashSet(java.util.HashSet)

Example 5 with Attribute

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

the class RFC3280CertPathUtilities method processCRLB1.

/**
     * If the DP includes cRLIssuer, then verify that the issuer field in the
     * complete CRL matches cRLIssuer in the DP and that the complete CRL
     * contains an issuing distribution point extension with the indirectCRL
     * boolean asserted. Otherwise, verify that the CRL issuer matches the
     * certificate issuer.
     *
     * @param dp   The distribution point.
     * @param cert The certificate ot attribute certificate.
     * @param crl  The CRL for <code>cert</code>.
     * @throws AnnotatedException if one of the above conditions does not apply or an error
     *                            occurs.
     */
protected static void processCRLB1(DistributionPoint dp, Object cert, X509CRL crl) throws AnnotatedException {
    DERObject idp = CertPathValidatorUtilities.getExtensionValue(crl, ISSUING_DISTRIBUTION_POINT);
    boolean isIndirect = false;
    if (idp != null) {
        if (IssuingDistributionPoint.getInstance(idp).isIndirectCRL()) {
            isIndirect = true;
        }
    }
    byte[] issuerBytes = CertPathValidatorUtilities.getIssuerPrincipal(crl).getEncoded();
    boolean matchIssuer = false;
    if (dp.getCRLIssuer() != null) {
        GeneralName[] genNames = dp.getCRLIssuer().getNames();
        for (int j = 0; j < genNames.length; j++) {
            if (genNames[j].getTagNo() == GeneralName.directoryName) {
                try {
                    if (Arrays.areEqual(genNames[j].getName().getDERObject().getEncoded(), issuerBytes)) {
                        matchIssuer = true;
                    }
                } catch (IOException e) {
                    throw new AnnotatedException("CRL issuer information from distribution point cannot be decoded.", e);
                }
            }
        }
        if (matchIssuer && !isIndirect) {
            throw new AnnotatedException("Distribution point contains cRLIssuer field but CRL is not indirect.");
        }
        if (!matchIssuer) {
            throw new AnnotatedException("CRL issuer of CRL does not match CRL issuer of distribution point.");
        }
    } else {
        if (CertPathValidatorUtilities.getIssuerPrincipal(crl).equals(CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert))) {
            matchIssuer = true;
        }
    }
    if (!matchIssuer) {
        throw new AnnotatedException("Cannot find matching CRL issuer for certificate.");
    }
}
Also used : DERObject(org.bouncycastle.asn1.DERObject) GeneralName(org.bouncycastle.asn1.x509.GeneralName) IOException(java.io.IOException) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint)

Aggregations

Attribute (org.jdom2.Attribute)149 Element (org.jdom2.Element)104 IOException (java.io.IOException)42 ArrayList (java.util.ArrayList)38 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)33 Attribute (org.bouncycastle.asn1.cms.Attribute)29 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)26 X509Certificate (java.security.cert.X509Certificate)25 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)23 Test (org.junit.Test)22 DERSequence (org.bouncycastle.asn1.DERSequence)20 DERSet (org.bouncycastle.asn1.DERSet)20 List (java.util.List)19 Attribute (org.bouncycastle.asn1.pkcs.Attribute)18 Document (org.jdom2.Document)18 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)17 DataConversionException (org.jdom2.DataConversionException)16 Editor (jmri.jmrit.display.Editor)15 CertificateEncodingException (java.security.cert.CertificateEncodingException)14 ASN1Set (org.bouncycastle.asn1.ASN1Set)14