Search in sources :

Example 1 with X509AttributeCertificate

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

the class AssetTagCertBO method validateAssetTagCert.

/**
     * Validates the asset tag certificate and returns back true/false accordingly.
     * 
     * @param atagObj
     * @return 
     */
private boolean validateAssetTagCert(MwAssetTagCertificate atagObj) {
    boolean isValid = false;
    try {
        // First let us verify if the revoked flag is set
        if (atagObj.getRevoked() == true)
            return false;
        // X509AttributeCertificate provides a helper function that validates both the dates and the signature.
        // For that we need to first get the CA certificate that signed the Attribute Certificate. We need to
        // extract this from the PEM file list and pass it to the helper function
        X509AttributeCertificate atagAttrCertForHost = X509AttributeCertificate.valueOf(atagObj.getCertificate());
        List<X509Certificate> atagCaCerts = null;
        ////////////////
        FileDAO fileDao;
        try {
            fileDao = TagJdbi.fileDao();
            File cacertFile = fileDao.findByName("cacerts");
            if (cacertFile == null) {
                log.error("Error loading the cacert pem file to extract the CA certificate(s).");
            } else {
                atagCaCerts = X509Util.decodePemCertificates(new String(cacertFile.getContent(), "UTF-8"));
                //IOUtils.closeQuietly(atagCaIn);
                log.debug("Added {} certificates from AssetTagCA.pem", atagCaCerts.size());
            //                    cacerts = X509Util.decodePemCertificates(new String(cacertFile.getContent(), "UTF-8"));
            }
        } catch (Exception e) {
            log.error("Cannot load cacerts", e);
            atagCaCerts = null;
        }
        // The below isValid function verifies both the signature and the dates.
        if (atagCaCerts != null) {
            for (X509Certificate atagCACert : atagCaCerts) {
                if (atagAttrCertForHost.isValid(atagCACert))
                    return true;
            }
        }
    } catch (Exception ex) {
        throw new ASException(ex);
    }
    return isValid;
}
Also used : FileDAO(com.intel.mtwilson.tag.dao.jdbi.FileDAO) X509AttributeCertificate(com.intel.mtwilson.datatypes.X509AttributeCertificate) File(com.intel.mtwilson.datatypes.File) X509Certificate(java.security.cert.X509Certificate) ASException(com.intel.mountwilson.as.common.ASException) ApiException(com.intel.mtwilson.ApiException) CryptographyException(com.intel.mtwilson.crypto.CryptographyException) SignatureException(java.security.SignatureException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ASException(com.intel.mountwilson.as.common.ASException)

Example 2 with X509AttributeCertificate

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

the class AssetTagCertBO method importAssetTagCertificate.

//    public AssetTagCertBO(PersistenceManager pm) {
//        super(pm);
//    }
/**
     * This functions stores a new asset tag certificate that was provisioned by the Asset tag
     * provisioning service for a host.This certificate would be associated to the host for
     * which it was provisioned only when that host gets registered with Mt.Wilson
     * @param atagObj
     * @return 
     */
public boolean importAssetTagCertificate(AssetTagCertCreateRequest atagObj, String uuid) {
    boolean result;
    X509AttributeCertificate x509AttrCert;
    try {
        try {
            x509AttrCert = X509AttributeCertificate.valueOf(atagObj.getCertificate());
        } catch (IllegalArgumentException ce) {
            log.error("Error during retrieval of a new asset tag certificate. Error Details - {}.", ce.getMessage());
            throw new ASException(ce, ErrorCode.AS_INVALID_ASSET_TAG_CERTIFICATE, ce.getMessage());
        }
        MwAssetTagCertificate atagCert = new MwAssetTagCertificate();
        if (uuid != null && !uuid.isEmpty())
            atagCert.setUuid_hex(uuid);
        else
            atagCert.setUuid_hex(new UUID().toString());
        atagCert.setCertificate(atagObj.getCertificate());
        atagCert.setUuid(x509AttrCert.getSubject().toLowerCase());
        atagCert.setNotAfter(x509AttrCert.getNotAfter());
        atagCert.setNotBefore(x509AttrCert.getNotBefore());
        atagCert.setRevoked(false);
        //atagCert.setSHA1Hash(Sha1Digest.digestOf(atagObj.getCertificate()).toByteArray());
        atagCert.setSHA1Hash(Sha1Digest.digestOf(x509AttrCert.getEncoded()).toByteArray());
        log.debug("Certificate creation time is {}", x509AttrCert.getSerialNumber());
        log.debug("Certificate SHA1 is {}", Sha1Digest.digestOf(x509AttrCert.getEncoded()).toHexString());
        atagCert.setCreate_time(x509AttrCert.getSerialNumber());
        //atagCert.setSHA256Hash(Sha256Digest.digestOf(atagObj.getCertificate()).toByteArray()); // not used with TPM 1.2
        // We are just writing some default value here, which would be changed when the host would be mapped to this
        // certificate.
        //atagCert.setPCREvent(Sha1Digest.digestOf(atagCert.getSHA1Hash()).toByteArray());
        Sha1Digest sha1D = Sha1Digest.digestOf(atagObj.getCertificate());
        Sha1Digest expectedPcr = Sha1Digest.ZERO.extend(Sha1Digest.digestOf(sha1D.toBase64().getBytes()));
        atagCert.setPCREvent(expectedPcr.toByteArray());
        log.debug("assetTag writing cert to DB");
        //My.jpa().mwAssetTagCertificate().create(atagCert);
        MwAssetTagCertificateJpaController mwAssetTagCertificateJpaController = new MwAssetTagCertificateJpaController(getEntityManagerFactory());
        mwAssetTagCertificateJpaController.create(atagCert);
        result = true;
        // here we need to check a config option, mtwilson.atag.associate.hosts.auto
        // now try to match a host to it
        log.debug("trying to associate tag to existing host using " + Hex.encodeHexString(atagCert.getSHA1Hash()));
        AssetTagCertAssociateRequest request = new AssetTagCertAssociateRequest();
        request.setSha1OfAssetCert(atagCert.getSHA1Hash());
        //result = 
        mapAssetTagCertToHost(request);
    } catch (ASException ase) {
        log.error("Error during creation of a new asset tag certificate. Error Details - {}:{}.", ase.getErrorCode(), ase.getErrorMessage());
        throw ase;
    } catch (Exception ex) {
        log.error("Unexpected error during creation of a new asset tag certificate. Error Details - {}.", ex.getMessage());
        throw new ASException(ex);
    }
    return result;
}
Also used : Sha1Digest(com.intel.mtwilson.util.crypto.Sha1Digest) X509AttributeCertificate(com.intel.mtwilson.datatypes.X509AttributeCertificate) UUID(com.intel.mtwilson.util.io.UUID) MwAssetTagCertificateJpaController(com.intel.mtwilson.as.controller.MwAssetTagCertificateJpaController) ASException(com.intel.mountwilson.as.common.ASException) MwAssetTagCertificate(com.intel.mtwilson.as.data.MwAssetTagCertificate) ASException(com.intel.mountwilson.as.common.ASException) ApiException(com.intel.mtwilson.ApiException) CryptographyException(com.intel.mtwilson.crypto.CryptographyException) SignatureException(java.security.SignatureException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AssetTagCertAssociateRequest(com.intel.mtwilson.datatypes.AssetTagCertAssociateRequest)

Example 3 with X509AttributeCertificate

use of com.intel.mtwilson.datatypes.X509AttributeCertificate 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

CryptographyException (com.intel.mtwilson.crypto.CryptographyException)3 X509AttributeCertificate (com.intel.mtwilson.datatypes.X509AttributeCertificate)3 ASException (com.intel.mountwilson.as.common.ASException)2 ApiException (com.intel.mtwilson.ApiException)2 AssetTagCertAssociateRequest (com.intel.mtwilson.datatypes.AssetTagCertAssociateRequest)2 IOException (java.io.IOException)2 KeyManagementException (java.security.KeyManagementException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 SignatureException (java.security.SignatureException)2 CertificateException (java.security.cert.CertificateException)2 AssetTagCertBO (com.intel.mtwilson.as.business.AssetTagCertBO)1 MwAssetTagCertificateJpaController (com.intel.mtwilson.as.controller.MwAssetTagCertificateJpaController)1 MwAssetTagCertificate (com.intel.mtwilson.as.data.MwAssetTagCertificate)1 Certificate (com.intel.mtwilson.datatypes.Certificate)1 CertificateCollection (com.intel.mtwilson.datatypes.CertificateCollection)1 CertificateFilterCriteria (com.intel.mtwilson.datatypes.CertificateFilterCriteria)1 File (com.intel.mtwilson.datatypes.File)1 TagCertificateAuthority (com.intel.mtwilson.tag.TagCertificateAuthority)1 TagConfiguration (com.intel.mtwilson.tag.TagConfiguration)1 FileDAO (com.intel.mtwilson.tag.dao.jdbi.FileDAO)1