Search in sources :

Example 6 with CryptographyException

use of com.intel.mtwilson.crypto.CryptographyException 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)

Example 7 with CryptographyException

use of com.intel.mtwilson.crypto.CryptographyException in project OpenAttestation by OpenAttestation.

the class HostBO method queryForHosts.

/**
         * Author: Sudhir
         * 
         * Searches for the hosts using the criteria specified.
         * 
         * @param searchCriteria: If in case the user has not provided any search criteria, then all the hosts
         * would be returned back to the caller
         * @return 
         */
public List<TxtHostRecord> queryForHosts(String searchCriteria) {
    try {
        TblHostsJpaController tblHostsJpaController = new TblHostsJpaController(getEntityManagerFactory());
        List<TxtHostRecord> txtHostList = new ArrayList<TxtHostRecord>();
        List<TblHosts> tblHostList;
        if (searchCriteria != null && !searchCriteria.isEmpty()) {
            log.info("searchCriteria is not null -- calling tblHostsJpaController.findHostsByNameSearchCriteria(searchCriteria)");
            tblHostList = tblHostsJpaController.findHostsByNameSearchCriteria(searchCriteria);
            log.info(new Integer(tblHostList.size()).toString());
        } else {
            log.info("calling tblHostsJpaController.findTblHostsEntities()");
            tblHostList = tblHostsJpaController.findTblHostsEntities();
            log.info(new Integer(tblHostList.size()).toString());
        }
        //			if (tblHostList != null) {
        log.info(String.format("Found [%d] host results for search criteria [%s]", tblHostList.size(), searchCriteria));
        for (TblHosts tblHosts : tblHostList) {
            TxtHostRecord hostObj = createTxtHostFromDatabaseRecord(tblHosts);
            txtHostList.add(hostObj);
        }
        return txtHostList;
    } catch (ASException e) {
        throw e;
    } catch (CryptographyException e) {
        throw new ASException(e, ErrorCode.AS_ENCRYPTION_ERROR, e.getCause() == null ? e.getMessage() : e.getCause().getMessage());
    } catch (Exception e) {
        throw new ASException(e);
    }
}
Also used : TblHostsJpaController(com.intel.mtwilson.as.controller.TblHostsJpaController) CryptographyException(com.intel.mtwilson.crypto.CryptographyException) TblHosts(com.intel.mtwilson.as.data.TblHosts) ArrayList(java.util.ArrayList) ASException(com.intel.mountwilson.as.common.ASException) ASException(com.intel.mountwilson.as.common.ASException) NoResultException(javax.persistence.NoResultException) NonexistentEntityException(com.intel.mtwilson.as.controller.exceptions.NonexistentEntityException) IllegalOrphanException(com.intel.mtwilson.as.controller.exceptions.IllegalOrphanException) CryptographyException(com.intel.mtwilson.crypto.CryptographyException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Example 8 with CryptographyException

use of com.intel.mtwilson.crypto.CryptographyException in project OpenAttestation by OpenAttestation.

the class HostBO method addHost.

public String addHost(TxtHost host) {
    String certificate = null;
    String location = null;
    String ipAddress = null;
    HashMap<String, ? extends IManifest> pcrMap = null;
    try {
        ipAddress = InetAddress.getByName(host.getHostName().toString()).getHostAddress();
        if (!ipAddress.equalsIgnoreCase(host.getIPAddress().toString())) {
            throw new ASException(ErrorCode.AS_HOST_IPADDRESS_NOT_MATCHED, host.getHostName().toString(), host.getIPAddress().toString());
        }
        checkForDuplicate(host);
        getBiosAndVMM(host);
        log.info("Getting Server Identity.");
        TblHosts tblHosts = new TblHosts();
        tblHosts.setTlsPolicyName("TRUST_FIRST_CERTIFICATE");
        tblHosts.setTlsKeystore(null);
        tblHosts.setAddOnConnectionInfo(host.getAddOn_Connection_String());
        if (host.getHostName() != null) {
            tblHosts.setName(host.getHostName().toString());
        }
        if (host.getIPAddress() != null) {
            tblHosts.setIPAddress(host.getIPAddress().toString());
        }
        if (host.getPort() != null) {
            tblHosts.setPort(host.getPort());
        } else {
            throw new ASException(ErrorCode.PORT_MISSING, host.getHostName().toString(), host.getIPAddress().toString());
        }
        if (canFetchAIKCertificateForHost(host.getVmm().getName())) {
            // datatype.Vmm
            if (!host.getAddOn_Connection_String().toLowerCase().contains("citrix")) {
                certificate = getAIKCertificateForHost(tblHosts, host);
                // we have to check that the aik certificate was signed by a trusted privacy ca
                X509Certificate hostAikCert = X509Util.decodePemCertificate(certificate);
                hostAikCert.checkValidity();
                // read privacy ca certificate
                InputStream privacyCaIn = new FileInputStream(ResourceFinder.getFile("PrivacyCA.cer"));
                // XXX TODO currently we only support one privacy CA cert...
                // in the future we should read a PEM format file with possibly multiple trusted privacy ca certs
                X509Certificate privacyCaCert = X509Util.decodeDerCertificate(IOUtils.toByteArray(privacyCaIn));
                IOUtils.closeQuietly(privacyCaIn);
                privacyCaCert.checkValidity();
                // verify the trusted privacy ca signed this aik cert
                hostAikCert.verify(privacyCaCert.getPublicKey());
            // NoSuchAlgorithmException,InvalidKeyException,NoSuchProviderException,SignatureException
            }
        } else {
            // ESX host so get the location for the host and store in the table
            pcrMap = getHostPcrManifest(tblHosts, host);
            // BUG #497 sending both the new TblHosts record and the TxtHost object just to get the TlsPolicy into
            // the initial call so that with the trust_first_certificate policy we will obtain the host certificate now while adding it
            log.info("Getting location for host from VCenter");
            location = getLocation(pcrMap);
        }
        HostAgentFactory factory = new HostAgentFactory();
        HostAgent agent = factory.getHostAgent(tblHosts);
        log.info("Saving Host in database with TlsPolicyName {} and TlsKeystoreLength {}", tblHosts.getTlsPolicyName(), tblHosts.getTlsKeystore() == null ? "null" : tblHosts.getTlsKeystore().length);
        Map<String, String> attributes = agent.getHostAttributes();
        String hostUuidAttr = attributes.get("Host_UUID");
        //if ((attributes != null) && (!attributes.isEmpty()) && (hostUuidAttr != null))
        if (!attributes.isEmpty() && hostUuidAttr != null)
            tblHosts.setHardwareUuid(hostUuidAttr.toLowerCase().trim());
        //                        
        log.debug("Saving the host details in the DB");
        // retrieve the complete manifest and get module info inserted into database
        // We only handle module info for PCR 19
        HashMap<String, ? extends IManifest> pcrs = getHostPcrManifest(tblHosts, host);
        List<TblHostSpecificManifest> tblHostSpecificManifests = null;
        if (vmmMleId.getRequiredManifestList().contains(MODULE_PCR)) {
            if (pcrs != null) {
                PcrManifest pcr19 = (PcrManifest) pcrs.get(MODULE_PCR);
                addModuleWhiteList(pcr19, tblHosts, host, hostUuidAttr);
                log.info("Host specific modules would be retrieved from the host that extends into PCR 19.");
                String hostType = host.getVendor();
                tblHostSpecificManifests = createHostSpecificManifestRecords(vmmMleId, pcrs, hostType);
            }
        } else {
            log.info("Host specific modules will not be configured since PCR 19 is not selected for attestation");
        }
        //saveHostInDatabase(tblHosts, host, certificate, location, pcrMap);
        biosMleId = findBiosMleForHost(host);
        vmmMleId = findVmmMleForHost(host);
        saveHostInDatabase(tblHosts, host, certificate, location, pcrMap, tblHostSpecificManifests, biosMleId, vmmMleId);
        // Now that the host has been registered successfully, let us see if there is an asset tag certificated configured for the host
        // to which the host has to be associated
        //attributes);
        associateAssetTagCertForHost(host, agent.getHostAttributes(), tblHosts);
    } catch (ASException ase) {
        throw ase;
    } catch (CryptographyException e) {
        throw new ASException(e, ErrorCode.AS_ENCRYPTION_ERROR, e.getCause() == null ? e.getMessage() : e.getCause().getMessage());
    } catch (Exception e) {
        log.debug("beggining stack trace --------------");
        e.printStackTrace();
        log.debug("end stack trace --------------");
        throw new ASException(e);
    }
    return "true";
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) X509Certificate(java.security.cert.X509Certificate) FileInputStream(java.io.FileInputStream) ASException(com.intel.mountwilson.as.common.ASException) NoResultException(javax.persistence.NoResultException) NonexistentEntityException(com.intel.mtwilson.as.controller.exceptions.NonexistentEntityException) IllegalOrphanException(com.intel.mtwilson.as.controller.exceptions.IllegalOrphanException) CryptographyException(com.intel.mtwilson.crypto.CryptographyException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) CryptographyException(com.intel.mtwilson.crypto.CryptographyException) PcrManifest(com.intel.mountwilson.manifest.data.PcrManifest) TblHosts(com.intel.mtwilson.as.data.TblHosts) TblHostSpecificManifest(com.intel.mtwilson.as.data.TblHostSpecificManifest) HostAgent(com.intel.mtwilson.agent.HostAgent) HostAgentFactory(com.intel.mtwilson.agent.HostAgentFactory) ASException(com.intel.mountwilson.as.common.ASException)

Example 9 with CryptographyException

use of com.intel.mtwilson.crypto.CryptographyException in project OpenAttestation by OpenAttestation.

the class HostBO method deleteHost.

public String deleteHost(Hostname hostName) {
    try {
        TblHosts tblHosts = getHostByName(hostName);
        if (tblHosts == null) {
            throw new ASException(ErrorCode.AS_HOST_NOT_FOUND, hostName);
        }
        log.info("Deleting Host from database");
        deleteHostAssetTagMapping(tblHosts);
        deleteHostSpecificManifest(tblHosts);
        deleteModulesForMLE(createTxtHostFromDatabaseRecord(tblHosts));
        deleteTALogs(tblHosts.getId());
        deleteSAMLAssertions(tblHosts);
        getHostsJpaController().destroy(tblHosts.getId());
        unmapAssetTagCertFromHost(tblHosts.getId(), tblHosts.getName());
    } catch (ASException ase) {
        throw ase;
    } catch (CryptographyException e) {
        throw new ASException(ErrorCode.SYSTEM_ERROR, e.getCause() == null ? e.getMessage() : e.getCause().getMessage(), e);
    } catch (Exception e) {
        throw new ASException(e);
    }
    // return new HostResponse(ErrorCode.OK);
    return "true";
}
Also used : CryptographyException(com.intel.mtwilson.crypto.CryptographyException) TblHosts(com.intel.mtwilson.as.data.TblHosts) ASException(com.intel.mountwilson.as.common.ASException) ASException(com.intel.mountwilson.as.common.ASException) NoResultException(javax.persistence.NoResultException) NonexistentEntityException(com.intel.mtwilson.as.controller.exceptions.NonexistentEntityException) IllegalOrphanException(com.intel.mtwilson.as.controller.exceptions.IllegalOrphanException) CryptographyException(com.intel.mtwilson.crypto.CryptographyException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Aggregations

CryptographyException (com.intel.mtwilson.crypto.CryptographyException)9 ASException (com.intel.mountwilson.as.common.ASException)8 TblHosts (com.intel.mtwilson.as.data.TblHosts)8 IOException (java.io.IOException)6 IllegalOrphanException (com.intel.mtwilson.as.controller.exceptions.IllegalOrphanException)4 NonexistentEntityException (com.intel.mtwilson.as.controller.exceptions.NonexistentEntityException)4 UnknownHostException (java.net.UnknownHostException)4 NoResultException (javax.persistence.NoResultException)4 HostType (com.intel.mountwilson.as.hosttrustreport.data.HostType)3 TblTaLog (com.intel.mtwilson.as.data.TblTaLog)3 PcrManifest (com.intel.mountwilson.manifest.data.PcrManifest)2 TblHostSpecificManifest (com.intel.mtwilson.as.data.TblHostSpecificManifest)2 HostManifestReportType (com.intel.mountwilson.as.hostmanifestreport.data.HostManifestReportType)1 ManifestType (com.intel.mountwilson.as.hostmanifestreport.data.ManifestType)1 HostsTrustReportType (com.intel.mountwilson.as.hosttrustreport.data.HostsTrustReportType)1 IManifestStrategy (com.intel.mountwilson.manifest.IManifestStrategy)1 IManifestStrategyFactory (com.intel.mountwilson.manifest.IManifestStrategyFactory)1 IManifest (com.intel.mountwilson.manifest.data.IManifest)1 HostAgent (com.intel.mtwilson.agent.HostAgent)1 HostAgentFactory (com.intel.mtwilson.agent.HostAgentFactory)1