Search in sources :

Example 1 with ProvisioningDeviceSecurityException

use of com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceSecurityException 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)

Example 2 with ProvisioningDeviceSecurityException

use of com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceSecurityException in project azure-iot-sdk-java by Azure.

the class StatusTask method getRegistrationStatus.

private RegistrationOperationStatusParser getRegistrationStatus(String operationId, Authorization authorization) throws ProvisioningDeviceClientException {
    try {
        // SRS_StatusTask_25_003: [ This method shall throw ProvisioningDeviceClientException if registration id is null or empty. ]
        String registrationId = this.securityProvider.getRegistrationId();
        if (registrationId == null || registrationId.isEmpty()) {
            throw new ProvisioningDeviceSecurityException("registrationId cannot be null or empty");
        }
        // SRS_StatusTask_25_004: [ This method shall retrieve the SSL context from Authorization and throw ProvisioningDeviceClientException if it is null. ]
        SSLContext sslContext = authorization.getSslContext();
        if (sslContext == null) {
            throw new ProvisioningDeviceSecurityException("SSL context cannot be null");
        }
        RequestData requestData = new RequestData(registrationId, operationId, authorization.getSslContext(), authorization.getSasToken(), null);
        // SRS_StatusTask_25_005: [ This method shall trigger getRegistrationState on the contract API and wait for response and return it. ]
        ResponseData responseData = new ResponseData();
        provisioningDeviceClientContract.getRegistrationStatus(requestData, new ResponseCallbackImpl(), responseData);
        if (responseData.getResponseData() == null || responseData.getContractState() != ContractState.DPS_REGISTRATION_RECEIVED) {
            Thread.sleep(MAX_WAIT_FOR_STATUS_RESPONSE);
        }
        if (responseData.getResponseData() != null && responseData.getContractState() == ContractState.DPS_REGISTRATION_RECEIVED) {
            String jsonBody = new String(responseData.getResponseData(), StandardCharsets.UTF_8);
            try {
                return RegistrationOperationStatusParser.createFromJson(jsonBody);
            } catch (IllegalArgumentException e) {
                // SRS_StatusTask_34_007: [ If the response data cannot be parsed into a RegistrationOperationStatusParser,
                // this function shall parse it into a ProvisioningErrorParser and throw a ProvisioningDeviceClientException with the parsed message. ]
                ProvisioningErrorParser provisioningErrorParser = ProvisioningErrorParser.createFromJson(jsonBody);
                throw new ProvisioningDeviceClientException(provisioningErrorParser.getExceptionMessage());
            }
        } else {
            // SRS_StatusTask_25_006: [ This method shall throw ProvisioningDeviceClientException if null response or no response is received in maximum time of 90 seconds. ]
            throw new ProvisioningDeviceClientException("Did not receive DPS Status information");
        }
    } catch (InterruptedException | SecurityProviderException e) {
        throw new ProvisioningDeviceClientException(e);
    }
}
Also used : ProvisioningDeviceSecurityException(com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceSecurityException) ProvisioningErrorParser(com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.ProvisioningErrorParser) SecurityProviderException(com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException) SSLContext(javax.net.ssl.SSLContext) ProvisioningDeviceClientException(com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceClientException)

Example 3 with ProvisioningDeviceSecurityException

use of com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceSecurityException 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)

Example 4 with ProvisioningDeviceSecurityException

use of com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceSecurityException in project azure-iot-sdk-java by Azure.

the class AmqpsProvisioningSaslHandler method handleThirdChallenge.

private byte[] handleThirdChallenge(byte[] challengeData) throws ProvisioningDeviceClientException {
    // validate challenge
    if (challengeData.length < 1 || challengeData[0] != FINAL_SEGMENT_CONTROL_BYTE) {
        // Codes_SRS_AMQPSPROVISIONINGSASLHANDLER_34_015: [If this object is waiting for the third challenge, this function shall validate that this challenge payload contains a control byte with the mask 0xC1 and shall throw an IllegalStateException if it is not.]
        throw new IllegalStateException("Unexpected challenge data");
    }
    // Codes_SRS_AMQPSPROVISIONINGSASLHANDLER_34_016: [If this object is waiting for the third challenge, this function shall read the challenge in the format "control byte + nonce (second half)" and save the nonce portion.]
    this.challengeKey = buildNonceFromThirdChallenge(challengeData);
    // Codes_SRS_AMQPSPROVISIONINGSASLHANDLER_34_017: [If this object is waiting for the third challenge, this function shall put together the full nonce byte array and run the saved responseCallback with the nonce and DPS_REGISTRATION_RECEIVED.]
    this.responseCallback.run(new ResponseData(this.challengeKey, ContractState.DPS_REGISTRATION_RECEIVED, 0), this.authorizationCallbackContext);
    this.challengeState = ChallengeState.WAITING_TO_SEND_SAS_TOKEN;
    // Codes_SRS_AMQPSPROVISIONINGSASLHANDLER_34_018: [If this object is waiting for the third challenge, after running the saved responseCallback, this function shall wait for the sas token to be set before returning a payload in the format "control byte + sas token".]
    long millisecondsElapsed = 0;
    long waitTimeStart = System.currentTimeMillis();
    while (this.sasToken == null && millisecondsElapsed < MAX_MILLISECONDS_TIMEOUT_FOR_SAS_TOKEN_WAIT) {
        try {
            // noinspection BusyWait
            Thread.sleep(WAIT_INTERVALS);
        } catch (InterruptedException e) {
            throw new ProvisioningDeviceClientException(e);
        }
        millisecondsElapsed = System.currentTimeMillis() - waitTimeStart;
    }
    if (millisecondsElapsed >= MAX_MILLISECONDS_TIMEOUT_FOR_SAS_TOKEN_WAIT) {
        // Codes_SRS_AMQPSPROVISIONINGSASLHANDLER_34_019: [If this object is waiting for the third challenge, and if the sas token is not provided within 3 minutes of waiting, this function shall throw a SecurityException.]
        throw new ProvisioningDeviceSecurityException("Sasl negotiation failed: Sas token was never supplied to finish negotiation");
    }
    this.challengeState = ChallengeState.WAITING_FOR_FINAL_OUTCOME;
    return prependByteArrayWithControlByte(INIT_SEGMENT_CONTROL_BYTE, sasToken.getBytes(StandardCharsets.UTF_8));
}
Also used : ProvisioningDeviceSecurityException(com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceSecurityException) ResponseData(com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ResponseData) ProvisioningDeviceClientException(com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceClientException)

Aggregations

ProvisioningDeviceClientException (com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceClientException)4 ProvisioningDeviceSecurityException (com.microsoft.azure.sdk.iot.provisioning.device.internal.exceptions.ProvisioningDeviceSecurityException)4 SecurityProviderSymmetricKey (com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderSymmetricKey)2 SecurityProviderTpm (com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderTpm)2 SecurityProviderException (com.microsoft.azure.sdk.iot.provisioning.security.exceptions.SecurityProviderException)2 SSLContext (javax.net.ssl.SSLContext)2 UrlPathBuilder (com.microsoft.azure.sdk.iot.provisioning.device.internal.contract.UrlPathBuilder)1 ProvisioningErrorParser (com.microsoft.azure.sdk.iot.provisioning.device.internal.parser.ProvisioningErrorParser)1 ResponseData (com.microsoft.azure.sdk.iot.provisioning.device.internal.task.ResponseData)1 SecurityProviderX509 (com.microsoft.azure.sdk.iot.provisioning.security.SecurityProviderX509)1 IOException (java.io.IOException)1