Search in sources :

Example 21 with KeymasterArguments

use of android.security.keymaster.KeymasterArguments in project android_frameworks_base by AOSPA.

the class KeyStoreTest method importAesKey.

private int importAesKey(String name, byte[] key, int size, int mode) {
    KeymasterArguments args = new KeymasterArguments();
    args.addEnum(KeymasterDefs.KM_TAG_PURPOSE, KeymasterDefs.KM_PURPOSE_ENCRYPT);
    args.addEnum(KeymasterDefs.KM_TAG_PURPOSE, KeymasterDefs.KM_PURPOSE_DECRYPT);
    args.addEnum(KeymasterDefs.KM_TAG_ALGORITHM, KeymasterDefs.KM_ALGORITHM_AES);
    args.addEnum(KeymasterDefs.KM_TAG_PADDING, KeymasterDefs.KM_PAD_NONE);
    args.addEnum(KeymasterDefs.KM_TAG_BLOCK_MODE, mode);
    args.addUnsignedInt(KeymasterDefs.KM_TAG_KEY_SIZE, size);
    args.addBoolean(KeymasterDefs.KM_TAG_NO_AUTH_REQUIRED);
    return mKeyStore.importKey(name, args, KeymasterDefs.KM_KEY_FORMAT_RAW, key, 0, new KeyCharacteristics());
}
Also used : KeymasterArguments(android.security.keymaster.KeymasterArguments) KeyCharacteristics(android.security.keymaster.KeyCharacteristics)

Example 22 with KeymasterArguments

use of android.security.keymaster.KeymasterArguments in project android_frameworks_base by AOSPA.

the class KeyStoreTest method testOperationPruning.

// This is a very implementation specific test and should be thrown out eventually, however it
// is nice for now to test that keystore is properly pruning operations.
public void testOperationPruning() throws Exception {
    String name = "test";
    KeymasterArguments args = new KeymasterArguments();
    args.addEnum(KeymasterDefs.KM_TAG_PURPOSE, KeymasterDefs.KM_PURPOSE_ENCRYPT);
    args.addEnum(KeymasterDefs.KM_TAG_PURPOSE, KeymasterDefs.KM_PURPOSE_DECRYPT);
    args.addEnum(KeymasterDefs.KM_TAG_ALGORITHM, KeymasterDefs.KM_ALGORITHM_AES);
    args.addEnum(KeymasterDefs.KM_TAG_PADDING, KeymasterDefs.KM_PAD_NONE);
    args.addUnsignedInt(KeymasterDefs.KM_TAG_KEY_SIZE, 256);
    args.addEnum(KeymasterDefs.KM_TAG_BLOCK_MODE, KeymasterDefs.KM_MODE_CTR);
    args.addBoolean(KeymasterDefs.KM_TAG_NO_AUTH_REQUIRED);
    KeyCharacteristics outCharacteristics = new KeyCharacteristics();
    int rc = mKeyStore.generateKey(name, args, null, 0, outCharacteristics);
    assertEquals("Generate should succeed", KeyStore.NO_ERROR, rc);
    args = new KeymasterArguments();
    args.addEnum(KeymasterDefs.KM_TAG_ALGORITHM, KeymasterDefs.KM_ALGORITHM_AES);
    args.addEnum(KeymasterDefs.KM_TAG_BLOCK_MODE, KeymasterDefs.KM_MODE_CTR);
    args.addEnum(KeymasterDefs.KM_TAG_PADDING, KeymasterDefs.KM_PAD_NONE);
    OperationResult result = mKeyStore.begin(name, KeymasterDefs.KM_PURPOSE_ENCRYPT, true, args, null);
    assertEquals("Begin should succeed", KeyStore.NO_ERROR, result.resultCode);
    IBinder first = result.token;
    // Implementation detail: softkeymaster supports 16 concurrent operations
    for (int i = 0; i < 16; i++) {
        result = mKeyStore.begin(name, KeymasterDefs.KM_PURPOSE_ENCRYPT, true, args, null);
        assertEquals("Begin should succeed", KeyStore.NO_ERROR, result.resultCode);
    }
    // At this point the first operation should be pruned.
    assertEquals("Operation should be pruned", KeymasterDefs.KM_ERROR_INVALID_OPERATION_HANDLE, mKeyStore.update(first, null, new byte[] { 0x01 }).resultCode);
}
Also used : IBinder(android.os.IBinder) KeymasterArguments(android.security.keymaster.KeymasterArguments) KeyCharacteristics(android.security.keymaster.KeyCharacteristics) OperationResult(android.security.keymaster.OperationResult)

Example 23 with KeymasterArguments

use of android.security.keymaster.KeymasterArguments in project android_frameworks_base by AOSPA.

the class KeyStoreTest method generateRsaKey.

private KeyCharacteristics generateRsaKey(String name) throws Exception {
    KeymasterArguments args = new KeymasterArguments();
    args.addEnum(KeymasterDefs.KM_TAG_PURPOSE, KeymasterDefs.KM_PURPOSE_ENCRYPT);
    args.addEnum(KeymasterDefs.KM_TAG_PURPOSE, KeymasterDefs.KM_PURPOSE_DECRYPT);
    args.addEnum(KeymasterDefs.KM_TAG_ALGORITHM, KeymasterDefs.KM_ALGORITHM_RSA);
    args.addEnum(KeymasterDefs.KM_TAG_PADDING, KeymasterDefs.KM_PAD_NONE);
    args.addBoolean(KeymasterDefs.KM_TAG_NO_AUTH_REQUIRED);
    args.addUnsignedInt(KeymasterDefs.KM_TAG_KEY_SIZE, 2048);
    args.addUnsignedLong(KeymasterDefs.KM_TAG_RSA_PUBLIC_EXPONENT, RSAKeyGenParameterSpec.F4);
    KeyCharacteristics outCharacteristics = new KeyCharacteristics();
    int result = mKeyStore.generateKey(name, args, null, 0, outCharacteristics);
    assertEquals("generateRsaKey should succeed", KeyStore.NO_ERROR, result);
    return outCharacteristics;
}
Also used : KeymasterArguments(android.security.keymaster.KeymasterArguments) KeyCharacteristics(android.security.keymaster.KeyCharacteristics)

Example 24 with KeymasterArguments

use of android.security.keymaster.KeymasterArguments in project android_frameworks_base by AOSPA.

the class AndroidKeyStoreKeyGeneratorSpi method engineGenerateKey.

@Override
protected SecretKey engineGenerateKey() {
    KeyGenParameterSpec spec = mSpec;
    if (spec == null) {
        throw new IllegalStateException("Not initialized");
    }
    KeymasterArguments args = new KeymasterArguments();
    args.addUnsignedInt(KeymasterDefs.KM_TAG_KEY_SIZE, mKeySizeBits);
    args.addEnum(KeymasterDefs.KM_TAG_ALGORITHM, mKeymasterAlgorithm);
    args.addEnums(KeymasterDefs.KM_TAG_PURPOSE, mKeymasterPurposes);
    args.addEnums(KeymasterDefs.KM_TAG_BLOCK_MODE, mKeymasterBlockModes);
    args.addEnums(KeymasterDefs.KM_TAG_PADDING, mKeymasterPaddings);
    args.addEnums(KeymasterDefs.KM_TAG_DIGEST, mKeymasterDigests);
    if (spec.isUseSecureProcessor())
        args.addBoolean(KeymasterDefs.KM_TAG_USE_SECURE_PROCESSOR);
    KeymasterUtils.addUserAuthArgs(args, spec.isUserAuthenticationRequired(), spec.getUserAuthenticationValidityDurationSeconds(), spec.isUserAuthenticationValidWhileOnBody(), spec.isInvalidatedByBiometricEnrollment());
    KeymasterUtils.addMinMacLengthAuthorizationIfNecessary(args, mKeymasterAlgorithm, mKeymasterBlockModes, mKeymasterDigests);
    args.addDateIfNotNull(KeymasterDefs.KM_TAG_ACTIVE_DATETIME, spec.getKeyValidityStart());
    args.addDateIfNotNull(KeymasterDefs.KM_TAG_ORIGINATION_EXPIRE_DATETIME, spec.getKeyValidityForOriginationEnd());
    args.addDateIfNotNull(KeymasterDefs.KM_TAG_USAGE_EXPIRE_DATETIME, spec.getKeyValidityForConsumptionEnd());
    if (((spec.getPurposes() & KeyProperties.PURPOSE_ENCRYPT) != 0) && (!spec.isRandomizedEncryptionRequired())) {
        // Permit caller-provided IV when encrypting with this key
        args.addBoolean(KeymasterDefs.KM_TAG_CALLER_NONCE);
    }
    byte[] additionalEntropy = KeyStoreCryptoOperationUtils.getRandomBytesToMixIntoKeystoreRng(mRng, (mKeySizeBits + 7) / 8);
    int flags = 0;
    String keyAliasInKeystore = Credentials.USER_SECRET_KEY + spec.getKeystoreAlias();
    KeyCharacteristics resultingKeyCharacteristics = new KeyCharacteristics();
    boolean success = false;
    try {
        Credentials.deleteAllTypesForAlias(mKeyStore, spec.getKeystoreAlias(), spec.getUid());
        int errorCode = mKeyStore.generateKey(keyAliasInKeystore, args, additionalEntropy, spec.getUid(), flags, resultingKeyCharacteristics);
        if (errorCode != KeyStore.NO_ERROR) {
            throw new ProviderException("Keystore operation failed", KeyStore.getKeyStoreException(errorCode));
        }
        @KeyProperties.KeyAlgorithmEnum String keyAlgorithmJCA;
        try {
            keyAlgorithmJCA = KeyProperties.KeyAlgorithm.fromKeymasterSecretKeyAlgorithm(mKeymasterAlgorithm, mKeymasterDigest);
        } catch (IllegalArgumentException e) {
            throw new ProviderException("Failed to obtain JCA secret key algorithm name", e);
        }
        SecretKey result = new AndroidKeyStoreSecretKey(keyAliasInKeystore, spec.getUid(), keyAlgorithmJCA);
        success = true;
        return result;
    } finally {
        if (!success) {
            Credentials.deleteAllTypesForAlias(mKeyStore, spec.getKeystoreAlias(), spec.getUid());
        }
    }
}
Also used : KeymasterArguments(android.security.keymaster.KeymasterArguments) KeyGenParameterSpec(android.security.keystore.KeyGenParameterSpec) ProviderException(java.security.ProviderException) SecretKey(javax.crypto.SecretKey) KeyCharacteristics(android.security.keymaster.KeyCharacteristics)

Example 25 with KeymasterArguments

use of android.security.keymaster.KeymasterArguments in project android_frameworks_base by AOSPA.

the class AndroidKeyStoreKeyPairGeneratorSpi method initialize.

@SuppressWarnings("deprecation")
@Override
public void initialize(AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException {
    resetAll();
    boolean success = false;
    try {
        if (params == null) {
            throw new InvalidAlgorithmParameterException("Must supply params of type " + KeyGenParameterSpec.class.getName() + " or " + KeyPairGeneratorSpec.class.getName());
        }
        KeyGenParameterSpec spec;
        boolean encryptionAtRestRequired = false;
        int keymasterAlgorithm = mOriginalKeymasterAlgorithm;
        if (params instanceof KeyGenParameterSpec) {
            spec = (KeyGenParameterSpec) params;
        } else if (params instanceof KeyPairGeneratorSpec) {
            // Legacy/deprecated spec
            KeyPairGeneratorSpec legacySpec = (KeyPairGeneratorSpec) params;
            try {
                KeyGenParameterSpec.Builder specBuilder;
                String specKeyAlgorithm = legacySpec.getKeyType();
                if (specKeyAlgorithm != null) {
                    // Spec overrides the generator's default key algorithm
                    try {
                        keymasterAlgorithm = KeyProperties.KeyAlgorithm.toKeymasterAsymmetricKeyAlgorithm(specKeyAlgorithm);
                    } catch (IllegalArgumentException e) {
                        throw new InvalidAlgorithmParameterException("Invalid key type in parameters", e);
                    }
                }
                switch(keymasterAlgorithm) {
                    case KeymasterDefs.KM_ALGORITHM_EC:
                        specBuilder = new KeyGenParameterSpec.Builder(legacySpec.getKeystoreAlias(), KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY);
                        // Authorized to be used with any digest (including no digest).
                        // MD5 was never offered for Android Keystore for ECDSA.
                        specBuilder.setDigests(KeyProperties.DIGEST_NONE, KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA224, KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA384, KeyProperties.DIGEST_SHA512);
                        break;
                    case KeymasterDefs.KM_ALGORITHM_RSA:
                        specBuilder = new KeyGenParameterSpec.Builder(legacySpec.getKeystoreAlias(), KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY);
                        // Authorized to be used with any digest (including no digest).
                        specBuilder.setDigests(KeyProperties.DIGEST_NONE, KeyProperties.DIGEST_MD5, KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA224, KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA384, KeyProperties.DIGEST_SHA512);
                        // Authorized to be used with any encryption and signature padding
                        // schemes (including no padding).
                        specBuilder.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE, KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1, KeyProperties.ENCRYPTION_PADDING_RSA_OAEP);
                        specBuilder.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1, KeyProperties.SIGNATURE_PADDING_RSA_PSS);
                        // Disable randomized encryption requirement to support encryption
                        // padding NONE above.
                        specBuilder.setRandomizedEncryptionRequired(false);
                        break;
                    default:
                        throw new ProviderException("Unsupported algorithm: " + mKeymasterAlgorithm);
                }
                if (legacySpec.getKeySize() != -1) {
                    specBuilder.setKeySize(legacySpec.getKeySize());
                }
                if (legacySpec.getAlgorithmParameterSpec() != null) {
                    specBuilder.setAlgorithmParameterSpec(legacySpec.getAlgorithmParameterSpec());
                }
                specBuilder.setCertificateSubject(legacySpec.getSubjectDN());
                specBuilder.setCertificateSerialNumber(legacySpec.getSerialNumber());
                specBuilder.setCertificateNotBefore(legacySpec.getStartDate());
                specBuilder.setCertificateNotAfter(legacySpec.getEndDate());
                encryptionAtRestRequired = legacySpec.isEncryptionRequired();
                specBuilder.setUserAuthenticationRequired(false);
                spec = specBuilder.build();
            } catch (NullPointerException | IllegalArgumentException e) {
                throw new InvalidAlgorithmParameterException(e);
            }
        } else {
            throw new InvalidAlgorithmParameterException("Unsupported params class: " + params.getClass().getName() + ". Supported: " + KeyGenParameterSpec.class.getName() + ", " + KeyPairGeneratorSpec.class.getName());
        }
        mEntryAlias = spec.getKeystoreAlias();
        mEntryUid = spec.getUid();
        mSpec = spec;
        mKeymasterAlgorithm = keymasterAlgorithm;
        mEncryptionAtRestRequired = encryptionAtRestRequired;
        mKeySizeBits = spec.getKeySize();
        initAlgorithmSpecificParameters();
        if (mKeySizeBits == -1) {
            mKeySizeBits = getDefaultKeySize(keymasterAlgorithm);
        }
        checkValidKeySize(keymasterAlgorithm, mKeySizeBits);
        if (spec.isUseSecureProcessor()) {
            checkSecureProcessorValidKeySize(keymasterAlgorithm, mKeySizeBits);
        }
        if (spec.getKeystoreAlias() == null) {
            throw new InvalidAlgorithmParameterException("KeyStore entry alias not provided");
        }
        String jcaKeyAlgorithm;
        try {
            jcaKeyAlgorithm = KeyProperties.KeyAlgorithm.fromKeymasterAsymmetricKeyAlgorithm(keymasterAlgorithm);
            mKeymasterPurposes = KeyProperties.Purpose.allToKeymaster(spec.getPurposes());
            mKeymasterBlockModes = KeyProperties.BlockMode.allToKeymaster(spec.getBlockModes());
            mKeymasterEncryptionPaddings = KeyProperties.EncryptionPadding.allToKeymaster(spec.getEncryptionPaddings());
            if (((spec.getPurposes() & KeyProperties.PURPOSE_ENCRYPT) != 0) && (spec.isRandomizedEncryptionRequired())) {
                for (int keymasterPadding : mKeymasterEncryptionPaddings) {
                    if (!KeymasterUtils.isKeymasterPaddingSchemeIndCpaCompatibleWithAsymmetricCrypto(keymasterPadding)) {
                        throw new InvalidAlgorithmParameterException("Randomized encryption (IND-CPA) required but may be violated" + " by padding scheme: " + KeyProperties.EncryptionPadding.fromKeymaster(keymasterPadding) + ". See " + KeyGenParameterSpec.class.getName() + " documentation.");
                    }
                }
            }
            mKeymasterSignaturePaddings = KeyProperties.SignaturePadding.allToKeymaster(spec.getSignaturePaddings());
            if (spec.isDigestsSpecified()) {
                mKeymasterDigests = KeyProperties.Digest.allToKeymaster(spec.getDigests());
            } else {
                mKeymasterDigests = EmptyArray.INT;
            }
            // Check that user authentication related parameters are acceptable. This method
            // will throw an IllegalStateException if there are issues (e.g., secure lock screen
            // not set up).
            KeymasterUtils.addUserAuthArgs(new KeymasterArguments(), mSpec.isUserAuthenticationRequired(), mSpec.getUserAuthenticationValidityDurationSeconds(), mSpec.isUserAuthenticationValidWhileOnBody(), mSpec.isInvalidatedByBiometricEnrollment());
        } catch (IllegalArgumentException | IllegalStateException e) {
            throw new InvalidAlgorithmParameterException(e);
        }
        mJcaKeyAlgorithm = jcaKeyAlgorithm;
        mRng = random;
        mKeyStore = KeyStore.getInstance();
        success = true;
    } finally {
        if (!success) {
            resetAll();
        }
    }
}
Also used : KeyPairGeneratorSpec(android.security.KeyPairGeneratorSpec) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) KeymasterArguments(android.security.keymaster.KeymasterArguments) RSAKeyGenParameterSpec(java.security.spec.RSAKeyGenParameterSpec) ProviderException(java.security.ProviderException) DERBitString(com.android.org.bouncycastle.asn1.DERBitString)

Aggregations

KeymasterArguments (android.security.keymaster.KeymasterArguments)90 KeyCharacteristics (android.security.keymaster.KeyCharacteristics)50 OperationResult (android.security.keymaster.OperationResult)30 ProviderException (java.security.ProviderException)30 IBinder (android.os.IBinder)15 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)15 InvalidKeyException (java.security.InvalidKeyException)15 KeyGenParameterSpec (android.security.keystore.KeyGenParameterSpec)10 KeyProtection (android.security.keystore.KeyProtection)10 KeyStoreException (java.security.KeyStoreException)10 KeyPairGeneratorSpec (android.security.KeyPairGeneratorSpec)5 KeyStoreParameter (android.security.KeyStoreParameter)5 KeymasterBlob (android.security.keymaster.KeymasterBlob)5 DERBitString (com.android.org.bouncycastle.asn1.DERBitString)5 GeneralSecurityException (java.security.GeneralSecurityException)5 CertificateEncodingException (java.security.cert.CertificateEncodingException)5 X509Certificate (java.security.cert.X509Certificate)5 RSAKeyGenParameterSpec (java.security.spec.RSAKeyGenParameterSpec)5 SecretKey (javax.crypto.SecretKey)5