Search in sources :

Example 46 with ClientException

use of com.microsoft.identity.common.exception.ClientException in project microsoft-authentication-library-common-for-android by AzureAD.

the class DevicePopManager method getX509SubjectPublicKeyInfo.

private String getX509SubjectPublicKeyInfo() throws ClientException {
    final Exception exception;
    final String errCode;
    try {
        final KeyStore.PrivateKeyEntry keyEntry = mKeyManager.getEntry();
        final KeyPair rsaKeyPair = getKeyPairForEntry(keyEntry);
        final PublicKey publicKey = rsaKeyPair.getPublic();
        final byte[] publicKeybytes = publicKey.getEncoded();
        final byte[] bytesBase64Encoded = Base64.encode(publicKeybytes, Base64.DEFAULT);
        return new String(bytesBase64Encoded);
    } catch (final KeyStoreException e) {
        exception = e;
        errCode = KEYSTORE_NOT_INITIALIZED;
    } catch (final NoSuchAlgorithmException e) {
        exception = e;
        errCode = NO_SUCH_ALGORITHM;
    } catch (final UnrecoverableEntryException e) {
        exception = e;
        errCode = INVALID_PROTECTION_PARAMS;
    }
    final ClientException clientException = new ClientException(errCode, exception.getMessage(), exception);
    Logger.error(TAG, clientException.getMessage(), clientException);
    throw clientException;
}
Also used : KeyPair(java.security.KeyPair) RSAPublicKey(java.security.interfaces.RSAPublicKey) PublicKey(java.security.PublicKey) UnrecoverableEntryException(java.security.UnrecoverableEntryException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ClientException(com.microsoft.identity.common.exception.ClientException) KeyStore(java.security.KeyStore) JOSEException(com.nimbusds.jose.JOSEException) KeyStoreException(java.security.KeyStoreException) JSONException(org.json.JSONException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) StrongBoxUnavailableException(android.security.keystore.StrongBoxUnavailableException) SignatureException(java.security.SignatureException) ProviderException(java.security.ProviderException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) KeyPermanentlyInvalidatedException(android.security.keystore.KeyPermanentlyInvalidatedException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) ClientException(com.microsoft.identity.common.exception.ClientException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) BadPaddingException(javax.crypto.BadPaddingException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 47 with ClientException

use of com.microsoft.identity.common.exception.ClientException in project microsoft-authentication-library-common-for-android by AzureAD.

the class AndroidKeystoreAsymmetricRsaKeyFactory method clearAsymmetricKey.

@Override
public synchronized boolean clearAsymmetricKey(@NonNull final String alias) throws ClientException {
    final Exception exception;
    final String errCode;
    try {
        return new DevicePopManager(alias).clearAsymmetricKey();
    } catch (final KeyStoreException e) {
        exception = e;
        errCode = KEYSTORE_NOT_INITIALIZED;
    } catch (final CertificateException e) {
        exception = e;
        errCode = CERTIFICATE_LOAD_FAILURE;
    } catch (final NoSuchAlgorithmException e) {
        exception = e;
        errCode = NO_SUCH_ALGORITHM;
    } catch (final IOException e) {
        exception = e;
        errCode = IO_ERROR;
    }
    throw new ClientException(errCode, exception.getMessage(), exception);
}
Also used : CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) ClientException(com.microsoft.identity.common.exception.ClientException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ClientException(com.microsoft.identity.common.exception.ClientException) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) CertificateException(java.security.cert.CertificateException)

Example 48 with ClientException

use of com.microsoft.identity.common.exception.ClientException in project microsoft-authentication-library-common-for-android by AzureAD.

the class AzureActiveDirectoryAuthorizationResultFactory method createAuthorizationResult.

@Override
public AzureActiveDirectoryAuthorizationResult createAuthorizationResult(final int resultCode, final Intent data, final AzureActiveDirectoryAuthorizationRequest request) {
    if (data == null || data.getExtras() == null) {
        return createAuthorizationResultWithErrorResponse(AuthorizationStatus.FAIL, MicrosoftAuthorizationErrorResponse.AUTHORIZATION_FAILED, MicrosoftAuthorizationErrorResponse.NULL_INTENT);
    }
    final Bundle extras = data.getExtras();
    final int requestId = extras.getInt(AuthenticationConstants.Browser.REQUEST_ID);
    AzureActiveDirectoryAuthorizationResult result = null;
    switch(resultCode) {
        case AuthenticationConstants.UIResponse.BROWSER_CODE_CANCEL:
            Logger.verbose(TAG, "User cancel the request in webview: " + requestId);
            result = createAuthorizationResultWithErrorResponse(AuthorizationStatus.USER_CANCEL, MicrosoftAuthorizationErrorResponse.USER_CANCEL, MicrosoftAuthorizationErrorResponse.USER_CANCELLED_FLOW);
            break;
        case AuthenticationConstants.UIResponse.BROWSER_CODE_COMPLETE:
            final String url = extras.getString(AuthenticationConstants.Browser.RESPONSE_FINAL_URL, "");
            result = parseUrlAndCreateAuthorizationResult(url, data.getStringExtra(MicrosoftAuthorizationResult.REQUEST_STATE_PARAMETER));
            break;
        case AuthenticationConstants.UIResponse.BROWSER_CODE_ERROR:
            // This is purely client side error, possible return could be chrome_not_installed or the request intent is
            // not resolvable
            final String error = extras.getString(AuthenticationConstants.Browser.RESPONSE_ERROR_CODE);
            final String errorDescription = extras.getString(AuthenticationConstants.Browser.RESPONSE_ERROR_MESSAGE);
            result = createAuthorizationResultWithErrorResponse(AuthorizationStatus.FAIL, error, errorDescription);
            break;
        case AuthenticationConstants.UIResponse.BROWSER_CODE_AUTHENTICATION_EXCEPTION:
            // TODO : Verify that a ClientException is serialized here after Broker Implementation
            Serializable responseAuthenticationException = extras.getSerializable(AuthenticationConstants.Browser.RESPONSE_AUTHENTICATION_EXCEPTION);
            if (responseAuthenticationException != null && responseAuthenticationException instanceof ClientException) {
                ClientException exception = (ClientException) responseAuthenticationException;
                result = createAuthorizationResultWithErrorResponse(AuthorizationStatus.FAIL, exception.getErrorCode(), exception.getMessage());
            }
            break;
        case AuthenticationConstants.UIResponse.BROKER_REQUEST_RESUME:
            Logger.verbose(TAG, "Device needs to have broker installed, we expect the apps to call us" + "back when the broker is installed");
            result = createAuthorizationResultWithErrorResponse(AuthorizationStatus.FAIL, MicrosoftAuthorizationErrorResponse.BROKER_NEEDS_TO_BE_INSTALLED, MicrosoftAuthorizationErrorResponse.BROKER_NEEDS_TO_BE_INSTALLED_ERROR_DESCRIPTION);
            break;
        case AuthenticationConstants.UIResponse.BROWSER_CODE_DEVICE_REGISTER:
            Logger.info(TAG, "Device Registration needed, need to start WPJ");
            result = createAuthorizationResultWithErrorResponse(AuthorizationStatus.FAIL, MicrosoftAuthorizationErrorResponse.DEVICE_REGISTRATION_NEEDED, MicrosoftAuthorizationErrorResponse.DEVICE_REGISTRATION_NEEDED_ERROR_DESCRIPTION);
            // Set username returned from the service
            result.getAuthorizationErrorResponse().setUserName(data.getStringExtra(AuthenticationConstants.Broker.INSTALL_UPN_KEY));
            break;
        case AuthenticationConstants.UIResponse.BROWSER_CODE_MDM:
            Logger.info(TAG, "MDM required. Launching Intune MDM link on browser.");
            result = createAuthorizationResultWithErrorResponse(AuthorizationStatus.FAIL, MicrosoftAuthorizationErrorResponse.DEVICE_NEEDS_TO_BE_MANAGED, MicrosoftAuthorizationErrorResponse.DEVICE_NEEDS_TO_BE_MANAGED_ERROR_DESCRIPTION);
            break;
        default:
            result = createAuthorizationResultWithErrorResponse(AuthorizationStatus.FAIL, MicrosoftAuthorizationErrorResponse.UNKNOWN_ERROR, MicrosoftAuthorizationErrorResponse.UNKNOWN_RESULT_CODE + "[" + resultCode + "]");
            break;
    }
    if (result == null) {
        result = createAuthorizationResultWithErrorResponse(AuthorizationStatus.FAIL, MicrosoftAuthorizationErrorResponse.UNKNOWN_ERROR, MicrosoftAuthorizationErrorResponse.UNKNOWN_RESULT_CODE + "[" + resultCode + "]");
    }
    return result;
}
Also used : Serializable(java.io.Serializable) Bundle(android.os.Bundle) ClientException(com.microsoft.identity.common.exception.ClientException)

Example 49 with ClientException

use of com.microsoft.identity.common.exception.ClientException in project microsoft-authentication-library-common-for-android by AzureAD.

the class MicrosoftStsOAuth2Strategy method createTokenRequest.

@Override
public MicrosoftStsTokenRequest createTokenRequest(@NonNull final MicrosoftStsAuthorizationRequest request, @NonNull final MicrosoftStsAuthorizationResponse response, @NonNull final AbstractAuthenticationScheme authScheme) throws ClientException {
    final String methodName = ":createTokenRequest";
    Logger.verbose(TAG + methodName, "Creating TokenRequest...");
    if (mConfig.getMultipleCloudsSupported() || request.getMultipleCloudAware()) {
        Logger.verbose(TAG, "get cloud specific authority based on authorization response.");
        setTokenEndpoint(getCloudSpecificTokenEndpoint(response));
    }
    final MicrosoftStsTokenRequest tokenRequest = new MicrosoftStsTokenRequest();
    tokenRequest.setCodeVerifier(request.getPkceChallenge().getCodeVerifier());
    tokenRequest.setCode(response.getCode());
    tokenRequest.setRedirectUri(request.getRedirectUri());
    tokenRequest.setClientId(request.getClientId());
    tokenRequest.setScope(request.getTokenScope());
    tokenRequest.setClaims(request.getClaims());
    setTokenRequestCorrelationId(tokenRequest);
    // Existence of a device code inside of the response object implies Device Code Flow is being used
    if (response.getDeviceCode() != null) {
        tokenRequest.setGrantType(TokenRequest.GrantTypes.DEVICE_CODE);
        tokenRequest.setDeviceCode(response.getDeviceCode());
    } else {
        // If device code doesn't exist, continue with auth_code configuration
        tokenRequest.setGrantType(TokenRequest.GrantTypes.AUTHORIZATION_CODE);
    }
    if (SCHEME_POP.equals(authScheme.getName())) {
        if (null == mStrategyParameters.getContext()) {
            throw new ClientException(MicrosoftStsOAuth2Strategy.class.getSimpleName() + "Cannot execute PoP request sans Context");
        }
        // Add a token_type
        tokenRequest.setTokenType(TokenRequest.TokenType.POP);
        final IDevicePopManager devicePopManager = Device.getDevicePoPManagerInstance();
        // Generate keys if they don't already exist...
        if (!devicePopManager.asymmetricKeyExists()) {
            final String thumbprint = devicePopManager.generateAsymmetricKey(mStrategyParameters.getContext());
            Logger.verbosePII(TAG, "Generated new PoP asymmetric key with thumbprint: " + thumbprint);
        }
        final String reqCnf = devicePopManager.getRequestConfirmation();
        // Set the req_cnf
        tokenRequest.setRequestConfirmation(reqCnf);
    }
    return tokenRequest;
}
Also used : IDevicePopManager(com.microsoft.identity.common.internal.platform.IDevicePopManager) ClientException(com.microsoft.identity.common.exception.ClientException)

Example 50 with ClientException

use of com.microsoft.identity.common.exception.ClientException in project microsoft-authentication-library-common-for-android by AzureAD.

the class SecretKeyAccessor method encrypt.

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public byte[] encrypt(@NonNull final byte[] plaintext) throws ClientException {
    final String errCode;
    final Exception exception;
    try {
        final KeyStore.SecretKeyEntry entry = mKeyManager.getEntry();
        final SecretKey key = entry.getSecretKey();
        final Cipher c = Cipher.getInstance(suite.cipher().name());
        c.init(Cipher.ENCRYPT_MODE, key);
        final byte[] iv = c.getIV();
        final byte[] enc = c.doFinal(plaintext);
        final byte[] out = new byte[iv.length + enc.length];
        System.arraycopy(iv, 0, out, 0, iv.length);
        System.arraycopy(enc, 0, out, iv.length, enc.length);
        return out;
    } catch (final UnrecoverableEntryException e) {
        errCode = INVALID_PROTECTION_PARAMS;
        exception = e;
    } catch (final NoSuchAlgorithmException e) {
        errCode = NO_SUCH_ALGORITHM;
        exception = e;
    } catch (final KeyStoreException e) {
        errCode = KEYSTORE_NOT_INITIALIZED;
        exception = e;
    } catch (final NoSuchPaddingException e) {
        errCode = NO_SUCH_PADDING;
        exception = e;
    } catch (final IllegalBlockSizeException e) {
        errCode = INVALID_BLOCK_SIZE;
        exception = e;
    } catch (final BadPaddingException e) {
        errCode = BAD_PADDING;
        exception = e;
    } catch (final InvalidKeyException e) {
        errCode = INVALID_KEY;
        exception = e;
    }
    throw new ClientException(errCode, exception.getMessage(), exception);
}
Also used : NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) KeyStore(java.security.KeyStore) KeyStoreException(java.security.KeyStoreException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) ClientException(com.microsoft.identity.common.exception.ClientException) BadPaddingException(javax.crypto.BadPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) SecretKey(javax.crypto.SecretKey) UnrecoverableEntryException(java.security.UnrecoverableEntryException) Cipher(javax.crypto.Cipher) ClientException(com.microsoft.identity.common.exception.ClientException) RequiresApi(androidx.annotation.RequiresApi)

Aggregations

ClientException (com.microsoft.identity.common.exception.ClientException)74 IOException (java.io.IOException)23 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)23 InvalidKeyException (java.security.InvalidKeyException)18 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)17 KeyStoreException (java.security.KeyStoreException)17 BadPaddingException (javax.crypto.BadPaddingException)17 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)17 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)17 UnrecoverableEntryException (java.security.UnrecoverableEntryException)15 CertificateException (java.security.cert.CertificateException)13 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)12 SignatureException (java.security.SignatureException)11 KeyPermanentlyInvalidatedException (android.security.keystore.KeyPermanentlyInvalidatedException)10 StrongBoxUnavailableException (android.security.keystore.StrongBoxUnavailableException)10 NonNull (androidx.annotation.NonNull)10 JOSEException (com.nimbusds.jose.JOSEException)10 NoSuchProviderException (java.security.NoSuchProviderException)10 ProviderException (java.security.ProviderException)10 JSONException (org.json.JSONException)10