Search in sources :

Example 1 with SecurityProviderException

use of com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException in project azure-iot-sdk-java by Azure.

the class SecurityProviderSymmetricKey method HMACSignData.

/**
 * Signs data using the provided base 64 decoded key using HMAC SHA 256
 * @param signature Data to be signed
 * @param base64DecodedKey Key used for signing
 * @return Returns signed data
 * @throws SecurityProviderException If signing was not successful
 */
public byte[] HMACSignData(byte[] signature, byte[] base64DecodedKey) throws SecurityProviderException {
    if (signature == null || signature.length == 0 || base64DecodedKey == null || base64DecodedKey.length == 0) {
        throw new SecurityProviderException("Signature or Key cannot be null or empty");
    }
    try {
        SecretKeySpec secretKey = new SecretKeySpec(base64DecodedKey, HMAC_SHA_256);
        Mac hMacSha256 = Mac.getInstance(HMAC_SHA_256);
        hMacSha256.init(secretKey);
        return hMacSha256.doFinal(signature);
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        throw new SecurityProviderException(e);
    }
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) SecurityProviderException(com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException) Mac(javax.crypto.Mac)

Example 2 with SecurityProviderException

use of com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException in project azure-iot-sdk-java by Azure.

the class SecurityProviderX509 method generateSSLContext.

private SSLContext generateSSLContext(X509Certificate leafCertificate, Key leafPrivateKey, Collection<X509Certificate> signerCertificates) throws NoSuchProviderException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException, CertificateException, SecurityProviderException {
    if (leafCertificate == null || leafPrivateKey == null || signerCertificates == null) {
        // SRS_SecurityClientX509_25_006: [ This method shall throw IllegalArgumentException if input parameters are null. ]
        throw new IllegalArgumentException("cert or private key cannot be null");
    }
    // SRS_SecurityClientX509_25_007: [ This method shall use random UUID as a password for keystore. ]
    String password = UUID.randomUUID().toString();
    // SRS_SecurityClientX509_25_008: [ This method shall create a TLSv1.2 instance. ]
    SSLContext sslContext = SSLContext.getInstance(DEFAULT_TLS_PROTOCOL);
    // Load Trusted certs to keystore and retrieve it.
    // SRS_SecurityClientX509_25_009: [ This method shall retrieve the keystore loaded with trusted certs. ]
    KeyStore keyStore = this.getKeyStoreWithTrustedCerts();
    if (keyStore == null) {
        throw new SecurityProviderException("Key store with trusted certs cannot be null");
    }
    // Load Alias cert and private key to key store
    int noOfCerts = signerCertificates.size() + 1;
    X509Certificate[] certs = new X509Certificate[noOfCerts];
    int i = 0;
    certs[i++] = leafCertificate;
    // Load the chain of signer cert to keystore
    for (X509Certificate c : signerCertificates) {
        certs[i++] = c;
    }
    // SRS_SecurityClientX509_25_010: [ This method shall load all the provided X509 certs (leaf with both public certificate and private key,
    // intermediate certificates(if any) to the Key store. ]
    keyStore.setKeyEntry(ALIAS_CERT_ALIAS, leafPrivateKey, password.toCharArray(), certs);
    // SRS_SecurityClientX509_25_011: [ This method shall initialize the ssl context with X509KeyManager and X509TrustManager for the keystore. ]
    sslContext.init(new KeyManager[] { this.getDefaultX509KeyManager(keyStore, password) }, new TrustManager[] { this.getDefaultX509TrustManager(keyStore) }, new SecureRandom());
    // SRS_SecurityClientX509_25_012: [ This method shall return the ssl context created as above to the caller. ]
    return sslContext;
}
Also used : SecurityProviderException(com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException) X509Certificate(java.security.cert.X509Certificate)

Example 3 with SecurityProviderException

use of com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException in project azure-iot-sdk-java by Azure.

the class ProvisioningTpmSample method main.

public static void main(String[] args) throws Exception {
    System.out.println("Starting...");
    System.out.println("Beginning setup.");
    SecurityProviderTpm securityClientTPMEmulator = null;
    Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8.name());
    DeviceClient deviceClient = null;
    try {
        securityClientTPMEmulator = new SecurityProviderTPMEmulator();
        System.out.println("Endorsement Key : \n" + new String(encodeBase64(securityClientTPMEmulator.getEndorsementKey()), StandardCharsets.UTF_8));
        System.out.println("Registration Id : \n" + securityClientTPMEmulator.getRegistrationId());
        System.out.println("Please visit Azure Portal (https://portal.azure.com/) and create a TPM Individual Enrollment with the information above i.e EndorsementKey and RegistrationId \n" + "Press enter when you are ready to run registration after enrolling with the service");
        scanner.nextLine();
    } catch (SecurityProviderException e) {
        e.printStackTrace();
    }
    ProvisioningDeviceClient provisioningDeviceClient = null;
    try {
        ProvisioningStatus provisioningStatus = new ProvisioningStatus();
        provisioningDeviceClient = ProvisioningDeviceClient.create(GLOBAL_ENDPOINT, SCOPE_ID, PROVISIONING_DEVICE_CLIENT_TRANSPORT_PROTOCOL, securityClientTPMEmulator);
        provisioningDeviceClient.registerDevice(new ProvisioningDeviceClientRegistrationCallbackImpl(), provisioningStatus);
        while (provisioningStatus.provisioningDeviceClientRegistrationInfoClient.getProvisioningDeviceClientStatus() != ProvisioningDeviceClientStatus.PROVISIONING_DEVICE_STATUS_ASSIGNED) {
            if (provisioningStatus.provisioningDeviceClientRegistrationInfoClient.getProvisioningDeviceClientStatus() == ProvisioningDeviceClientStatus.PROVISIONING_DEVICE_STATUS_ERROR || provisioningStatus.provisioningDeviceClientRegistrationInfoClient.getProvisioningDeviceClientStatus() == ProvisioningDeviceClientStatus.PROVISIONING_DEVICE_STATUS_DISABLED || provisioningStatus.provisioningDeviceClientRegistrationInfoClient.getProvisioningDeviceClientStatus() == ProvisioningDeviceClientStatus.PROVISIONING_DEVICE_STATUS_FAILED) {
                provisioningStatus.exception.printStackTrace();
                System.out.println("Registration error, bailing out");
                break;
            }
            System.out.println("Waiting for Provisioning Service to register");
            Thread.sleep(MAX_TIME_TO_WAIT_FOR_REGISTRATION);
        }
        if (provisioningStatus.provisioningDeviceClientRegistrationInfoClient.getProvisioningDeviceClientStatus() == ProvisioningDeviceClientStatus.PROVISIONING_DEVICE_STATUS_ASSIGNED) {
            System.out.println("IotHUb Uri : " + provisioningStatus.provisioningDeviceClientRegistrationInfoClient.getIothubUri());
            System.out.println("Device ID : " + provisioningStatus.provisioningDeviceClientRegistrationInfoClient.getDeviceId());
            // connect to iothub
            String iotHubUri = provisioningStatus.provisioningDeviceClientRegistrationInfoClient.getIothubUri();
            String deviceId = provisioningStatus.provisioningDeviceClientRegistrationInfoClient.getDeviceId();
            try {
                deviceClient = DeviceClient.createFromSecurityProvider(iotHubUri, deviceId, securityClientTPMEmulator, IotHubClientProtocol.MQTT);
                deviceClient.open();
                Message messageToSendFromDeviceToHub = new Message("Whatever message you would like to send");
                System.out.println("Sending message from device to IoT Hub...");
                deviceClient.sendEventAsync(messageToSendFromDeviceToHub, new IotHubEventCallbackImpl(), null);
            } catch (IOException e) {
                System.out.println("Device client threw an exception: " + e.getMessage());
                if (deviceClient != null) {
                    deviceClient.closeNow();
                }
            }
        }
    } catch (ProvisioningDeviceClientException | InterruptedException e) {
        System.out.println("Provisioning Device Client threw an exception" + e.getMessage());
        if (provisioningDeviceClient != null) {
            provisioningDeviceClient.closeNow();
        }
    }
    System.out.println("Press any key to exit...");
    scanner.nextLine();
    if (provisioningDeviceClient != null) {
        provisioningDeviceClient.closeNow();
    }
    if (deviceClient != null) {
        deviceClient.closeNow();
    }
    System.out.println("Shutting down...");
}
Also used : Scanner(java.util.Scanner) SecurityProviderTpm(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderTpm) SecurityProviderException(com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException) IOException(java.io.IOException) ProvisioningDeviceClientException(com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceClientException) SecurityProviderTPMEmulator(com.microsoft.azure.sdk.iot.provisioning.security.hsm.SecurityProviderTPMEmulator)

Example 4 with SecurityProviderException

use of com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException in project azure-iot-sdk-java by Azure.

the class SecurityProviderTpm method getRegistrationId.

@Override
public String getRegistrationId() throws SecurityProviderException {
    try {
        // SRS_SecurityClientTpm_25_001: [ This method shall retrieve the EnrollmentKey from the implementation of this abstract class. ]
        byte[] enrollmentKey = this.getEndorsementKey();
        // SRS_SecurityClientTpm_25_002: [ This method shall hash the EnrollmentKey using SHA-256. ]
        MessageDigest digest = MessageDigest.getInstance(SHA_256);
        byte[] hash = digest.digest(enrollmentKey);
        // SRS_SecurityClientTpm_25_003: [ This method shall convert the resultant hash to Base32 to convert all the data to be case agnostic and remove "=" from the string. ]
        Base32 base32 = new Base32();
        byte[] base32Encoded = base32.encode(hash);
        String registrationId = new String(base32Encoded, StandardCharsets.UTF_8).toLowerCase();
        if (registrationId.contains(EQUALS)) {
            registrationId = registrationId.replace(EQUALS, "").toLowerCase();
        }
        return registrationId;
    } catch (NoSuchAlgorithmException e) {
        // SRS_SecurityClientTpm_25_008: [ This method shall throw SecurityProviderException if any of the underlying API's in generating registration Id. ]
        throw new SecurityProviderException(e);
    }
}
Also used : SecurityProviderException(com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException) Base32(org.apache.commons.codec.binary.Base32)

Example 5 with SecurityProviderException

use of com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException in project azure-iot-sdk-java by Azure.

the class RegisterTask method authenticateWithDPS.

private RegistrationOperationStatusParser authenticateWithDPS() throws ProvisioningDeviceClientException, SecurityProviderException {
    if (securityProvider.getRegistrationId() == null) {
        throw new ProvisioningDeviceClientException(new IllegalArgumentException("registration id cannot be null"));
    }
    try {
        SSLContext sslContext = securityProvider.getSSLContext();
        if (sslContext == null) {
            throw new ProvisioningDeviceSecurityException("Null SSL Context received from security client");
        }
        authorization.setSslContext(sslContext);
        if (this.securityProvider instanceof SecurityProviderX509) {
            RequestData requestData = new RequestData(securityProvider.getRegistrationId(), sslContext, true, this.provisioningDeviceClientConfig.getPayload());
            log.info("Authenticating with device provisioning service using x509 certificates");
            return this.authenticateWithX509(requestData);
        } else if (this.securityProvider instanceof SecurityProviderTpm) {
            SecurityProviderTpm securityProviderTpm = (SecurityProviderTpm) securityProvider;
            if (securityProviderTpm.getEndorsementKey() == null || securityProviderTpm.getStorageRootKey() == null) {
                throw new ProvisioningDeviceSecurityException(new IllegalArgumentException("Ek or SRK cannot be null"));
            }
            // SRS_RegisterTask_25_009: [ If the provided security client is for Key then, this method shall save the SSL context to Authorization if it is not null and throw ProvisioningDeviceClientException otherwise. ]
            RequestData requestData = new RequestData(securityProviderTpm.getEndorsementKey(), securityProviderTpm.getStorageRootKey(), securityProvider.getRegistrationId(), sslContext, null, this.provisioningDeviceClientConfig.getPayload());
            log.info("Authenticating with device provisioning service using tpm");
            return this.authenticateWithTPM(requestData);
        } else if (this.securityProvider instanceof SecurityProviderSymmetricKey) {
            RequestData requestData = new RequestData(securityProvider.getRegistrationId(), sslContext, null, this.provisioningDeviceClientConfig.getPayload());
            log.info("Authenticating with device provisioning service using symmetric key");
            return this.authenticateWithSasToken(requestData);
        } else {
            throw new ProvisioningDeviceSecurityException("Unknown Security client received");
        }
    } catch (SecurityProviderException | IOException | InterruptedException e) {
        throw new ProvisioningDeviceSecurityException(e);
    }
}
Also used : ProvisioningDeviceSecurityException(com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceSecurityException) SecurityProviderTpm(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderTpm) SecurityProviderX509(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderX509) SecurityProviderSymmetricKey(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderSymmetricKey) SecurityProviderException(com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) ProvisioningDeviceClientException(com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceClientException)

Aggregations

SecurityProviderException (com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException)15 ProvisioningDeviceClientException (com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceClientException)4 IOException (java.io.IOException)4 SecurityProviderTpm (com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderTpm)3 Test (org.junit.Test)3 ProvisioningDeviceSecurityException (com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceSecurityException)2 SecurityProviderX509 (com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderX509)2 Scanner (java.util.Scanner)2 SSLContext (javax.net.ssl.SSLContext)2 IotHubAuthenticationProvider (com.microsoft.azure.sdk.iot.device.auth.IotHubAuthenticationProvider)1 IotHubX509HardwareAuthenticationProvider (com.microsoft.azure.sdk.iot.device.auth.IotHubX509HardwareAuthenticationProvider)1 ProvisioningErrorParser (com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.ProvisioningErrorParser)1 RegistrationOperationStatusParser (com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.RegistrationOperationStatusParser)1 SecurityProviderSymmetricKey (com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderSymmetricKey)1 SecurityProviderDiceEmulator (com.microsoft.azure.sdk.iot.provisioning.security.hsm.SecurityProviderDiceEmulator)1 SecurityProviderTPMEmulator (com.microsoft.azure.sdk.iot.provisioning.security.hsm.SecurityProviderTPMEmulator)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 UnknownHostException (java.net.UnknownHostException)1 BufferUnderflowException (java.nio.BufferUnderflowException)1 X509Certificate (java.security.cert.X509Certificate)1