Search in sources :

Example 1 with SecurityProvider

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

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

the class IotHubX509HardwareIotHubAuthenticationProviderTest method constructorSuccess.

// Tests_SRS_IOTHUBX509HARDWAREAUTHENTICATION_34_001: [This function shall save the provided security provider.]
@Test
public void constructorSuccess() {
    // act
    IotHubAuthenticationProvider authentication = new IotHubX509HardwareAuthenticationProvider(hostname, gatewayHostname, deviceId, moduleId, mockSecurityProviderX509);
    // assert
    SecurityProvider actualSecurityProvider = Deencapsulation.getField(authentication, "securityProviderX509");
    assertEquals(mockSecurityProviderX509, actualSecurityProvider);
}
Also used : IotHubAuthenticationProvider(com.microsoft.azure.sdk.iot.device.auth.IotHubAuthenticationProvider) IotHubX509HardwareAuthenticationProvider(com.microsoft.azure.sdk.iot.device.auth.IotHubX509HardwareAuthenticationProvider) SecurityProvider(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProvider) Test(org.junit.Test)

Example 3 with SecurityProvider

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

Example 4 with SecurityProvider

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

the class ProvisioningTests method individualEnrollmentGetAttestationMechanismTPM.

@Test
public void individualEnrollmentGetAttestationMechanismTPM() throws ProvisioningServiceClientException, SecurityProviderException {
    // with the other TPM tests, so it lives here with them
    if (testInstance.attestationType != AttestationType.TPM) {
        return;
    }
    if (testInstance.protocol != HTTPS) {
        // The test protocol has no bearing on this test since it only uses the provisioning service client, so the test should only run once.
        return;
    }
    SecurityProvider securityProvider = new SecurityProviderTPMEmulator(testInstance.registrationId, MAX_TPM_CONNECT_RETRY_ATTEMPTS);
    Attestation attestation = new TpmAttestation(new String(encodeBase64(((SecurityProviderTpm) securityProvider).getEndorsementKey())));
    IndividualEnrollment individualEnrollment = new IndividualEnrollment(testInstance.registrationId, attestation);
    testInstance.provisioningServiceClient.createOrUpdateIndividualEnrollment(individualEnrollment);
    AttestationMechanism retrievedAttestationMechanism = testInstance.provisioningServiceClient.getIndividualEnrollmentAttestationMechanism(testInstance.registrationId);
    assertEquals(retrievedAttestationMechanism.getType(), AttestationMechanismType.TPM);
    assertTrue(retrievedAttestationMechanism.getAttestation() instanceof TpmAttestation);
    TpmAttestation retrievedTpmAttestation = (TpmAttestation) retrievedAttestationMechanism.getAttestation();
    assertNotNull(retrievedTpmAttestation.getEndorsementKey());
}
Also used : SecurityProviderTPMEmulator(com.microsoft.azure.sdk.iot.provisioning.security.hsm.SecurityProviderTPMEmulator) SecurityProvider(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProvider) IotHubConnectionString(com.microsoft.azure.sdk.iot.service.IotHubConnectionString) ContinuousIntegrationTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.ContinuousIntegrationTest) StandardTierHubOnlyTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.StandardTierHubOnlyTest) Test(org.junit.Test) DeviceProvisioningServiceTest(tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.DeviceProvisioningServiceTest)

Example 5 with SecurityProvider

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

the class ProvisioningTPMTests method provisioningTpmFlow.

@Test
public void provisioningTpmFlow() throws SecurityProviderException, ProvisioningServiceClientException, ProvisioningDeviceClientException, InterruptedException {
    ProvisioningServiceClient provisioningServiceClient = ProvisioningServiceClient.createFromConnectionString(provisioningServiceConnectionString);
    String registrationId = UUID.randomUUID().toString();
    String provisionedDeviceId = "Some-Provisioned-Device-" + TPM + "-" + UUID.randomUUID().toString();
    SecurityProvider securityProvider = new SecurityProviderTPMEmulator(registrationId);
    Attestation attestation = new TpmAttestation(new String(encodeBase64(((SecurityProviderTpm) securityProvider).getEndorsementKey())));
    IndividualEnrollment individualEnrollment = new IndividualEnrollment(registrationId, attestation);
    individualEnrollment.setDeviceIdFinal(provisionedDeviceId);
    provisioningServiceClient.createOrUpdateIndividualEnrollment(individualEnrollment);
    ProvisioningDeviceClient provisioningDeviceClient = ProvisioningDeviceClient.create(provisioningServiceGlobalEndpoint, provisioningServiceIdScope, ProvisioningDeviceClientTransportProtocol.AMQPS, securityProvider);
    AtomicBoolean registrationCompleted = new AtomicBoolean(false);
    AtomicBoolean registrationCompletedSuccessfully = new AtomicBoolean(false);
    provisioningDeviceClient.registerDevice((provisioningDeviceClientRegistrationResult, e, context) -> {
        log.debug("Provisioning registration callback fired with result {}", provisioningDeviceClientRegistrationResult.getProvisioningDeviceClientStatus());
        if (e != null) {
            log.error("Provisioning registration callback fired with exception {}", e);
        }
        ProvisioningDeviceClientStatus status = provisioningDeviceClientRegistrationResult.getProvisioningDeviceClientStatus();
        if (status == ProvisioningDeviceClientStatus.PROVISIONING_DEVICE_STATUS_ASSIGNED) {
            registrationCompletedSuccessfully.set(true);
        }
        registrationCompleted.set(true);
    }, null);
    long startTime = System.currentTimeMillis();
    while (!registrationCompleted.get()) {
        Thread.sleep(200);
        if (System.currentTimeMillis() - startTime > REGISTRATION_TIMEOUT_MILLISECONDS) {
            fail("Timed out waiting for device registration to complete.");
        }
    }
    assertTrue("Registration completed, but not successfully", registrationCompletedSuccessfully.get());
    provisioningDeviceClient.closeNow();
}
Also used : IndividualEnrollment(com.microsoft.azure.sdk.iot.provisioning.service.configs.IndividualEnrollment) ProvisioningDeviceClient(com.microsoft.azure.sdk.iot.provisioning.device.ProvisioningDeviceClient) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SecurityProviderTPMEmulator(com.microsoft.azure.sdk.iot.provisioning.security.hsm.SecurityProviderTPMEmulator) ProvisioningDeviceClientStatus(com.microsoft.azure.sdk.iot.provisioning.device.ProvisioningDeviceClientStatus) TpmAttestation(com.microsoft.azure.sdk.iot.provisioning.service.configs.TpmAttestation) SecurityProvider(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProvider) TpmAttestation(com.microsoft.azure.sdk.iot.provisioning.service.configs.TpmAttestation) Attestation(com.microsoft.azure.sdk.iot.provisioning.service.configs.Attestation) ProvisioningServiceClient(com.microsoft.azure.sdk.iot.provisioning.service.ProvisioningServiceClient) Test(org.junit.Test)

Aggregations

SecurityProvider (com.microsoft.azure.sdk.iot.provisioning.security.SecurityProvider)5 SecurityProviderTPMEmulator (com.microsoft.azure.sdk.iot.provisioning.security.hsm.SecurityProviderTPMEmulator)3 Test (org.junit.Test)3 SecurityProviderX509Cert (com.microsoft.azure.sdk.iot.provisioning.security.hsm.SecurityProviderX509Cert)2 IotHubAuthenticationProvider (com.microsoft.azure.sdk.iot.device.auth.IotHubAuthenticationProvider)1 IotHubX509HardwareAuthenticationProvider (com.microsoft.azure.sdk.iot.device.auth.IotHubX509HardwareAuthenticationProvider)1 ProvisioningDeviceClient (com.microsoft.azure.sdk.iot.provisioning.device.ProvisioningDeviceClient)1 ProvisioningDeviceClientStatus (com.microsoft.azure.sdk.iot.provisioning.device.ProvisioningDeviceClientStatus)1 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 ProvisioningServiceClient (com.microsoft.azure.sdk.iot.provisioning.service.ProvisioningServiceClient)1 Attestation (com.microsoft.azure.sdk.iot.provisioning.service.configs.Attestation)1 IndividualEnrollment (com.microsoft.azure.sdk.iot.provisioning.service.configs.IndividualEnrollment)1 TpmAttestation (com.microsoft.azure.sdk.iot.provisioning.service.configs.TpmAttestation)1 IotHubConnectionString (com.microsoft.azure.sdk.iot.service.IotHubConnectionString)1 IOException (java.io.IOException)1 Scanner (java.util.Scanner)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 ContinuousIntegrationTest (tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.ContinuousIntegrationTest)1