Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

KeyStoreException when AWS Cognito tries to create EncryptedSharedPreferences #2510

Closed
1 task done
reisfernanda opened this issue Jul 11, 2023 · 11 comments
Closed
1 task done
Assignees
Labels
auth Related to the Auth category/plugins pending-maintainer-response Issue is pending response from an Amplify team member

Comments

@reisfernanda
Copy link

Before opening, please confirm:

Language and Async Model

Kotlin - Coroutines

Amplify Categories

Authentication

Gradle script dependencies

implementation("com.squareup.okhttp3:okhttp:5.0.0-alpha.11")
implementation("com.amplifyframework:aws-auth-cognito:2.8.7")
implementation("com.amplifyframework:core-kotlin:2.8.7")

Environment information

------------------------------------------------------------
Gradle 7.6.2
------------------------------------------------------------

Build time:   2023-06-30 15:42:51 UTC
Revision:     dab132169006b16e7ada4ab2456e0c9d6415b52a

Kotlin:       1.7.10
Groovy:       3.0.13
Ant:          Apache Ant(TM) version 1.10.11 compiled on July 10 2021
JVM:          11.0.12 (Oracle Corporation 11.0.12+8-LTS-237)
OS:           Windows 10 10.0 amd64

Please include any relevant guides or documentation you're referencing

No response

Describe the bug

Our crash monitoring is reporting some occurrences of an android.security.KeyStoreException (com.google.crypto.tink.integration.android.AndroidKeystoreAesGcm.encryptInternal) under the creation of EncryptedSharedPreferences (com.amplifyframework.core.store.EncryptedKeyValueRepository).
I couldn't reproduce the issue in any way, but the rare users that find this problem can reproduce it frequently.
I'm not sure when this is happening but I believe it's when the app is starting since 100% of the occurrences happened with the app in background, and also because these occurrences happen before the application can send logs related to fragments creation.
This crash happens on the devices:

  • Motorola Edge 30 Pro - Android 13
  • Samsung - Android 12 (the crash monitoring tool does not inform the specific model of this Samsung device)

Another crash with the same exception also happens but for com.google.crypto.tink.integration.android.AndroidKeystoreAesGcm.decryptInternal

Reproduction steps (if applicable)

No response

Code Snippet

class AppApplication : Application() {

    override fun onCreate() {
        super.onCreate()
        try {
            Amplify.addPlugin(AWSCognitoAuthPlugin())
            Amplify.configure(context)
        } catch (exception: AmplifyException) {
            loggingManager.logNonFatalException(exception)
        }
    }
}

Log output


Fatal Exception: java.security.InvalidKeyException: Keystore operation failed
       at android.security.keystore2.KeyStoreCryptoOperationUtils.getInvalidKeyException(KeyStoreCryptoOperationUtils.java:130)
       at android.security.keystore2.KeyStoreCryptoOperationUtils.getExceptionForCipherInit(KeyStoreCryptoOperationUtils.java:154)
       at android.security.keystore2.AndroidKeyStoreCipherSpiBase.ensureKeystoreOperationInitialized(AndroidKeyStoreCipherSpiBase.java:339)
       at android.security.keystore2.AndroidKeyStoreCipherSpiBase.engineInit(AndroidKeyStoreCipherSpiBase.java:171)
       at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:2985)
       at javax.crypto.Cipher.tryCombinations(Cipher.java:2892)
       at javax.crypto.Cipher$SpiAndProviderUpdater.updateAndGetSpiAndProvider(Cipher.java:2797)
       at javax.crypto.Cipher.chooseProvider(Cipher.java:774)
       at javax.crypto.Cipher.init(Cipher.java:1144)
       at javax.crypto.Cipher.init(Cipher.java:1085)
       at com.google.crypto.tink.integration.android.AndroidKeystoreAesGcm.encryptInternal(AndroidKeystoreAesGcm.java:85)
       at com.google.crypto.tink.integration.android.AndroidKeystoreAesGcm.encrypt(AndroidKeystoreAesGcm.java:73)
       at com.google.crypto.tink.integration.android.AndroidKeystoreKmsClient.validateAead(AndroidKeystoreKmsClient.java:298)
       at com.google.crypto.tink.integration.android.AndroidKeystoreKmsClient.getAead(AndroidKeystoreKmsClient.java:180)
       at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.readMasterkeyDecryptAndParseKeyset(AndroidKeysetManager.java:366)
       at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.build(AndroidKeysetManager.java:298)
       at androidx.security.crypto.EncryptedSharedPreferences.create(EncryptedSharedPreferences.java:123)
       at com.amplifyframework.core.store.EncryptedKeyValueRepository$sharedPreferences$2.invoke(EncryptedKeyValueRepository.kt:35)
       at com.amplifyframework.core.store.EncryptedKeyValueRepository$sharedPreferences$2.invoke(EncryptedKeyValueRepository.kt:34)
       at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
       at com.amplifyframework.core.store.EncryptedKeyValueRepository.getSharedPreferences$com_amplifyframework_core(EncryptedKeyValueRepository.kt:34)
       at com.amplifyframework.core.store.EncryptedKeyValueRepository.get(EncryptedKeyValueRepository.kt:56)
       at com.amplifyframework.auth.cognito.data.AWSCognitoAuthCredentialStore.retrieveCredential(AWSCognitoAuthCredentialStore.kt:63)
       at com.amplifyframework.auth.cognito.actions.CredentialStoreCognitoActions$loadCredentialStoreAction$$inlined$invoke$1.execute(Action.kt:70)
       at com.amplifyframework.statemachine.ConcurrentEffectExecutor$execute$1$1.invokeSuspend(ConcurrentEffectExecutor.kt:26)
       at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
       at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
       at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.java:584)
       at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:793)
       at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:697)
       at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:684)

Caused by android.security.KeyStoreException: System error (internal Keystore code: 4 message: In create_operation: Failed to begin operation.

Caused by:
    0: In KeystoreSecurityLevel::upgrade_keyblob_if_required_with.
    1: In utils::upgrade_keyblob_if_required_with: Calling km_op.
    2: Binder exception code SERVICE_SPECIFIC, 15)
       at android.security.KeyStore2.getKeyStoreException(KeyStore2.java:336)
       at android.security.KeyStoreSecurityLevel.createOperation(KeyStoreSecurityLevel.java:120)
       at android.security.keystore2.AndroidKeyStoreCipherSpiBase.ensureKeystoreOperationInitialized(AndroidKeyStoreCipherSpiBase.java:334)
       at android.security.keystore2.AndroidKeyStoreCipherSpiBase.engineInit(AndroidKeyStoreCipherSpiBase.java:171)
       at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:2985)
       at javax.crypto.Cipher.tryCombinations(Cipher.java:2892)
       at javax.crypto.Cipher$SpiAndProviderUpdater.updateAndGetSpiAndProvider(Cipher.java:2797)
       at javax.crypto.Cipher.chooseProvider(Cipher.java:774)
       at javax.crypto.Cipher.init(Cipher.java:1144)
       at javax.crypto.Cipher.init(Cipher.java:1085)
       at com.google.crypto.tink.integration.android.AndroidKeystoreAesGcm.encryptInternal(AndroidKeystoreAesGcm.java:85)
       at com.google.crypto.tink.integration.android.AndroidKeystoreAesGcm.encrypt(AndroidKeystoreAesGcm.java:73)
       at com.google.crypto.tink.integration.android.AndroidKeystoreKmsClient.validateAead(AndroidKeystoreKmsClient.java:298)
       at com.google.crypto.tink.integration.android.AndroidKeystoreKmsClient.getAead(AndroidKeystoreKmsClient.java:180)
       at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.readMasterkeyDecryptAndParseKeyset(AndroidKeysetManager.java:366)
       at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.build(AndroidKeysetManager.java:298)
       at androidx.security.crypto.EncryptedSharedPreferences.create(EncryptedSharedPreferences.java:123)
       at com.amplifyframework.core.store.EncryptedKeyValueRepository$sharedPreferences$2.invoke(EncryptedKeyValueRepository.kt:35)
       at com.amplifyframework.core.store.EncryptedKeyValueRepository$sharedPreferences$2.invoke(EncryptedKeyValueRepository.kt:34)
       at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74)
       at com.amplifyframework.core.store.EncryptedKeyValueRepository.getSharedPreferences$com_amplifyframework_core(EncryptedKeyValueRepository.kt:34)
       at com.amplifyframework.core.store.EncryptedKeyValueRepository.get(EncryptedKeyValueRepository.kt:56)
       at com.amplifyframework.auth.cognito.data.AWSCognitoAuthCredentialStore.retrieveCredential(AWSCognitoAuthCredentialStore.kt:63)
       at com.amplifyframework.auth.cognito.actions.CredentialStoreCognitoActions$loadCredentialStoreAction$$inlined$invoke$1.execute(Action.kt:70)
       at com.amplifyframework.statemachine.ConcurrentEffectExecutor$execute$1$1.invokeSuspend(ConcurrentEffectExecutor.kt:26)
       at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
       at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
       at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.java:584)
       at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:793)
       at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:697)
       at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:684)

amplifyconfiguration.json

{
    "UserAgent": "aws-amplify-cli/2.0",
    "Version": "1.0",
    "auth": {
        "plugins": {
            "awsCognitoAuthPlugin": {
                "UserAgent": "aws-amplify/cli",
                "Version": "0.1.0",
                "IdentityManager": {
                    "Default": {}
                },
                "CognitoUserPool": {
                    "Default": {
                        "PoolId": "********",
                        "AppClientId": "********",
                        "Region": "******"
                    }
                },
                "Auth": {
                    "Default": {
                        "OAuth": {
                            "WebDomain": "*******",
                            "AppClientId": "*******",
                            "SignInRedirectURI": "*******",
                            "SignOutRedirectURI": "*******",
                            "Scopes": [
                                "aws.cognito.signin.user.admin",
                                "email",
                                "openid",
                                "phone",
                                "profile"
                            ]
                        },
                        "authenticationFlowType": "USER_SRP_AUTH",
                        "socialProviders": [
                            "FACEBOOK",
                            "GOOGLE",
                            "APPLE"
                        ],
                        "usernameAttributes": [],
                        "signupAttributes": [],
                        "passwordProtectionSettings": {
                            "passwordPolicyMinLength": 8,
                            "passwordPolicyCharacters": [
                                "REQUIRES_LOWERCASE",
                                "REQUIRES_UPPERCASE",
                                "REQUIRES_NUMBERS",
                                "REQUIRES_SYMBOLS"
                            ]
                        },
                        "mfaConfiguration": "OFF",
                        "mfaTypes": [],
                        "verificationMechanisms": [
                            "EMAIL"
                        ]
                    }
                }
            }
        }
    }
}

GraphQL Schema

// Put your schema below this line

Additional information and screenshots

No response

@gpanshu gpanshu added the auth Related to the Auth category/plugins label Jul 13, 2023
@gpanshu
Copy link
Contributor

gpanshu commented Jul 25, 2023

Hi @reisfernanda can you advise what is your android:allowBackup set to in your manifest ?

@reisfernanda
Copy link
Author

Hello @gpanshu, android:allowBackup is set to false

@gpanshu
Copy link
Contributor

gpanshu commented Jul 27, 2023

This is a known issue however we will investigate how we can fix it or help you fix it.

@reisfernanda
Copy link
Author

Ok. We're having 4 exceptions under the same piece of code:

com.amplifyframework.core.store.EncryptedKeyValueRepository$sharedPreferences$2.invoke (EncryptedKeyValueRepository.kt:35)

image

Is there any other information we can provide to help you?
Thank you!

@gpanshu
Copy link
Contributor

gpanshu commented Jul 27, 2023

Nope I think you have provided all you can provide. We will investigate and get back to you. In the meantime have you tried not have the androidBackup line in your manifest?

@reisfernanda
Copy link
Author

No, I didn't try to remove the android:allowBackup because the default value is true and it can expose some user-sensitive data. Also, some developers said removing this line didn't fix the issue.

@gpanshu gpanshu self-assigned this Jul 31, 2023
@gpanshu
Copy link
Contributor

gpanshu commented Jul 31, 2023

@reisfernanda unfortunately since this is a known issue with the platform, as a library there is nothing we can do about it nor we can recommend or endorse solutions that we have not tested that are on the thread that have worked for people. If you figure out a solution that would work please reply to this thread to help the community but as for this issue, this is working as designed. I hope this helps.

@gpanshu gpanshu closed this as completed Jul 31, 2023
@github-actions
Copy link
Contributor

⚠️COMMENT VISIBILITY WARNING⚠️

Comments on closed issues are hard for our team to see.
If you need more assistance, please either tag a team member or open a new issue that references this one.
If you wish to keep having a conversation with other community members under this issue feel free to do so.

@r-elbouhi
Copy link

r-elbouhi commented Aug 6, 2023

But I have same issue in "EncryptedKeyValueRepository" class. Here is the crash output from :

Fatal Exception: com.google.crypto.tink.shaded.protobuf.InvalidProtocolBufferException: Protocol message contained an invalid tag (zero). 
at com.google.crypto.tink.shaded.protobuf.GeneratedMessageLite.parsePartialFrom(GeneratedMessageLite.java:1566) 
at com.google.crypto.tink.shaded.protobuf.GeneratedMessageLite.parseFrom(GeneratedMessageLite.java:1664) 
at com.google.crypto.tink.proto.Keyset.parseFrom(Keyset.java:957) 
at com.google.crypto.tink.integration.android.SharedPrefKeysetReader.read(SharedPrefKeysetReader.java:84)
at com.google.crypto.tink.CleartextKeysetHandle.read(CleartextKeysetHandle.java) at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.read(AndroidKeysetManager.java:328) 
at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.readOrGenerateNewKeyset(AndroidKeysetManager.java:287) at com.google.crypto.tink.integration.android.AndroidKeysetManager$Builder.build(AndroidKeysetManager.java:238) at androidx.security.crypto.EncryptedSharedPreferences.create(EncryptedSharedPreferences.java:123) 
at com.amplifyframework.core.store.EncryptedKeyValueRepository$sharedPreferences$2.invoke(EncryptedKeyValueRepository.kt:35) 
at com.amplifyframework.core.store.EncryptedKeyValueRepository$sharedPreferences$2.invoke(EncryptedKeyValueRepository.kt:34) at kotlin.SynchronizedLazyImpl.getValue(LazyJVM.kt:74) 
at com.amplifyframework.core.store.EncryptedKeyValueRepository.getSharedPreferences$com_amplifyframework_core(EncryptedKeyValueRepository.kt:34) 
at com.amplifyframework.core.store.EncryptedKeyValueRepository.get(EncryptedKeyValueRepository.kt:56) at com.amplifyframework.auth.cognito.data.AWSCognitoAuthCredentialStore.retrieveCredential(AWSCognitoAuthCredentialStore.kt:63) 
at com.amplifyframework.auth.cognito.actions.CredentialStoreCognitoActions$loadCredentialStoreAction$$inlined$invoke$1.execute(Action.kt:70) 
at com.amplifyframework.statemachine.ConcurrentEffectExecutor$execute$1$1.invokeSuspend(ConcurrentEffectExecutor.kt:26) at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33) 
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106) 
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570) 
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750) 
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677) 
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt)

And already define android:allowBackup with false

@BadTokenException
Copy link

@reisfernanda unfortunately since this is a known issue with the platform, as a library there is nothing we can do about it nor we can recommend or endorse solutions that we have not tested that are on the thread that have worked for people. If you figure out a solution that would work please reply to this thread to help the community but as for this issue, this is working as designed. I hope this helps.

Is there a way to fix it?

@github-actions github-actions bot added the pending-maintainer-response Issue is pending response from an Amplify team member label Oct 21, 2024
@BadTokenException
Copy link

Ok. We're having 4 exceptions under the same piece of code:

com.amplifyframework.core.store.EncryptedKeyValueRepository$sharedPreferences$2.invoke (EncryptedKeyValueRepository.kt:35)

image

Is there any other information we can provide to help you? Thank you!

Did you find a fix?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
auth Related to the Auth category/plugins pending-maintainer-response Issue is pending response from an Amplify team member
Projects
None yet
Development

No branches or pull requests

4 participants