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

[PM-4695] Implement unlock with user key and update examples to use biometrics #330

Merged
merged 8 commits into from
Nov 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions crates/bitwarden-uniffi/src/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,17 @@ impl ClientCrypto {
.initialize_org_crypto(req)
.await?)
}

/// Get the uses's decrypted encryption key. Note: It's very important
/// to keep this key safe, as it can be used to decrypt all of the user's data
pub async fn get_user_encryption_key(&self) -> Result<String> {
Ok(self
.0
.0
.write()
.await
.crypto()
.get_user_encryption_key()
.await?)
}
}
17 changes: 17 additions & 0 deletions crates/bitwarden/src/client/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,23 @@ impl Client {
Ok(self.encryption_settings.as_ref().unwrap())
}

#[cfg(feature = "mobile")]
pub(crate) fn initialize_user_crypto_decrypted_key(
&mut self,
decrypted_user_key: &str,
private_key: EncString,
) -> Result<&EncryptionSettings> {
let user_key = decrypted_user_key.parse::<SymmetricCryptoKey>()?;
self.encryption_settings = Some(EncryptionSettings::new_decrypted_key(
user_key,
private_key,
)?);
Ok(self
.encryption_settings
.as_ref()
.expect("It was initialized on the previous line"))
}

pub(crate) fn initialize_crypto_single_key(
&mut self,
key: SymmetricCryptoKey,
Expand Down
38 changes: 24 additions & 14 deletions crates/bitwarden/src/client/encryption_settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ impl std::fmt::Debug for EncryptionSettings {
}

impl EncryptionSettings {
/// Initialize the encryption settings with the user password and their encrypted keys
#[cfg(feature = "internal")]
pub(crate) fn new(
login_method: &UserLoginMethod,
Expand All @@ -45,24 +46,33 @@ impl EncryptionSettings {
// Decrypt the user key
let user_key = master_key.decrypt_user_key(user_key)?;

// Decrypt the private key with the user key
let private_key = {
let dec: Vec<u8> = private_key.decrypt_with_key(&user_key)?;
Some(
rsa::RsaPrivateKey::from_pkcs8_der(&dec)
.map_err(|_| CryptoError::InvalidKey)?,
)
};

Ok(EncryptionSettings {
user_key,
private_key,
org_keys: HashMap::new(),
})
Self::new_decrypted_key(user_key, private_key)
}
}
}

/// Initialize the encryption settings with the decrypted user key and the encrypted user private key
/// This should only be used when unlocking the vault via biometrics or when the vault is set to lock: "never"
/// Otherwise handling the decrypted user key is dangerous and discouraged
#[cfg(feature = "internal")]
pub(crate) fn new_decrypted_key(
user_key: SymmetricCryptoKey,
private_key: EncString,
) -> Result<Self> {
let private_key = {
let dec: Vec<u8> = private_key.decrypt_with_key(&user_key)?;
Some(rsa::RsaPrivateKey::from_pkcs8_der(&dec).map_err(|_| CryptoError::InvalidKey)?)
};

Ok(EncryptionSettings {
user_key,
private_key,
org_keys: HashMap::new(),
})
}

/// Initialize the encryption settings with only a single decrypted key.
/// This is used only for logging in Secrets Manager with an access token
pub(crate) fn new_single_key(key: SymmetricCryptoKey) -> Self {
EncryptionSettings {
user_key: key,
Expand Down
8 changes: 7 additions & 1 deletion crates/bitwarden/src/mobile/client_crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ use crate::Client;
use crate::{
error::Result,
mobile::crypto::{
initialize_org_crypto, initialize_user_crypto, InitOrgCryptoRequest, InitUserCryptoRequest,
get_user_encryption_key, initialize_org_crypto, initialize_user_crypto,
InitOrgCryptoRequest, InitUserCryptoRequest,
},
};

Expand All @@ -21,6 +22,11 @@ impl<'a> ClientCrypto<'a> {
pub async fn initialize_org_crypto(&mut self, req: InitOrgCryptoRequest) -> Result<()> {
initialize_org_crypto(self.client, req).await
}

#[cfg(feature = "internal")]
pub async fn get_user_encryption_key(&mut self) -> Result<String> {
get_user_encryption_key(self.client).await
}
}

impl<'a> Client {
Expand Down
24 changes: 23 additions & 1 deletion crates/bitwarden/src/mobile/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@ use std::collections::HashMap;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::{client::kdf::Kdf, crypto::EncString, error::Result, Client};
use crate::{
client::kdf::Kdf,
crypto::EncString,
error::{Error, Result},
Client,
};

#[cfg(feature = "internal")]
#[derive(Serialize, Deserialize, Debug, JsonSchema)]
Expand Down Expand Up @@ -31,6 +36,10 @@ pub enum InitUserCryptoMethod {
/// The user's encrypted symmetric crypto key
user_key: String,
},
DecryptedKey {
/// The user's decrypted encryption key, obtained using `get_user_encryption_key`
decrypted_user_key: String,
},
}

#[cfg(feature = "internal")]
Expand All @@ -49,6 +58,9 @@ pub async fn initialize_user_crypto(client: &mut Client, req: InitUserCryptoRequ
let user_key: EncString = user_key.parse()?;
client.initialize_user_crypto(&password, user_key, private_key)?;
}
InitUserCryptoMethod::DecryptedKey { decrypted_user_key } => {
client.initialize_user_crypto_decrypted_key(&decrypted_user_key, private_key)?;
}
}

Ok(())
Expand All @@ -69,3 +81,13 @@ pub async fn initialize_org_crypto(client: &mut Client, req: InitOrgCryptoReques
client.initialize_org_crypto(organization_keys)?;
Ok(())
}

#[cfg(feature = "internal")]
pub async fn get_user_encryption_key(client: &mut Client) -> Result<String> {
let user_key = client
.get_encryption_settings()?
.get_key(&None)
.ok_or(Error::VaultLocked)?;

Ok(user_key.to_base64())
}
1 change: 1 addition & 0 deletions languages/kotlin/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ dependencies {
implementation 'androidx.compose.ui:ui-graphics'
implementation 'androidx.compose.ui:ui-tooling-preview'
implementation 'androidx.compose.material3:material3'
implementation "androidx.biometric:biometric:1.1.0"
implementation "io.ktor:ktor-client-core:2.3.3"
implementation "io.ktor:ktor-client-cio:2.3.3"
implementation "io.ktor:ktor-client-content-negotiation:2.3.3"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
package com.bitwarden.myapplication

import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Log
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricManager.Authenticators
import androidx.biometric.BiometricPrompt
import androidx.biometric.BiometricPrompt.CryptoObject
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import java.security.KeyStore
import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec

/**
* IMPORTANT: This file is provided only for the purpose of demostrating the use of the biometric unlock functionality.
* It hasn't gone through a throrough security review and should not be considered production ready. It also doesn't
* handle a lot of errors and edge cases that a production application would need to deal with.
* Developers are encouraged to review and improve the code as needed to meet their security requirements.
* Additionally, we recommend to consult with security experts and conduct thorough testing before using the code in production.
*/

class Biometric(private var activity: FragmentActivity) {
Hinton marked this conversation as resolved.
Show resolved Hide resolved
private var promptInfo: BiometricPrompt.PromptInfo =
BiometricPrompt.PromptInfo.Builder().setTitle("Unlock")
.setSubtitle("Bitwarden biometric unlock")
.setDescription("Confirm biometric to continue").setConfirmationRequired(true)
.setNegativeButtonText("Use account password").build()

suspend fun encryptString(
keyName: String, plaintext: String, callback: (String, String) -> Unit
) {
if (canAuthenticate()) {
val cipher = getCipher()
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(keyName))

val bio = createBiometricPrompt {
val ciphertext = it.cipher!!.doFinal(plaintext.toByteArray())
callback(
String(Base64.getEncoder().encode(ciphertext)),
String(Base64.getEncoder().encode(cipher.iv))
)
}
CoroutineScope(Dispatchers.Main).async {
bio.authenticate(promptInfo, CryptoObject(cipher))
}.await()
}
}

suspend fun decryptString(
keyName: String, encrypted: String, initializationVector: String, callback: (String) -> Unit
) {
if (canAuthenticate()) {
val enc = Base64.getDecoder().decode(encrypted)
val iv = Base64.getDecoder().decode(initializationVector)

val cipher = getCipher()
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(keyName), GCMParameterSpec(128, iv))

val bio = createBiometricPrompt {
callback(String(it.cipher!!.doFinal(enc)))
}

CoroutineScope(Dispatchers.Main).async {
bio.authenticate(promptInfo, CryptoObject(cipher))
}.await()
}
}

private fun canAuthenticate() = BiometricManager.from(activity)
.canAuthenticate(Authenticators.BIOMETRIC_STRONG) == BiometricManager.BIOMETRIC_SUCCESS

private fun createBiometricPrompt(processData: (CryptoObject) -> Unit): BiometricPrompt {
return BiometricPrompt(activity,
ContextCompat.getMainExecutor(activity),
object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
super.onAuthenticationError(errorCode, errString)
Log.e("Biometric", "$errorCode :: $errString")
}

override fun onAuthenticationFailed() {
super.onAuthenticationFailed()
Log.e("Biometric", "Authentication failed for an unknown reason")
}

override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
super.onAuthenticationSucceeded(result)
processData(result.cryptoObject!!)
}
})
}

private fun getCipher(): Cipher {
val transform =
"${KeyProperties.KEY_ALGORITHM_AES}/${KeyProperties.BLOCK_MODE_GCM}/${KeyProperties.ENCRYPTION_PADDING_NONE}"
return Cipher.getInstance(transform)
}

private fun getSecretKey(keyName: String): SecretKey {
// If the SecretKey exists, return it
val keyStore = KeyStore.getInstance("AndroidKeyStore")
keyStore.load(null)
keyStore.getKey(keyName, null)?.let { return it as SecretKey }

// Otherwise, we generate a new one
val keyGenParams = KeyGenParameterSpec.Builder(
keyName, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
).apply {
setBlockModes(KeyProperties.BLOCK_MODE_GCM)
setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
setKeySize(256)
setUserAuthenticationRequired(true)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG)
}
}.build()

val keyGenerator =
KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
keyGenerator.init(keyGenParams)
return keyGenerator.generateKey()
}
}
Loading