Search in sources :

Example 6 with SecurityProviderTpm

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

the class SecurityProviderTpmTest method getSSLContextSucceeds.

// SRS_SecurityClientTpm_25_004: [ This method shall generate SSLContext for this flow. ]
// SRS_SecurityClientTpm_25_006: [ This method shall load the keystore with TrustedCerts. ]
// SRS_SecurityClientTpm_25_007: [ This method shall initialize SSLContext with the default trustManager loaded with keystore. ]
// SRS_SecurityClient_25_001: [ This method shall retrieve the default instance of keystore using default algorithm type. ]
// SRS_SecurityClient_25_002: [ This method shall retrieve the default CertificateFactory instance. ]
// SRS_SecurityClient_25_003: [ This method shall load all the trusted certificates to the keystore. ]
@Test
public void getSSLContextSucceeds() throws SecurityProviderException, KeyManagementException, KeyStoreException, CertificateException {
    // arrange
    SecurityProviderTpm securityClientTpm = new SecurityProviderTPMTestImpl(ENROLLMENT_KEY);
    // act
    securityClientTpm.getSSLContext();
    new Verifications() {

        {
            mockedKeyStore.setCertificateEntry(anyString, (Certificate) any);
            times = 4;
            mockedSslContext.init((KeyManager[]) any, (TrustManager[]) any, (SecureRandom) any);
            times = 1;
        }
    };
}
Also used : SecurityProviderTpm(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderTpm) Verifications(mockit.Verifications) KeyManager(javax.net.ssl.KeyManager) TrustManager(javax.net.ssl.TrustManager) Test(org.junit.Test)

Example 7 with SecurityProviderTpm

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

the class SecurityProviderTpmTest method getSSLContextThrowsUnderlyingException.

// SRS_SecurityClientTpm_25_005: [ This method shall throw SecurityProviderException if any of the underlying API's in generating SSL context fails. ]
@Test(expected = SecurityProviderException.class)
public void getSSLContextThrowsUnderlyingException() throws SecurityProviderException, KeyStoreException {
    // arrange
    SecurityProviderTpm securityClientTpm = new SecurityProviderTPMTestImpl(ENROLLMENT_KEY);
    new NonStrictExpectations() {

        {
            mockedKeyStore.setCertificateEntry(anyString, (Certificate) any);
            result = new KeyStoreException();
        }
    };
    // act
    securityClientTpm.getSSLContext();
}
Also used : SecurityProviderTpm(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderTpm) NonStrictExpectations(mockit.NonStrictExpectations) Test(org.junit.Test)

Example 8 with SecurityProviderTpm

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

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

the class IotHubSasTokenHardwareAuthenticationProviderTest method securityProviderConstructorSavesNeededInfo.

// Tests_SRS_IOTHUBSASTOKENHARDWAREAUTHENTICATION_34_033: [This constructor shall generate and save a sas token from the security provider with the default time to live.]
// Tests_SRS_IOTHUBSASTOKENHARDWAREAUTHENTICATION_34_034: [This constructor shall retrieve and save the ssl context from the security provider.]
@Test
public void securityProviderConstructorSavesNeededInfo() throws IOException, InvalidKeyException, SecurityProviderException {
    // arrange
    final String someToken = "someToken";
    final byte[] tokenBytes = someToken.getBytes(StandardCharsets.UTF_8);
    new Expectations() {

        {
            URLEncoder.encode(anyString, encodingName);
            result = someToken;
            mockSecurityProviderTpm.signWithIdentity((byte[]) any);
            result = tokenBytes;
            URLEncoder.encode(anyString, encodingName);
            result = someToken;
            mockSecurityProviderTpm.getSSLContext();
            result = mockSSLContext;
            Deencapsulation.newInstance(IotHubSSLContext.class, new Class[] { SSLContext.class }, mockSSLContext);
            result = mockIotHubSSLContext;
        }
    };
    // act
    IotHubSasTokenAuthenticationProvider sasTokenAuthentication = new IotHubSasTokenHardwareAuthenticationProvider(expectedHostname, expectedGatewayHostname, expectedDeviceId, expectedModuleId, mockSecurityProviderTpm);
    // assert
    String actualHostname = sasTokenAuthentication.getHostname();
    String actualDeviceId = sasTokenAuthentication.getDeviceId();
    String actualModuleId = sasTokenAuthentication.getModuleId();
    SecurityProviderTpm actualSecurityProvider = Deencapsulation.getField(sasTokenAuthentication, "securityProvider");
    assertEquals(expectedHostname, actualHostname);
    assertEquals(expectedDeviceId, actualDeviceId);
    assertEquals(expectedModuleId, actualModuleId);
    assertEquals(mockSecurityProviderTpm, actualSecurityProvider);
}
Also used : SecurityProviderTpm(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderTpm) Test(org.junit.Test)

Example 10 with SecurityProviderTpm

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

the class RegisterTask method constructSasToken.

private String constructSasToken() throws ProvisioningDeviceClientException, UnsupportedEncodingException, SecurityProviderException {
    if (RegisterTask.DEFAULT_EXPIRY_TIME_IN_SECS <= 0) {
        throw new IllegalArgumentException("expiry time cannot be negative or zero");
    }
    String registrationId = securityProvider.getRegistrationId();
    String tokenScope = new UrlPathBuilder(provisioningDeviceClientConfig.getIdScope()).generateSasTokenUrl(registrationId);
    if (tokenScope == null || tokenScope.isEmpty()) {
        throw new ProvisioningDeviceClientException("Could not construct token scope");
    }
    Long expiryTimeUTC = System.currentTimeMillis() / 1000 + RegisterTask.DEFAULT_EXPIRY_TIME_IN_SECS;
    String value = tokenScope.concat("\n" + expiryTimeUTC);
    byte[] token = null;
    if (securityProvider instanceof SecurityProviderTpm) {
        SecurityProviderTpm securityClientTpm = (SecurityProviderTpm) securityProvider;
        token = securityClientTpm.signWithIdentity(value.getBytes(StandardCharsets.UTF_8));
    } else if (securityProvider instanceof SecurityProviderSymmetricKey) {
        SecurityProviderSymmetricKey securityProviderSymmetricKey = (SecurityProviderSymmetricKey) securityProvider;
        token = securityProviderSymmetricKey.HMACSignData(value.getBytes(StandardCharsets.UTF_8.displayName()), decodeBase64(securityProviderSymmetricKey.getSymmetricKey()));
    }
    if (token == null || token.length == 0) {
        throw new ProvisioningDeviceSecurityException("Security client could not sign data successfully");
    }
    byte[] base64Signature = encodeBase64(token);
    String base64UrlEncodedSignature = URLEncoder.encode(new String(base64Signature, StandardCharsets.UTF_8), StandardCharsets.UTF_8.displayName());
    // SRS_RegisterTask_25_015: [ If the provided security client is for Key then, this method shall build the SasToken of the format SharedAccessSignature sr=<tokenScope>&sig=<signature>&se=<expiryTime>&skn= and save it to authorization]
    return String.format(SASTOKEN_FORMAT, tokenScope, base64UrlEncodedSignature, expiryTimeUTC);
}
Also used : ProvisioningDeviceSecurityException(com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceSecurityException) UrlPathBuilder(com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder) SecurityProviderTpm(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderTpm) SecurityProviderSymmetricKey(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderSymmetricKey) 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