Search in sources :

Example 1 with SecurityProviderTpm

use of com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderTpm 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 2 with SecurityProviderTpm

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

the class ProvisioningTask method executeStateMachineForStatus.

private void executeStateMachineForStatus(RegistrationOperationStatusParser registrationOperationStatusParser) throws TimeoutException, InterruptedException, ExecutionException, ProvisioningDeviceClientException, SecurityProviderException {
    boolean isContinue = false;
    RegistrationOperationStatusParser statusRegistrationOperationStatusParser = registrationOperationStatusParser;
    ProvisioningStatus nextStatus = ProvisioningStatus.fromString(registrationOperationStatusParser.getStatus());
    log.info("Current provisioning status: {}", nextStatus);
    // continue invoking for status until a terminal state is reached
    do {
        if (nextStatus == null) {
            throw new ProvisioningDeviceClientException("Did not receive a valid status");
        }
        switch(nextStatus) {
            case UNASSIGNED:
            // intended fall through
            case ASSIGNING:
                log.trace("Polling device provisioning service for status of registration...");
                statusRegistrationOperationStatusParser = this.invokeStatus(registrationOperationStatusParser.getOperationId());
                nextStatus = ProvisioningStatus.fromString(statusRegistrationOperationStatusParser.getStatus());
                isContinue = true;
                break;
            case ASSIGNED:
                this.dpsStatus = PROVISIONING_DEVICE_STATUS_ASSIGNED;
                DeviceRegistrationResultParser registrationStatus = statusRegistrationOperationStatusParser.getRegistrationState();
                if (registrationStatus == null || registrationStatus.getAssignedHub() == null || registrationStatus.getAssignedHub().isEmpty() || registrationStatus.getDeviceId() == null || registrationStatus.getDeviceId().isEmpty()) {
                    // Codes_SRS_ProvisioningTask_34_018: [Upon reaching the terminal state ASSIGNED, if the registration status json is missing an assigned hub or device id, this function shall throw a ProvisioningDeviceClientException.]
                    throw new ProvisioningDeviceClientException("Could not retrieve Assigned Hub or Device ID and status changed to Assigned");
                }
                RegistrationResult registrationInfo = new RegistrationResult(registrationStatus.getAssignedHub(), registrationStatus.getDeviceId(), registrationStatus.getPayload(), PROVISIONING_DEVICE_STATUS_ASSIGNED);
                registrationInfo.setRegistrationId(registrationStatus.getRegistrationId());
                registrationInfo.setStatus(registrationStatus.getStatus());
                registrationInfo.setSubstatus(ProvisioningDeviceClientSubstatus.fromString(registrationStatus.getSubstatus()));
                registrationInfo.setCreatedDateTimeUtc(registrationStatus.getCreatedDateTimeUtc());
                registrationInfo.setLastUpdatesDateTimeUtc(registrationStatus.getLastUpdatesDateTimeUtc());
                registrationInfo.setETag(registrationStatus.getEtag());
                if (this.securityProvider instanceof SecurityProviderTpm) {
                    if (registrationStatus.getTpm() == null || registrationStatus.getTpm().getAuthenticationKey() == null || registrationStatus.getTpm().getAuthenticationKey().isEmpty()) {
                        // Codes_SRS_ProvisioningTask_34_017: [Upon reaching the terminal state ASSIGNED, if the saved security client is an instance of SecurityClientTpm and if the registration status json does not contain an authentication key, this function shall throw a ProvisioningDeviceClientException.]
                        throw new ProvisioningDeviceClientException("Could not retrieve Authentication key when status was assigned");
                    }
                    // Codes_SRS_ProvisioningTask_34_016: [Upon reaching the terminal state ASSIGNED, if the saved security client is an instance of SecurityClientTpm, the security client shall decrypt and store the authentication key from the statusResponseParser.]
                    String authenticationKey = registrationStatus.getTpm().getAuthenticationKey();
                    ((SecurityProviderTpm) this.securityProvider).activateIdentityKey(decodeBase64(authenticationKey.getBytes(StandardCharsets.UTF_8)));
                }
                log.info("Device provisioning service assigned the device successfully");
                this.invokeRegistrationCallback(registrationInfo, null);
                isContinue = false;
                break;
            case FAILED:
                this.dpsStatus = PROVISIONING_DEVICE_STATUS_FAILED;
                String errorMessage = statusRegistrationOperationStatusParser.getRegistrationState().getErrorMessage();
                ProvisioningDeviceHubException dpsHubException = new ProvisioningDeviceHubException(errorMessage);
                dpsHubException.setErrorCode(registrationOperationStatusParser.getRegistrationState().getErrorCode());
                registrationInfo = new RegistrationResult(null, null, null, PROVISIONING_DEVICE_STATUS_FAILED);
                log.error("Device provisioning service failed to provision the device, finished with status FAILED: {}", errorMessage);
                this.invokeRegistrationCallback(registrationInfo, dpsHubException);
                isContinue = false;
                break;
            case DISABLED:
                this.dpsStatus = PROVISIONING_DEVICE_STATUS_DISABLED;
                String disabledErrorMessage = statusRegistrationOperationStatusParser.getRegistrationState().getErrorMessage();
                dpsHubException = new ProvisioningDeviceHubException(disabledErrorMessage);
                dpsHubException.setErrorCode(registrationOperationStatusParser.getRegistrationState().getErrorCode());
                registrationInfo = new RegistrationResult(null, null, null, PROVISIONING_DEVICE_STATUS_DISABLED);
                log.error("Device provisioning service failed to provision the device, finished with status DISABLED: {}", disabledErrorMessage);
                this.invokeRegistrationCallback(registrationInfo, dpsHubException);
                isContinue = false;
                break;
        }
    } while (isContinue);
}
Also used : ProvisioningDeviceHubException(com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceHubException) RegistrationOperationStatusParser(com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.RegistrationOperationStatusParser) SecurityProviderTpm(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderTpm) DeviceRegistrationResultParser(com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.DeviceRegistrationResultParser) ProvisioningDeviceClientException(com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceClientException)

Example 3 with SecurityProviderTpm

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

the class SecurityProviderTpmTest method getRegistrationIdSucceeds.

// SRS_SecurityClientTpm_25_001: [ This method shall retrieve the EnrollmentKey from the implementation of this abstract class. ]
// SRS_SecurityClientTpm_25_002: [ This method shall hash the EnrollmentKey using SHA-256. ]
// 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. ]
@Test
public void getRegistrationIdSucceeds() throws SecurityProviderException, EncoderException {
    // arrange
    SecurityProviderTpm securityClientTpm = new SecurityProviderTPMTestImpl(ENROLLMENT_KEY);
    // act
    String actualRegistrationId = securityClientTpm.getRegistrationId();
    // assert
    assertNotNull(actualRegistrationId);
    assertEquals(actualRegistrationId, actualRegistrationId.toLowerCase());
    assertFalse(actualRegistrationId.contains("="));
    new Verifications() {

        {
            mockedMessageDigest.digest(ENROLLMENT_KEY);
            times = 1;
            mockedBase32.encode((byte[]) any);
            times = 1;
        }
    };
}
Also used : SecurityProviderTpm(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderTpm) Verifications(mockit.Verifications) Test(org.junit.Test)

Example 4 with SecurityProviderTpm

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

the class SecurityProviderTpmTest method getRegistrationIdThrowsSecurityClientException.

// SRS_SecurityClientTpm_25_008: [ This method shall throw SecurityProviderException if any of the underlying API's in generating registration Id. ]
@Test(expected = SecurityProviderException.class)
public void getRegistrationIdThrowsSecurityClientException() throws SecurityProviderException, NoSuchAlgorithmException {
    // arrange
    SecurityProviderTpm securityClientTpm = new SecurityProviderTPMTestImpl(ENROLLMENT_KEY);
    new NonStrictExpectations() {

        {
            MessageDigest.getInstance("SHA-256");
            result = new NoSuchAlgorithmException();
        }
    };
    // act
    securityClientTpm.getRegistrationId();
}
Also used : SecurityProviderTpm(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderTpm) NonStrictExpectations(mockit.NonStrictExpectations) Test(org.junit.Test)

Example 5 with SecurityProviderTpm

use of com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderTpm 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

SecurityProviderTpm (com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderTpm)11 ProvisioningDeviceClientException (com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceClientException)5 Test (org.junit.Test)5 SecurityProviderSymmetricKey (com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderSymmetricKey)3 IOException (java.io.IOException)3 ProvisioningDeviceSecurityException (com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceSecurityException)2 SecurityProviderException (com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException)2 SecurityProviderTPMEmulator (com.microsoft.azure.sdk.iot.provisioning.security.hsm.SecurityProviderTPMEmulator)2 NonStrictExpectations (mockit.NonStrictExpectations)2 Verifications (mockit.Verifications)2 UrlPathBuilder (com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder)1 ProvisioningDeviceClientAuthenticationException (com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceClientAuthenticationException)1 ProvisioningDeviceHubException (com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceHubException)1 DeviceRegistrationResultParser (com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.DeviceRegistrationResultParser)1 RegistrationOperationStatusParser (com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.RegistrationOperationStatusParser)1 SecurityProvider (com.microsoft.azure.sdk.iot.provisioning.security.SecurityProvider)1 SecurityProviderX509 (com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderX509)1 SecurityProviderX509Cert (com.microsoft.azure.sdk.iot.provisioning.security.hsm.SecurityProviderX509Cert)1 Scanner (java.util.Scanner)1 KeyManager (javax.net.ssl.KeyManager)1