Search in sources :

Example 36 with ASException

use of com.intel.mountwilson.as.common.ASException in project OpenAttestation by OpenAttestation.

the class TAHelper method generateNonce.

public String generateNonce() {
    try {
        // Create a secure random number generator
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        // Get 1024 random bits
        byte[] bytes = new byte[16];
        sr.nextBytes(bytes);
        //            nonce = new BASE64Encoder().encode( bytes);
        String nonce = Base64.encodeBase64String(bytes);
        log.info("Nonce Generated {}", nonce);
        return nonce;
    } catch (NoSuchAlgorithmException e) {
        throw new ASException(e);
    }
}
Also used : SecureRandom(java.security.SecureRandom) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ASException(com.intel.mountwilson.as.common.ASException)

Example 37 with ASException

use of com.intel.mountwilson.as.common.ASException in project OpenAttestation by OpenAttestation.

the class CommandUtil method runCommand.

public static List<String> runCommand(String commandLine, boolean readResult, String commandAlias) {
    List<String> result = new ArrayList<String>();
    try {
        int returnCode;
        log.trace("Running command {}", commandLine);
        Process p = Runtime.getRuntime().exec(commandLine);
        if (readResult) {
            InputStream in = p.getInputStream();
            try {
                BufferedReader input = new BufferedReader(new InputStreamReader(in));
                String newLine;
                while ((newLine = input.readLine()) != null) {
                    result.add(newLine);
                }
                input.close();
            } finally {
                if (in != null) {
                    in.close();
                }
            }
        }
        String resultForLog = result.size() + " items:\n" + StringUtils.join(result, "\n");
        log.trace("Result Output \n{}", resultForLog);
        //do a loop to wait for an exit value
        boolean isRunning;
        int timeout = 5000;
        int countToTimeout = 0;
        do {
            countToTimeout++;
            isRunning = false;
            try {
                /*returnCode = */
                p.exitValue();
            } catch (IllegalThreadStateException e1) {
                isRunning = true;
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e2) {
                    isRunning = false;
                }
            }
        } while (isRunning && (countToTimeout < timeout));
        if (countToTimeout == timeout) {
            log.trace("Command is not responding.");
            p.destroy();
        }
        returnCode = p.exitValue();
        log.trace("Return code {}", String.valueOf(returnCode));
        if (returnCode != 0) {
            throw new ASException(ErrorCode.AS_QUOTE_VERIFY_COMMAND_FAILED, returnCode);
        }
    } catch (ASException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ASException(ex);
    }
    return result;
}
Also used : InputStreamReader(java.io.InputStreamReader) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) ASException(com.intel.mountwilson.as.common.ASException) BufferedReader(java.io.BufferedReader) ASException(com.intel.mountwilson.as.common.ASException)

Example 38 with ASException

use of com.intel.mountwilson.as.common.ASException in project OpenAttestation by OpenAttestation.

the class TrustAgentSecureClient method sendRequestWithSSLSocket.

/*
    // XXX this constructor is not used anywhere
    public TrustAgentSecureClient(IPAddress serverIPAddress, int serverPort, byte[] data) { // datatype.IPAddress
        this(serverIPAddress, serverPort);
        if( data != null ) {
            this.data = Arrays.copyOf(data, data.length);
        }
    }

    // XXX this constructor is not used anywhere
    public TrustAgentSecureClient(IPAddress serverIPAddress, int serverPort) { // datatype.IPAddress
        this(serverIPAddress.toString(), serverPort);
    }
    */
private byte[] sendRequestWithSSLSocket() throws NoSuchAlgorithmException, NoSuchAlgorithmException, KeyManagementException, UnknownHostException, IOException {
    log.trace("Opening connection to {} port {}", new String[] { serverHostname, String.valueOf(serverPort) });
    if (data == null) {
        throw new IllegalArgumentException("Attempted to send request without data");
    }
    SSLSocketFactory sslsocketfactory = getSSLContext().getSocketFactory();
    SSLSocket sock = (SSLSocket) sslsocketfactory.createSocket();
    try {
        sock.connect(new InetSocketAddress(serverHostname, serverPort), TIME_OUT);
        InputStream sockInput = sock.getInputStream();
        OutputStream sockOutput = sock.getOutputStream();
        log.info("About to start reading/writing to/from socket.");
        byte[] buf = new byte[5000];
        sockOutput.write(data, 0, data.length);
        int bytes_read = sockInput.read(buf);
        log.info("Received " + bytes_read + " bytes to server and received them back again, msg = " + StringUtils.replace(new String(buf), "\n", "\n  "));
        return buf;
    } catch (SocketTimeoutException e) {
        throw new ASException(e, ErrorCode.AS_TRUST_AGENT_CONNNECT_TIMED_OUT, serverHostname, serverPort, (TIME_OUT / 1000));
    } finally {
        sock.close();
    }
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) InetSocketAddress(java.net.InetSocketAddress) InputStream(java.io.InputStream) SSLSocket(javax.net.ssl.SSLSocket) OutputStream(java.io.OutputStream) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) ASException(com.intel.mountwilson.as.common.ASException)

Example 39 with ASException

use of com.intel.mountwilson.as.common.ASException in project OpenAttestation by OpenAttestation.

the class AssetTagCertBO method findValidAssetTagCertForHost.

public MwAssetTagCertificate findValidAssetTagCertForHost(Integer hostID) {
    try {
        // So if the host has been provisioned multiple times, we will pick up the latest one.
        if (hostID != 0) {
            //List<MwAssetTagCertificate> atagCerts = My.jpa().mwAssetTagCertificate().findAssetTagCertificatesByHostID(hostID);
            MwAssetTagCertificateJpaController assetTagController = new MwAssetTagCertificateJpaController(getEntityManagerFactory());
            List<MwAssetTagCertificate> atagCerts = assetTagController.findAssetTagCertificatesByHostID(hostID);
            if (atagCerts.isEmpty()) {
                log.info("Asset tag certificate has not been provisioned for the host with ID : {}.", hostID);
                return null;
            } else {
                // Ideally there should be only one that is valid.
                for (MwAssetTagCertificate atagTempCert : atagCerts) {
                    if (validateAssetTagCert(atagTempCert)) {
                        log.debug("Valid asset tag certificate found for host with ID {}.", hostID);
                        return atagTempCert;
                    }
                }
                log.info("No valid asset tag certificate found for host with ID {}.", hostID);
            }
        } else {
            log.error("ID specified for the host is not valid.");
            throw new ASException(ErrorCode.AS_HOST_NOT_FOUND);
        }
    } catch (ASException ase) {
        log.error("Error during querying of valid asset tag certificate using host ID. Error Details - {}:{}.", ase.getErrorCode(), ase.getErrorMessage());
        throw ase;
    } catch (Exception ex) {
        log.error("Unexpected error during querying of valid asset tag certificate using host ID. Error Details - {}.", ex.getMessage());
        throw new ASException(ex);
    }
    return null;
}
Also used : MwAssetTagCertificateJpaController(com.intel.mtwilson.as.controller.MwAssetTagCertificateJpaController) MwAssetTagCertificate(com.intel.mtwilson.as.data.MwAssetTagCertificate) ASException(com.intel.mountwilson.as.common.ASException) 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)

Example 40 with ASException

use of com.intel.mountwilson.as.common.ASException in project OpenAttestation by OpenAttestation.

the class AssetTagCertBO method mapAssetTagCertToHost.

/**
     * This function would be used to associate a asset tag certificate with the host for which it is 
     * provisioned for.  It does not require you know the ID of the host you are associating to.  
     * Here you are giving the hash of the cert to the code and letting it find a matching host
     * @param atagObj
     * @return true if host was found, false if not
     */
public boolean mapAssetTagCertToHost(AssetTagCertAssociateRequest atagObj) throws CryptographyException {
    boolean result = false;
    log.debug("mapAssetTagCertToHost");
    AssetTagCertAssociateRequest request = new AssetTagCertAssociateRequest();
    if (atagObj.getSha1OfAssetCert() != null) {
        log.debug("trying to associate tag to existing host using " + Hex.encodeHexString(atagObj.getSha1OfAssetCert()));
        //List<MwAssetTagCertificate> atagCerts = My.jpa().mwAssetTagCertificate().findAssetTagCertificateBySha1Hash(atagObj.getSha1OfAssetCert());
        MwAssetTagCertificateJpaController mwAssetTagCertificateJpaController = new MwAssetTagCertificateJpaController(getEntityManagerFactory());
        List<MwAssetTagCertificate> atagCerts = mwAssetTagCertificateJpaController.findAssetTagCertificateBySha1Hash(atagObj.getSha1OfAssetCert());
        // List<MwAssetTagCertificate> atagCerts = My.jpa().mwAssetTagCertificate().findAssetTagCertificatesByHostUUID("494cb5dc-a3e1-4e46-9b52-e694349b1654");
        if (atagCerts.isEmpty()) {
            log.error("mapAssetTagCertToHost: The asset tag certificate does not exist");
            throw new ASException(ErrorCode.AS_INVALID_ASSET_TAG_CERTIFICATE_HASH);
        } else if (atagCerts.size() > 1) {
            log.error("mapAssetTagCertToHost: There were multiple matches for the specified hash");
            throw new ASException(ErrorCode.AS_INVALID_ASSET_TAG_CERTIFICATE_HASH);
        } else {
            MwAssetTagCertificate atagCert = atagCerts.get(0);
            request.setSha1OfAssetCert(atagCert.getSHA1Hash());
            String uuid = atagCert.getUuid().toLowerCase().trim();
            log.debug("searching using " + uuid);
            //TblHosts tblHost = My.jpa().mwHosts().findByHwUUID(uuid);
            TblHostsJpaController tblHostsJpaController = new TblHostsJpaController(getEntityManagerFactory());
            TblHosts tblHost = tblHostsJpaController.findByHwUUID(uuid);
            if (tblHost != null) {
                log.debug("found host matching uuid of cert, going to assoicate with host id = " + tblHost.getId());
                request.setHostID(tblHost.getId());
                //atagObj.setHostID(tblHost.getId());
                result = mapAssetTagCertToHostById(request);
            } else {
                log.debug("found no matching uuid of cert");
                result = false;
            }
        }
    }
    return result;
}
Also used : TblHostsJpaController(com.intel.mtwilson.as.controller.TblHostsJpaController) TblHosts(com.intel.mtwilson.as.data.TblHosts) MwAssetTagCertificateJpaController(com.intel.mtwilson.as.controller.MwAssetTagCertificateJpaController) MwAssetTagCertificate(com.intel.mtwilson.as.data.MwAssetTagCertificate) ASException(com.intel.mountwilson.as.common.ASException) AssetTagCertAssociateRequest(com.intel.mtwilson.datatypes.AssetTagCertAssociateRequest)

Aggregations

ASException (com.intel.mountwilson.as.common.ASException)69 IOException (java.io.IOException)28 CryptographyException (com.intel.mtwilson.crypto.CryptographyException)26 IllegalOrphanException (com.intel.mtwilson.as.controller.exceptions.IllegalOrphanException)20 NonexistentEntityException (com.intel.mtwilson.as.controller.exceptions.NonexistentEntityException)20 TblMle (com.intel.mtwilson.as.data.TblMle)20 NoResultException (javax.persistence.NoResultException)19 UnknownHostException (java.net.UnknownHostException)18 TblHosts (com.intel.mtwilson.as.data.TblHosts)17 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)14 ASDataException (com.intel.mtwilson.as.controller.exceptions.ASDataException)12 KeyManagementException (java.security.KeyManagementException)10 MwAssetTagCertificate (com.intel.mtwilson.as.data.MwAssetTagCertificate)9 SignatureException (java.security.SignatureException)8 CertificateException (java.security.cert.CertificateException)8 WebApplicationException (javax.ws.rs.WebApplicationException)8 ConfigurationException (org.apache.commons.configuration.ConfigurationException)8 ApiException (com.intel.mtwilson.ApiException)7 MwAssetTagCertificateJpaController (com.intel.mtwilson.as.controller.MwAssetTagCertificateJpaController)7 TblMleJpaController (com.intel.mtwilson.as.controller.TblMleJpaController)7