Search in sources :

Example 51 with ClientException

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

the class SecretKeyAccessor method sign.

@Override
public byte[] sign(@NonNull final byte[] text) throws ClientException {
    final String errCode;
    final Exception exception;
    try {
        final KeyStore.SecretKeyEntry entry = mKeyManager.getEntry();
        SecretKey key = entry.getSecretKey();
        Mac c = Mac.getInstance(suite.macName());
        c.init(key);
        return c.doFinal(text);
    } 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 InvalidKeyException e) {
        errCode = INVALID_KEY;
        exception = e;
    }
    throw new ClientException(errCode, exception.getMessage(), exception);
}
Also used : SecretKey(javax.crypto.SecretKey) UnrecoverableEntryException(java.security.UnrecoverableEntryException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) ClientException(com.microsoft.identity.common.exception.ClientException) 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) Mac(javax.crypto.Mac)

Example 52 with ClientException

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

the class DeviceKeyManager method getSecureHardwareState.

/**
 * Gets the {@link SecureHardwareState} of this key.
 *
 * @return The SecureHardwareState.
 * @throws ClientException If the underlying key material cannot be inspected.
 */
@Override
public SecureHardwareState getSecureHardwareState() throws ClientException {
    final String errCode;
    final Exception exception;
    try {
        KeyStore.Entry entry = getEntry();
        if (entry instanceof KeyStore.PrivateKeyEntry) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                try {
                    final PrivateKey privateKey = ((KeyStore.PrivateKeyEntry) entry).getPrivateKey();
                    final KeyFactory factory = KeyFactory.getInstance(privateKey.getAlgorithm(), mKeyStore.getProvider());
                    final KeyInfo info = factory.getKeySpec(privateKey, KeyInfo.class);
                    final boolean isInsideSecureHardware = info.isInsideSecureHardware();
                    Logger.info(TAG, "PrivateKey is secure hardware backed? " + isInsideSecureHardware);
                    return isInsideSecureHardware ? SecureHardwareState.TRUE_UNATTESTED : SecureHardwareState.FALSE;
                } catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
                    Logger.error(TAG, "Failed to query secure hardware state.", e);
                    return SecureHardwareState.UNKNOWN_QUERY_ERROR;
                }
            } else {
                Logger.info(TAG, "Cannot query secure hardware state (API unavailable <23)");
            }
            return SecureHardwareState.UNKNOWN_DOWNLEVEL;
        } else if (entry instanceof KeyStore.SecretKeyEntry) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                try {
                    final SecretKey privateKey = ((KeyStore.SecretKeyEntry) entry).getSecretKey();
                    final SecretKeyFactory factory = SecretKeyFactory.getInstance(privateKey.getAlgorithm(), mKeyStore.getProvider());
                    final KeyInfo info = (KeyInfo) factory.getKeySpec(privateKey, KeyInfo.class);
                    final boolean isInsideSecureHardware = info.isInsideSecureHardware();
                    Logger.info(TAG, "SecretKey is secure hardware backed? " + isInsideSecureHardware);
                    return isInsideSecureHardware ? SecureHardwareState.TRUE_UNATTESTED : SecureHardwareState.FALSE;
                } catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
                    Logger.error(TAG, "Failed to query secure hardware state.", e);
                    return SecureHardwareState.UNKNOWN_QUERY_ERROR;
                }
            } else {
                Logger.info(TAG, "Cannot query secure hardware state (API unavailable <23)");
            }
            return SecureHardwareState.UNKNOWN_DOWNLEVEL;
        } else {
            throw new ClientException(UNKNOWN_ERROR, "Cannot handle entries of type " + entry.getClass().getCanonicalName());
        }
    } catch (final KeyStoreException e) {
        errCode = KEYSTORE_NOT_INITIALIZED;
        exception = e;
    } catch (final NoSuchAlgorithmException e) {
        errCode = NO_SUCH_ALGORITHM;
        exception = e;
    } catch (final UnrecoverableEntryException e) {
        errCode = INVALID_PROTECTION_PARAMS;
        exception = e;
    }
    final ClientException clientException = new ClientException(errCode, exception.getMessage(), exception);
    Logger.error(TAG + ":getSecureHardwareState", errCode, exception);
    throw clientException;
}
Also used : PrivateKey(java.security.PrivateKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) KeyStore(java.security.KeyStore) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyStoreException(java.security.KeyStoreException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) ClientException(com.microsoft.identity.common.exception.ClientException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SecretKey(javax.crypto.SecretKey) KeyInfo(android.security.keystore.KeyInfo) UnrecoverableEntryException(java.security.UnrecoverableEntryException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) ClientException(com.microsoft.identity.common.exception.ClientException) SecretKeyFactory(javax.crypto.SecretKeyFactory) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyFactory(java.security.KeyFactory)

Example 53 with ClientException

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

the class RawKeyAccessor method encrypt.

@Override
public byte[] encrypt(@NonNull final byte[] plaintext) throws ClientException {
    final String errCode;
    final Exception exception;
    try {
        final SecretKeySpec keySpec = new SecretKeySpec(key, suite.cipher().name());
        final Cipher c = Cipher.getInstance(keySpec.getAlgorithm());
        final byte[] iv = new byte[12];
        mRandom.nextBytes(iv);
        final IvParameterSpec ivSpec = new IvParameterSpec(iv);
        c.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        c.update(plaintext);
        byte[] tmp = c.doFinal();
        final byte[] output = new byte[iv.length + tmp.length];
        System.arraycopy(iv, 0, output, 0, iv.length);
        System.arraycopy(tmp, 0, output, iv.length, tmp.length);
        return output;
    } catch (final NoSuchAlgorithmException e) {
        errCode = NO_SUCH_ALGORITHM;
        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;
    } catch (final InvalidAlgorithmParameterException e) {
        errCode = INVALID_ALG_PARAMETER;
        exception = e;
    }
    throw new ClientException(errCode, exception.getMessage());
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) ClientException(com.microsoft.identity.common.exception.ClientException) IOException(java.io.IOException) BadPaddingException(javax.crypto.BadPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) ClientException(com.microsoft.identity.common.exception.ClientException)

Example 54 with ClientException

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

the class BaseController method getCachedAccountRecord.

/**
 * Helper method to get a cached account
 *
 * @param parameters
 * @return
 */
protected AccountRecord getCachedAccountRecord(@NonNull final SilentTokenCommandParameters parameters) throws ClientException {
    if (parameters.getAccount() == null) {
        throw new ClientException(ErrorStrings.NO_ACCOUNT_FOUND, "No cached accounts found for the supplied homeAccountId and clientId");
    }
    final boolean isB2CAuthority = B2C.equalsIgnoreCase(parameters.getAuthority().getAuthorityTypeString());
    final String clientId = parameters.getClientId();
    final String homeAccountId = parameters.getAccount().getHomeAccountId();
    final String localAccountId = parameters.getAccount().getLocalAccountId();
    AccountRecord targetAccount;
    if (isB2CAuthority) {
        // Due to differences in the B2C service API relative to AAD, all IAccounts returned by
        // the B2C-STS have the same local_account_id irrespective of the policy used to load it.
        // 
        // Because the home_account_id is unique to policy and there is no concept of
        // multi-realm accounts relative to B2C, we'll conditionally use the home_account_id
        // in these cases
        targetAccount = parameters.getOAuth2TokenCache().getAccountByHomeAccountId(null, clientId, homeAccountId);
    } else {
        targetAccount = parameters.getOAuth2TokenCache().getAccountByLocalAccountId(null, clientId, localAccountId);
    }
    if (null == targetAccount && parameters.getOAuth2TokenCache() instanceof MsalOAuth2TokenCache) {
        targetAccount = getAccountWithFRTIfAvailable(parameters, (MsalOAuth2TokenCache) parameters.getOAuth2TokenCache());
    }
    if (null == targetAccount) {
        Logger.info(TAG, "No accounts found for clientId [" + clientId + ", " + "]", null);
        Logger.errorPII(TAG, "No accounts found for clientId, homeAccountId: [" + clientId + ", " + homeAccountId + "]", null);
        throw new ClientException(ErrorStrings.NO_ACCOUNT_FOUND, "No cached accounts found for the supplied homeAccountId");
    }
    return targetAccount;
}
Also used : AccountRecord(com.microsoft.identity.common.internal.dto.AccountRecord) ClientException(com.microsoft.identity.common.exception.ClientException) MsalOAuth2TokenCache(com.microsoft.identity.common.internal.cache.MsalOAuth2TokenCache)

Example 55 with ClientException

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

the class BaseController method getAccountWithFRTIfAvailable.

@Nullable
private AccountRecord getAccountWithFRTIfAvailable(@NonNull final SilentTokenCommandParameters parameters, @SuppressWarnings(WarningType.rawtype_warning) @NonNull final MsalOAuth2TokenCache msalOAuth2TokenCache) {
    final String homeAccountId = parameters.getAccount().getHomeAccountId();
    final String clientId = parameters.getClientId();
    // check for FOCI tokens for the homeAccountId
    final RefreshTokenRecord refreshTokenRecord = msalOAuth2TokenCache.getFamilyRefreshTokenForHomeAccountId(homeAccountId);
    if (refreshTokenRecord != null) {
        try {
            // foci token is available, make a request to service to see if the client id is FOCI and save the tokens
            TokenCacheItemMigrationAdapter.tryFociTokenWithGivenClientId(parameters.getOAuth2TokenCache(), clientId, parameters.getRedirectUri(), refreshTokenRecord, parameters.getAccount());
            // Try to look for account again in the cache
            return parameters.getOAuth2TokenCache().getAccountByLocalAccountId(null, clientId, parameters.getAccount().getLocalAccountId());
        } catch (IOException | ClientException e) {
            Logger.warn(TAG, "Error while attempting to validate client: " + clientId + " is part of family " + e.getMessage());
        }
    } else {
        Logger.info(TAG, "No Foci tokens found for homeAccountId " + homeAccountId);
    }
    return null;
}
Also used : RefreshTokenRecord(com.microsoft.identity.common.internal.dto.RefreshTokenRecord) IOException(java.io.IOException) ClientException(com.microsoft.identity.common.exception.ClientException) Nullable(androidx.annotation.Nullable)

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