Search in sources :

Example 1 with SecurityProviderX509Cert

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

the class ProvisioningX509Sample method main.

public static void main(String[] args) throws Exception {
    System.out.println("Starting...");
    System.out.println("Beginning setup.");
    ProvisioningDeviceClient provisioningDeviceClient = null;
    DeviceClient deviceClient = null;
    try {
        ProvisioningStatus provisioningStatus = new ProvisioningStatus();
        // For group enrollment uncomment this line
        // signerCertificates.add("<Your Signer/intermediate Certificate Here>");
        SecurityProvider securityProviderX509 = new SecurityProviderX509Cert(leafPublicPem, leafPrivateKey, signerCertificates);
        provisioningDeviceClient = ProvisioningDeviceClient.create(globalEndpoint, idScope, PROVISIONING_DEVICE_CLIENT_TRANSPORT_PROTOCOL, securityProviderX509);
        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, securityProviderX509, 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 scanner = new Scanner(System.in, StandardCharsets.UTF_8.name());
    scanner.nextLine();
    System.out.println("Shutting down...");
    if (provisioningDeviceClient != null) {
        provisioningDeviceClient.closeNow();
    }
    if (deviceClient != null) {
        deviceClient.closeNow();
    }
}
Also used : Scanner(java.util.Scanner) IOException(java.io.IOException) ProvisioningDeviceClientException(com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceClientException) SecurityProvider(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProvider) SecurityProviderX509Cert(com.microsoft.azure.sdk.iot.provisioning.security.hsm.SecurityProviderX509Cert)

Example 2 with SecurityProviderX509Cert

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

the class ProvisioningCommon method getSecurityProviderInstance.

public SecurityProvider getSecurityProviderInstance(EnrollmentType enrollmentType, AllocationPolicy allocationPolicy, ReprovisionPolicy reprovisionPolicy, CustomAllocationDefinition customAllocationDefinition, List<String> iothubs, DeviceCapabilities deviceCapabilities) throws ProvisioningServiceClientException, GeneralSecurityException, SecurityProviderException {
    SecurityProvider securityProvider = null;
    TwinCollection tags = new TwinCollection();
    final String TEST_KEY_TAG = "testTag";
    final String TEST_VALUE_TAG = "testValue";
    tags.put(TEST_KEY_TAG, TEST_VALUE_TAG);
    final String TEST_KEY_DP = "testDP";
    final String TEST_VALUE_DP = "testDPValue";
    TwinCollection desiredProperties = new TwinCollection();
    desiredProperties.put(TEST_KEY_DP, TEST_VALUE_DP);
    TwinState twinState = new TwinState(tags, desiredProperties);
    if (enrollmentType == EnrollmentType.GROUP) {
        if (testInstance.attestationType == AttestationType.TPM) {
            throw new UnsupportedOperationException("Group enrollments cannot use tpm attestation");
        } else if (testInstance.attestationType == AttestationType.X509) {
            throw new UnsupportedOperationException("Test code hasn't been written to test Group x509 enrollments yet");
        } else if (testInstance.attestationType == AttestationType.SYMMETRIC_KEY) {
            testInstance.groupId = "java-provisioning-test-group-id-" + testInstance.attestationType.toString().toLowerCase().replace("_", "-") + "-" + UUID.randomUUID().toString();
            testInstance.enrollmentGroup = new EnrollmentGroup(testInstance.groupId, new SymmetricKeyAttestation(null, null));
            testInstance.enrollmentGroup.setInitialTwinFinal(twinState);
            testInstance.enrollmentGroup.setAllocationPolicy(allocationPolicy);
            testInstance.enrollmentGroup.setReprovisionPolicy(reprovisionPolicy);
            testInstance.enrollmentGroup.setCustomAllocationDefinition(customAllocationDefinition);
            testInstance.enrollmentGroup.setIotHubs(iothubs);
            testInstance.enrollmentGroup.setCapabilities(deviceCapabilities);
            testInstance.enrollmentGroup = testInstance.provisioningServiceClient.createOrUpdateEnrollmentGroup(testInstance.enrollmentGroup);
            Attestation attestation = testInstance.enrollmentGroup.getAttestation();
            assertTrue(attestation instanceof SymmetricKeyAttestation);
            assertNotNull(testInstance.enrollmentGroup.getInitialTwin());
            assertEquals(TEST_VALUE_TAG, testInstance.enrollmentGroup.getInitialTwin().getTags().get(TEST_KEY_TAG));
            assertEquals(TEST_VALUE_DP, testInstance.enrollmentGroup.getInitialTwin().getDesiredProperty().get(TEST_KEY_DP));
            SymmetricKeyAttestation symmetricKeyAttestation = (SymmetricKeyAttestation) attestation;
            byte[] derivedPrimaryKey = SecurityProviderSymmetricKey.ComputeDerivedSymmetricKey(symmetricKeyAttestation.getPrimaryKey().getBytes(StandardCharsets.UTF_8), testInstance.registrationId);
            securityProvider = new SecurityProviderSymmetricKey(derivedPrimaryKey, testInstance.registrationId);
        }
    } else if (enrollmentType == EnrollmentType.INDIVIDUAL) {
        testInstance.provisionedDeviceId = "Some-Provisioned-Device-" + testInstance.attestationType + "-" + UUID.randomUUID().toString();
        if (testInstance.attestationType == AttestationType.TPM) {
            securityProvider = new SecurityProviderTPMEmulator(testInstance.registrationId, MAX_TPM_CONNECT_RETRY_ATTEMPTS);
            Attestation attestation = new TpmAttestation(new String(encodeBase64(((SecurityProviderTpm) securityProvider).getEndorsementKey())));
            createTestIndividualEnrollment(attestation, allocationPolicy, reprovisionPolicy, customAllocationDefinition, iothubs, twinState, deviceCapabilities);
        } else if (testInstance.attestationType == AttestationType.X509) {
            X509CertificateGenerator certificateGenerator = new X509CertificateGenerator(testInstance.registrationId);
            String leafPublicPem = certificateGenerator.getPublicCertificate();
            String leafPrivateKey = certificateGenerator.getPrivateKey();
            Collection<String> signerCertificates = new LinkedList<>();
            Attestation attestation = X509Attestation.createFromClientCertificates(leafPublicPem);
            createTestIndividualEnrollment(attestation, allocationPolicy, reprovisionPolicy, customAllocationDefinition, iothubs, twinState, deviceCapabilities);
            securityProvider = new SecurityProviderX509Cert(leafPublicPem, leafPrivateKey, signerCertificates);
        } else if (testInstance.attestationType == AttestationType.SYMMETRIC_KEY) {
            Attestation attestation = new SymmetricKeyAttestation(null, null);
            createTestIndividualEnrollment(attestation, allocationPolicy, reprovisionPolicy, customAllocationDefinition, iothubs, twinState, deviceCapabilities);
            assertTrue(CorrelationDetailsLoggingAssert.buildExceptionMessageDpsIndividualOrGroup("Expected symmetric key attestation", getHostName(provisioningServiceConnectionString), testInstance.groupId, testInstance.registrationId), testInstance.individualEnrollment.getAttestation() instanceof SymmetricKeyAttestation);
            SymmetricKeyAttestation symmetricKeyAttestation = (SymmetricKeyAttestation) testInstance.individualEnrollment.getAttestation();
            securityProvider = new SecurityProviderSymmetricKey(symmetricKeyAttestation.getPrimaryKey().getBytes(StandardCharsets.UTF_8), testInstance.registrationId);
        }
        Assert.assertEquals(CorrelationDetailsLoggingAssert.buildExceptionMessageDpsIndividualOrGroup("Unexpected device id assigned", getHostName(provisioningServiceConnectionString), testInstance.groupId, testInstance.registrationId), testInstance.provisionedDeviceId, testInstance.individualEnrollment.getDeviceId());
        assertNotNull(CorrelationDetailsLoggingAssert.buildExceptionMessageDpsIndividualOrGroup("Expected twin to not be null", getHostName(provisioningServiceConnectionString), testInstance.groupId, testInstance.registrationId), testInstance.individualEnrollment.getInitialTwin());
        Assert.assertEquals(CorrelationDetailsLoggingAssert.buildExceptionMessageDpsIndividualOrGroup("Unexpected tags found", getHostName(provisioningServiceConnectionString), testInstance.groupId, testInstance.registrationId), TEST_VALUE_TAG, testInstance.individualEnrollment.getInitialTwin().getTags().get(TEST_KEY_TAG));
        Assert.assertEquals(CorrelationDetailsLoggingAssert.buildExceptionMessageDpsIndividualOrGroup("Unexpected desired properties", getHostName(provisioningServiceConnectionString), testInstance.groupId, testInstance.registrationId), TEST_VALUE_DP, testInstance.individualEnrollment.getInitialTwin().getDesiredProperty().get(TEST_KEY_DP));
    }
    return securityProvider;
}
Also used : SecurityProviderTpm(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderTpm) SecurityProviderSymmetricKey(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderSymmetricKey) SecurityProviderTPMEmulator(com.microsoft.azure.sdk.iot.provisioning.security.hsm.SecurityProviderTPMEmulator) SecurityProvider(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProvider) SecurityProviderX509Cert(com.microsoft.azure.sdk.iot.provisioning.security.hsm.SecurityProviderX509Cert)

Aggregations

SecurityProvider (com.microsoft.azure.sdk.iot.provisioning.security.SecurityProvider)2 SecurityProviderX509Cert (com.microsoft.azure.sdk.iot.provisioning.security.hsm.SecurityProviderX509Cert)2 ProvisioningDeviceClientException (com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceClientException)1 SecurityProviderSymmetricKey (com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderSymmetricKey)1 SecurityProviderTpm (com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderTpm)1 SecurityProviderTPMEmulator (com.microsoft.azure.sdk.iot.provisioning.security.hsm.SecurityProviderTPMEmulator)1 IOException (java.io.IOException)1 Scanner (java.util.Scanner)1