Search in sources :

Example 1 with CertificateCollection

use of com.intel.mtwilson.datatypes.CertificateCollection in project OpenAttestation by OpenAttestation.

the class CertificateRepository method search.

@Override
public //    @RequiresPermissions("tag_certificates:search") 
CertificateCollection search(CertificateFilterCriteria criteria) {
    log.debug("Certificate:Search - Got request to search for the Certificates.");
    CertificateCollection objCollection = new CertificateCollection();
    try (JooqContainer jc = TagJdbi.jooq()) {
        DSLContext jooq = jc.getDslContext();
        SelectQuery sql = jooq.select().from(MW_TAG_CERTIFICATE).getQuery();
        if (criteria.filter) {
            if (criteria.id != null) {
                // when uuid is stored in database as the standard UUID string format (36 chars)
                sql.addConditions(MW_TAG_CERTIFICATE.ID.equalIgnoreCase(criteria.id.toString()));
            }
            if (criteria.subjectEqualTo != null && criteria.subjectEqualTo.length() > 0) {
                sql.addConditions(MW_TAG_CERTIFICATE.SUBJECT.equalIgnoreCase(criteria.subjectEqualTo));
            }
            if (criteria.subjectContains != null && criteria.subjectContains.length() > 0) {
                sql.addConditions(MW_TAG_CERTIFICATE.SUBJECT.lower().contains(criteria.subjectContains.toLowerCase()));
            }
            if (criteria.issuerEqualTo != null && criteria.issuerEqualTo.length() > 0) {
                sql.addConditions(MW_TAG_CERTIFICATE.ISSUER.equalIgnoreCase(criteria.issuerEqualTo));
            }
            if (criteria.issuerContains != null && criteria.issuerContains.length() > 0) {
                sql.addConditions(MW_TAG_CERTIFICATE.ISSUER.lower().contains(criteria.issuerContains.toLowerCase()));
            }
            if (criteria.sha1 != null) {
                sql.addConditions(MW_TAG_CERTIFICATE.SHA1.equalIgnoreCase(criteria.sha1.toHexString()));
            }
            if (criteria.sha256 != null) {
                sql.addConditions(MW_TAG_CERTIFICATE.SHA256.equalIgnoreCase(criteria.sha256.toHexString()));
            }
            if (criteria.validOn != null) {
                sql.addConditions(MW_TAG_CERTIFICATE.NOTBEFORE.lessOrEqual(new Timestamp(criteria.validOn.getTime())));
                sql.addConditions(MW_TAG_CERTIFICATE.NOTAFTER.greaterOrEqual(new Timestamp(criteria.validOn.getTime())));
            }
            if (criteria.validBefore != null) {
                sql.addConditions(MW_TAG_CERTIFICATE.NOTAFTER.greaterOrEqual(new Timestamp(criteria.validBefore.getTime())));
            }
            if (criteria.validAfter != null) {
                sql.addConditions(MW_TAG_CERTIFICATE.NOTBEFORE.lessOrEqual(new Timestamp(criteria.validAfter.getTime())));
            }
            if (criteria.revoked != null) {
                sql.addConditions(MW_TAG_CERTIFICATE.REVOKED.equal(criteria.revoked));
            }
        }
        sql.addOrderBy(MW_TAG_CERTIFICATE.SUBJECT);
        Result<Record> result = sql.fetch();
        log.debug("Got {} records", result.size());
        for (Record r : result) {
            Certificate certObj = new Certificate();
            try {
                certObj.setId(UUID.valueOf(r.getValue(MW_TAG_CERTIFICATE.ID)));
                // unlike other table queries, here we can get all the info from the certificate itself... except for the revoked flag
                certObj.setCertificate((byte[]) r.getValue(MW_TAG_CERTIFICATE.CERTIFICATE));
                certObj.setIssuer(r.getValue(MW_TAG_CERTIFICATE.ISSUER));
                certObj.setSubject(r.getValue(MW_TAG_CERTIFICATE.SUBJECT));
                certObj.setNotBefore(r.getValue(MW_TAG_CERTIFICATE.NOTBEFORE));
                certObj.setNotAfter(r.getValue(MW_TAG_CERTIFICATE.NOTAFTER));
                certObj.setSha1(Sha1Digest.valueOf(r.getValue(MW_TAG_CERTIFICATE.SHA1)));
                certObj.setSha256(Sha256Digest.valueOf(r.getValue(MW_TAG_CERTIFICATE.SHA256)));
                certObj.setRevoked(r.getValue(MW_TAG_CERTIFICATE.REVOKED));
                log.debug("Certificate:Search - Created certificate record in search result {}", certObj.getId().toString());
                objCollection.getCertificates().add(certObj);
            } catch (Exception e) {
                log.error("Certificate:Search - Cannot load certificate #{}", r.getValue(MW_TAG_CERTIFICATE.ID), e);
            }
        }
        sql.close();
    } catch (Exception ex) {
        log.error("Certificate:Search - Error during certificate search.", ex);
        throw new RepositorySearchException(ex, criteria);
    }
    log.debug("Certificate:Search - Returning back {} of results.", objCollection.getCertificates().size());
    return objCollection;
}
Also used : SelectQuery(org.jooq.SelectQuery) JooqContainer(com.intel.mtwilson.jooq.util.JooqContainer) CertificateCollection(com.intel.mtwilson.datatypes.CertificateCollection) DSLContext(org.jooq.DSLContext) Record(org.jooq.Record) RepositorySearchException(com.intel.mtwilson.tag.repository.RepositorySearchException) Timestamp(java.sql.Timestamp) 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) Certificate(com.intel.mtwilson.datatypes.Certificate) X509AttributeCertificate(com.intel.mtwilson.datatypes.X509AttributeCertificate)

Example 2 with CertificateCollection

use of com.intel.mtwilson.datatypes.CertificateCollection in project OpenAttestation by OpenAttestation.

the class CertificateRepository method delete.

@Override
public //    @RequiresPermissions("tag_certificates:delete,search") 
void delete(CertificateFilterCriteria criteria) {
    log.debug("Certificate:Delete - Got request to delete certificate by search criteria.");
    CertificateCollection objCollection = search(criteria);
    try {
        for (Certificate obj : objCollection.getCertificates()) {
            CertificateLocator locator = new CertificateLocator();
            locator.id = obj.getId();
            delete(locator);
        }
    } catch (RepositoryException re) {
        throw re;
    } catch (Exception ex) {
        log.error("Certificate:Delete - Error during Certificate deletion.", ex);
        throw new RepositoryDeleteException(ex);
    }
}
Also used : CertificateLocator(com.intel.mtwilson.datatypes.CertificateLocator) RepositoryDeleteException(com.intel.mtwilson.tag.repository.RepositoryDeleteException) CertificateCollection(com.intel.mtwilson.datatypes.CertificateCollection) RepositoryException(com.intel.mtwilson.tag.repository.RepositoryException) 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) Certificate(com.intel.mtwilson.datatypes.Certificate) X509AttributeCertificate(com.intel.mtwilson.datatypes.X509AttributeCertificate)

Example 3 with CertificateCollection

use of com.intel.mtwilson.datatypes.CertificateCollection in project OpenAttestation by OpenAttestation.

the class ProvisionTagCertificate method createOne.

//    
//    /**
//     * Returns the tag certificate bytes or null if one was not generated
//     * 
//     * @param subject
//     * @param selection may be null; the default selection will be used, if configured
//     * @param request
//     * @param response
//     * @return
//     * @throws IOException
//     */
public Certificate createOne(String subject, SelectionsType selections, HttpServletRequest request, HttpServletResponse response) throws IOException, ApiException, SignatureException, SQLException, IllegalArgumentException {
    //        TagConfiguration configuration = new TagConfiguration(My.configuration().getConfiguration());
    //        TagCertificateAuthority ca = new TagCertificateAuthority(configuration);
    TagConfiguration configuration = new TagConfiguration(ASConfig.getConfiguration());
    TagCertificateAuthority ca = new TagCertificateAuthority(configuration);
    // if the subject is an ip address or hostname, resolve it to a hardware uuid with mtwilson - if the host isn't registered in mtwilson we can't get the hardware uuid so we have to reject the request
    if (!UUID.isValid(subject)) {
        String subjectUuid = findSubjectHardwareUuid(subject);
        if (subjectUuid == null) {
            log.error("Cannot find hardware uuid for subject: {}", subject);
            throw new IllegalArgumentException("Invalid subject specified in the call");
        }
        subject = subjectUuid;
    }
    if (selections == null) {
        log.error("Selection input is null");
        throw new IllegalArgumentException("Invalid selections specified.");
    }
    // if external ca is configured then we only save the request to the database and indicate async processing in our response
    //        if( configuration.isTagProvisionExternal() || isAsync(request) ) {
    //            // requires async processing - we store the request, and an external ca will poll for requests, generate certs, and post the certs back to us; the client can periodically check the status and then download the cert when it's available
    //            storeAsyncRequest(subject, selections, response);
    //            return null;
    //        }
    // if always-generate/no-cache (cache mode off) is enabled then generate it right now and return it - no need to check database for existing certs etc. 
    String cacheMode = "on";
    if (selections.getOptions() != null && selections.getOptions().getCache() != null && selections.getOptions().getCache().getMode() != null) {
        cacheMode = selections.getOptions().getCache().getMode().value();
    }
    // first figure out which selection will be used for the given subject - also filters selections to ones that are currently valid or not marked with validity period
    // throws exception if there is no matching selection and no matching default selection
    SelectionType targetSelection = ca.findCurrentSelectionForSubject(UUID.valueOf(subject), selections);
    log.debug("Cache mode {}", cacheMode);
    if ("off".equals(cacheMode) && targetSelection != null) {
        byte[] certificateBytes = ca.createTagCertificate(UUID.valueOf(subject), targetSelection);
        Certificate certificate = storeTagCertificate(subject, certificateBytes);
        return certificate;
    }
    // if there is an existing currently valid certificate we return it
    CertificateFilterCriteria criteria = new CertificateFilterCriteria();
    criteria.subjectEqualTo = subject;
    criteria.revoked = false;
    criteria.validOn = new Iso8601Date(new Date());
    CertificateCollection results = certificateRepository.search(criteria);
    Date today = new Date();
    Certificate latestCert = null;
    BigInteger latestCreateTime = BigInteger.ZERO;
    //  pick the most recently created cert that is currently valid and has the same attributes specified in the selection.  we evaluate the notBefore and notAfter fields of the certificate itself even though we already narrowed the search to currently valid certs using the search criteria. 
    if (!results.getCertificates().isEmpty()) {
        for (Certificate certificate : results.getCertificates()) {
            X509AttributeCertificate attributeCertificate = X509AttributeCertificate.valueOf(certificate.getCertificate());
            if (today.before(attributeCertificate.getNotBefore())) {
                continue;
            }
            if (today.after(attributeCertificate.getNotAfter())) {
                continue;
            }
            if (targetSelection != null && !certificateAttributesEqual(attributeCertificate, targetSelection)) {
                continue;
            }
            // And here we want to return the latest certificate so we keep track as we look through the results.
            if (latestCreateTime.compareTo(attributeCertificate.getSerialNumber()) <= 0) {
                latestCreateTime = attributeCertificate.getSerialNumber();
                latestCert = certificate;
            }
        }
    }
    // Check if a valid certificate was found during the search.
    if (latestCert != null) {
        X509AttributeCertificate attributeCertificate = X509AttributeCertificate.valueOf(latestCert.getCertificate());
        AssetTagCertAssociateRequest atca = new AssetTagCertAssociateRequest();
        atca.setSha1OfAssetCert(Sha1Digest.digestOf(attributeCertificate.getEncoded()).toByteArray());
        AssetTagCertBO object = new AssetTagCertBO();
        try {
            object.mapAssetTagCertToHost(atca);
        } catch (CryptographyException ex) {
            java.util.logging.Logger.getLogger(ProvisionTagCertificate.class.getName()).log(Level.SEVERE, null, ex);
        }
        //            ca.mapTagCertificate(UUID.valueOf(subject), attributeCertificate.);
        return latestCert;
    }
    // no cached certificate so generate a new certificate
    if (targetSelection == null) {
        throw new IllegalArgumentException("No cached certificate and no default selection provided");
    }
    byte[] certificateBytes = ca.createTagCertificate(UUID.valueOf(subject), targetSelection);
    Certificate certificate = storeTagCertificate(subject, certificateBytes);
    return certificate;
}
Also used : CertificateCollection(com.intel.mtwilson.datatypes.CertificateCollection) AssetTagCertBO(com.intel.mtwilson.as.business.AssetTagCertBO) X509AttributeCertificate(com.intel.mtwilson.datatypes.X509AttributeCertificate) Date(java.util.Date) Iso8601Date(com.intel.mtwilson.util.io.Iso8601Date) TagConfiguration(com.intel.mtwilson.tag.TagConfiguration) CryptographyException(com.intel.mtwilson.crypto.CryptographyException) TagCertificateAuthority(com.intel.mtwilson.tag.TagCertificateAuthority) SelectionType(com.intel.mtwilson.tag.selection.xml.SelectionType) CertificateFilterCriteria(com.intel.mtwilson.datatypes.CertificateFilterCriteria) BigInteger(java.math.BigInteger) Iso8601Date(com.intel.mtwilson.util.io.Iso8601Date) Certificate(com.intel.mtwilson.datatypes.Certificate) X509AttributeCertificate(com.intel.mtwilson.datatypes.X509AttributeCertificate) AssetTagCertAssociateRequest(com.intel.mtwilson.datatypes.AssetTagCertAssociateRequest)

Aggregations

Certificate (com.intel.mtwilson.datatypes.Certificate)3 CertificateCollection (com.intel.mtwilson.datatypes.CertificateCollection)3 X509AttributeCertificate (com.intel.mtwilson.datatypes.X509AttributeCertificate)3 RepositoryCreateConflictException (com.intel.mtwilson.tag.repository.RepositoryCreateConflictException)2 RepositoryCreateException (com.intel.mtwilson.tag.repository.RepositoryCreateException)2 RepositoryDeleteException (com.intel.mtwilson.tag.repository.RepositoryDeleteException)2 RepositoryException (com.intel.mtwilson.tag.repository.RepositoryException)2 RepositoryRetrieveException (com.intel.mtwilson.tag.repository.RepositoryRetrieveException)2 RepositorySearchException (com.intel.mtwilson.tag.repository.RepositorySearchException)2 RepositoryStoreConflictException (com.intel.mtwilson.tag.repository.RepositoryStoreConflictException)2 RepositoryStoreException (com.intel.mtwilson.tag.repository.RepositoryStoreException)2 AssetTagCertBO (com.intel.mtwilson.as.business.AssetTagCertBO)1 CryptographyException (com.intel.mtwilson.crypto.CryptographyException)1 AssetTagCertAssociateRequest (com.intel.mtwilson.datatypes.AssetTagCertAssociateRequest)1 CertificateFilterCriteria (com.intel.mtwilson.datatypes.CertificateFilterCriteria)1 CertificateLocator (com.intel.mtwilson.datatypes.CertificateLocator)1 JooqContainer (com.intel.mtwilson.jooq.util.JooqContainer)1 TagCertificateAuthority (com.intel.mtwilson.tag.TagCertificateAuthority)1 TagConfiguration (com.intel.mtwilson.tag.TagConfiguration)1 SelectionType (com.intel.mtwilson.tag.selection.xml.SelectionType)1