Search in sources :

Example 11 with SecurityProviderException

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

the class ProvisioningTask method call.

// this thread will continue to run until DPS status is assigned and registered or exit on error
// DPS State machine
/**
 * This method executes the State machine with the device goes through during registration.
 * @return Returns {@code null}
 * @throws Exception This exception is thrown if any of the exception during execution is not handled.
 */
@Override
public Object call() throws Exception {
    // The thread doesn't have any opened connections associated to it yet.
    String threadName = this.provisioningDeviceClientContract.getHostName() + "-" + this.provisioningDeviceClientConfig.getUniqueIdentifier() + "-Cxn" + "PendingConnectionId" + "-" + THREAD_NAME;
    Thread.currentThread().setName(threadName);
    try {
        // SRS_ProvisioningTask_25_015: [ This method shall invoke open call on the contract.]
        log.info("Opening the connection to device provisioning service...");
        provisioningDeviceClientContract.open(new RequestData(securityProvider.getRegistrationId(), securityProvider.getSSLContext(), securityProvider instanceof SecurityProviderX509, provisioningDeviceClientConfig.getPayload()));
        // SRS_ProvisioningTask_25_007: [ This method shall invoke Register task and status task to execute the state machine of the service as per below rules.]
        /*
            Service State Machine Rules

            SRS_ProvisioningTask_25_008: [ This method shall invoke register task and wait for it to complete.]
            SRS_ProvisioningTask_25_009: [ This method shall invoke status callback with status PROVISIONING_DEVICE_STATUS_AUTHENTICATED if register task completes successfully.]
            SRS_ProvisioningTask_25_010: [ This method shall invoke status task to get the current state of the device registration and wait until a terminal state is reached.]
            SRS_ProvisioningTask_25_011: [ Upon reaching one of the terminal state i.e ASSIGNED, this method shall invoke registration callback with the information retrieved from service for IotHub Uri and DeviceId. Also if status callback is defined then it shall be invoked with status PROVISIONING_DEVICE_STATUS_ASSIGNED.]
            SRS_ProvisioningTask_25_012: [ Upon reaching one of the terminal states i.e FAILED or DISABLED, this method shall invoke registration callback with error message received from service. Also if status callback is defined then it shall be invoked with status PROVISIONING_DEVICE_STATUS_ERROR.]
            SRS_ProvisioningTask_25_013: [ Upon reaching intermediate state i.e UNASSIGNED or ASSIGNING, this method shall continue to query for status until a terminal state is reached. Also if status callback is defined then it shall be invoked with status PROVISIONING_DEVICE_STATUS_ASSIGNING.]
            State diagram :

            One of the following states can be reached from register or status task - (A) Unassigned (B) Assigning (C) Assigned (D) Fail (E) Disable

                Return-State	A	            B	        C	        D	        E
                Register-State	B, C, D, E	    C, D, E	    terminal	terminal	terminal
                Status-State	B, C, D, E	    C, D, E	    terminal	terminal	terminal
             */
        String connectionId = this.provisioningDeviceClientConfig.getUniqueIdentifier();
        if (connectionId == null) {
            // For Symetric Key authentication, connection is not open until the registration is invoked.
            connectionId = "PendingConnectionId";
        }
        threadName = this.provisioningDeviceClientContract.getHostName() + "-" + this.provisioningDeviceClientConfig.getUniqueIdentifier() + "-Cxn" + connectionId + "-" + THREAD_NAME;
        Thread.currentThread().setName(threadName);
        log.info("Connection to device provisioning service opened successfully, sending initial device registration message");
        RegistrationOperationStatusParser registrationOperationStatusParser = this.invokeRegister();
        log.info("Waiting for device provisioning service to provision this device...");
        this.executeStateMachineForStatus(registrationOperationStatusParser);
        this.close();
    } catch (ExecutionException | TimeoutException | ProvisioningDeviceClientException | SecurityProviderException e) {
        // SRS_ProvisioningTask_25_006: [ This method shall invoke the status callback, if any of the task fail or throw any exception. ]
        this.dpsStatus = PROVISIONING_DEVICE_STATUS_ERROR;
        invokeRegistrationCallback(new RegistrationResult(null, null, null, PROVISIONING_DEVICE_STATUS_ERROR), e);
        // SRS_ProvisioningTask_25_015: [ This method shall invoke close call on the contract and close the threads started.]
        this.close();
    }
    return null;
}
Also used : RegistrationOperationStatusParser(com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.RegistrationOperationStatusParser) SecurityProviderX509(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderX509) SecurityProviderException(com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException) ProvisioningDeviceClientException(com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceClientException)

Example 12 with SecurityProviderException

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

the class SecurityProviderTPMEmulator method localTpmSimulatorWithRetry.

public static Tpm localTpmSimulatorWithRetry(int retryAttempts) throws SecurityProviderException {
    if (retryAttempts <= 0) {
        throw new SecurityProviderException("Could not connect to tpm successfully");
    }
    new Tpm();
    TpmDevice device = new TpmDeviceTcp("localhost", 2321);
    device.powerCycle();
    Tpm tpm = new Tpm();
    tpm._setDevice(device);
    try {
        tpm.Startup(TPM_SU.CLEAR);
        tpm.DictionaryAttackLockReset(TPM_HANDLE.from(TPM_RH.LOCKOUT));
    } catch (BufferUnderflowException e) {
        // TODO need to investigate why tpm emulator occasionally gives unexpected response to the startup call, kanban task 4268737
        try {
            tpm.close();
            Thread.sleep(MILLISECONDS_BETWEEN_TPM_CONNECTION_ATTEMPTS);
            return localTpmSimulatorWithRetry(--retryAttempts);
        } catch (Exception e1) {
            throw new SecurityProviderException(e1);
        }
    }
    return tpm;
}
Also used : SecurityProviderTpm(com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderTpm) SecurityProviderException(com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException) BufferUnderflowException(java.nio.BufferUnderflowException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) BufferUnderflowException(java.nio.BufferUnderflowException) SecurityProviderException(com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException)

Example 13 with SecurityProviderException

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

the class SecurityProviderTPMEmulator method clearPersistent.

@SuppressWarnings("SameParameterValue")
private void clearPersistent(Tpm tpm, TPM_HANDLE hPersistent, String keyRole) throws SecurityProviderException {
    tpm._allowErrors().ReadPublic(hPersistent);
    TPM_RC rc = tpm._getLastResponseCode();
    if (rc == TPM_RC.SUCCESS) {
        tpm.EvictControl(TPM_HANDLE.from(TPM_RH.OWNER), hPersistent, hPersistent);
    } else if (rc != TPM_RC.HANDLE) {
        throw new SecurityProviderException("Unexpected failure for {" + rc.name() + "} of TPM2_ReadPublic for " + keyRole + " 0x" + hPersistent.handle);
    }
}
Also used : SecurityProviderException(com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException)

Example 14 with SecurityProviderException

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

the class IotHubSasTokenHardwareAuthenticationProviderTest method securityProviderConstructorThrowsIfRetrievingSSLContextFromSecurityProviderThrows.

// Tests_SRS_IOTHUBSASTOKENHARDWAREAUTHENTICATION_34_023: [If the security provider throws an exception while retrieving a sas token or ssl context from it, this function shall throw an IOException.]
@Test(expected = IOException.class)
public void securityProviderConstructorThrowsIfRetrievingSSLContextFromSecurityProviderThrows() throws IOException, InvalidKeyException, SecurityProviderException {
    // arrange
    final String someToken = "someToken";
    final byte[] tokenBytes = someToken.getBytes(StandardCharsets.UTF_8);
    new NonStrictExpectations() {

        {
            URLEncoder.encode(anyString, encodingName);
            result = someToken;
            mockSecurityProviderTpm.signWithIdentity((byte[]) any);
            result = tokenBytes;
            encodeBase64((byte[]) any);
            result = tokenBytes;
            URLEncoder.encode(anyString, encodingName);
            result = someToken;
            mockSecurityProviderTpm.getSSLContext();
            result = new SecurityProviderException("");
        }
    };
    // act
    new IotHubSasTokenHardwareAuthenticationProvider(expectedHostname, expectedGatewayHostname, expectedDeviceId, expectedModuleId, mockSecurityProviderTpm);
}
Also used : SecurityProviderException(com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException) Test(org.junit.Test)

Example 15 with SecurityProviderException

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

the class ProvisioningX509CertGen method main.

public static void main(String[] args) {
    try {
        String aliasCertCnName, rootCertCnName, signerCertCnName;
        SecurityProviderDiceEmulator securityClient;
        Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8.name());
        System.out.println("Do you want to input common name : Y/N(use default)");
        String isCnName = scanner.next();
        if (isCnName.equalsIgnoreCase("Y")) {
            System.out.println("Input Client Cert commonName :");
            aliasCertCnName = scanner.next();
            System.out.println("Input Root Cert commonName :");
            rootCertCnName = scanner.next();
            System.out.println("Input Signer Cert commonName :");
            signerCertCnName = scanner.next();
            securityClient = new SecurityProviderDiceEmulator(aliasCertCnName, signerCertCnName, rootCertCnName);
        } else {
            securityClient = new SecurityProviderDiceEmulator();
        }
        System.out.println("Your registration Id is : " + securityClient.getRegistrationId());
        System.out.println("Client Cert");
        System.out.println(securityClient.getAliasCertPem());
        System.out.println("Client Cert Private Key");
        System.out.println(securityClient.getAliasCertPrivateKeyPem());
        System.out.println("Signer (Intermediate) Cert");
        System.out.println(securityClient.getSignerCertPem());
        System.out.println("Root Cert");
        System.out.println(securityClient.getRootCertPem());
        System.out.println("Do you want to input Verification Code Y/N");
        String isVerify = scanner.next();
        try {
            if (isVerify.equalsIgnoreCase("Y")) {
                System.out.println("Input Verification Code");
                scanner = new Scanner(System.in, StandardCharsets.UTF_8.name());
                {
                    String verificationCode = scanner.next();
                    if (verificationCode != null) {
                        System.out.println("Verification Cert");
                        System.out.println(securityClient.generateLeafCert(verificationCode));
                    }
                }
            }
        } catch (SecurityProviderException e) {
            e.printStackTrace();
        } finally {
            scanner.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Shutting down...");
    }
}
Also used : Scanner(java.util.Scanner) SecurityProviderException(com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException) SecurityProviderDiceEmulator(com.microsoft.azure.sdk.iot.provisioning.security.hsm.SecurityProviderDiceEmulator) SecurityProviderException(com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException)

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