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

Recovery Phrase / Alternate Password #272

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 5 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
58 changes: 58 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ subtle = "2.6.1"
bon = "3.3.0"
shush-rs = "0.1.10"
criterion = { version = "0.5.1", features = ["html_reports"] }
bip39 = { version = "2.1.0", features = ["all-languages"] }

[target.'cfg(target_os = "linux")'.dependencies]
fuse3 = { version = "0.8.1", features = ["tokio-runtime", "unprivileged"] }
Expand Down
29 changes: 29 additions & 0 deletions examples/update_pswd_with_recover_key.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
use std::env::args;
use std::path::Path;
use std::str::FromStr;
use shush_rs::SecretString;
use rencfs::crypto::Cipher;
use rencfs::encryptedfs::{EncryptedFs, FsError};

#[tokio::main]
async fn main() {
tracing_subscriber::fmt().init();

let mut args = args();
let _ = args.next(); // skip the program name
let data_dir = args.next().expect("data_dir is missing");

match EncryptedFs::update_passwd_with_recovery_key(
Path::new(&data_dir),
SecretString::from_str("flight wrap symptom gadget purpose tower equal under simple satisfy female vacant critic mass media safe orchard barrel orchard intact safe butter bronze custom").unwrap(),
SecretString::from_str("new-pass").unwrap(),
Cipher::ChaCha20Poly1305,
)
.await
{
Ok(()) => println!("Password changed successfully"),
Err(FsError::InvalidPassword) => println!("Invalid old password"),
Err(FsError::InvalidDataDirStructure) => println!("Invalid structure of data directory"),
Err(err) => println!("Error: {err}"),
}
}
6 changes: 6 additions & 0 deletions src/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ use crate::{fs_util, stream_util};
pub mod buf_mut;
pub mod read;
pub mod write;
pub mod bip39;

pub static BASE64: GeneralPurpose = GeneralPurpose::new(&STANDARD, NO_PAD);

Expand Down Expand Up @@ -101,6 +102,11 @@ pub enum Error {
source: bincode::Error,
// backtrace: Backtrace,
},
#[error("")]
Hrushi20 marked this conversation as resolved.
Show resolved Hide resolved
RecoveryPhraseError {
#[from]
source: bip39::Error
},
#[error("generic error: {0}")]
Generic(&'static str),
#[error("generic error: {0}")]
Expand Down
127 changes: 127 additions & 0 deletions src/crypto/bip39.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
use bip39;

use crate::crypto::Result;
use shush_rs::{ExposeSecret, SecretString, SecretVec};

pub(crate) use bip39::Error;
use strum_macros::EnumIter;

pub(crate) fn generate_recovery_phrase(language: Language, key:&SecretVec<u8>) -> Result<String> {
let entropy = key.expose_secret();
let recovery_phrase = bip39::Mnemonic::from_entropy_in(language.into(), &entropy)?;

Ok(recovery_phrase.to_string())
}

// Can create a struct here.
pub(crate) fn mnemonic_to_entropy(mnemonic: &SecretString) -> Result<(Vec<u8>,Language)> {
let parsed_data = bip39::Mnemonic::parse_normalized(&mnemonic.expose_secret())?;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think correct is to_entropy

Ok((parsed_data.to_entropy(), parsed_data.language().into()))
}

// Avoid depending on the library directly.
#[derive(Copy, Clone, EnumIter)]
pub enum Language {

English,
// #[cfg(feature = "chinese-simplified")]
SimplifiedChinese,
// #[cfg(feature = "chinese-traditional")]
TraditionalChinese,
// #[cfg(feature = "czech")]
Czech,
// #[cfg(feature = "french")]
French,
// #[cfg(feature = "italian")]
Italian,
// #[cfg(feature = "japanese")]
Japanese,
// #[cfg(feature = "korean")]
Korean,
// #[cfg(feature = "portuguese")]
Portuguese,
// #[cfg(feature = "spanish")]
Spanish,
}

impl From<Language> for bip39::Language {
fn from(value: Language) -> Self {
match value {
Language::English => bip39::Language::English,
// #[cfg(feature = "chinese-simplified")]
Language::SimplifiedChinese => bip39::Language::SimplifiedChinese,
// #[cfg(feature = "chinese-traditional")]
Language::TraditionalChinese => bip39::Language::TraditionalChinese,
// #[cfg(feature = "czech")]
Language::Czech => bip39::Language::Czech,
// #[cfg(feature = "french")]
Language::French => bip39::Language::French,
// #[cfg(feature = "italian")]
Language::Italian => bip39::Language::Italian,
// #[cfg(feature = "japanese")]
Language::Japanese => bip39::Language::Japanese,
// #[cfg(feature = "korean")]
Language::Korean => bip39::Language::Korean,
// #[cfg(feature = "portuguese")]
Language::Portuguese => bip39::Language::Portuguese,
// #[cfg(feature = "spanish")]
Language::Spanish => bip39::Language::Spanish,
}
}
}

impl From<bip39::Language> for Language {
fn from(value: bip39::Language) -> Self {
match value {
bip39::Language::English => Language::English,
// #[cfg(feature = "chinese-simplified")]
bip39::Language::SimplifiedChinese => Language::SimplifiedChinese,
// #[cfg(feature = "chinese-traditional")]
bip39::Language::TraditionalChinese => Language::TraditionalChinese,
// #[cfg(feature = "czech")]
bip39::Language::Czech => Language::Czech,
// #[cfg(feature = "french")]
bip39::Language::French => Language::French,
// #[cfg(feature = "italian")]
bip39::Language::Italian => Language::Italian,
// #[cfg(feature = "japanese")]
bip39::Language::Japanese => Language::Japanese,
// #[cfg(feature = "korean")]
bip39::Language::Korean => Language::Korean,
// #[cfg(feature = "portuguese")]
bip39::Language::Portuguese => Language::Portuguese,
// #[cfg(feature = "spanish")]
bip39::Language::Spanish => Language::Spanish,
}
}
}

impl Default for Language {
fn default() -> Self {
Language::English
}
}

#[cfg(test)]
mod tests {
use argon2::password_hash::rand_core::RngCore;
use super::*;
use shush_rs::SecretVec;
use strum::IntoEnumIterator;

#[test]
fn init_recovery_phrase(){
let mut entropy = vec![0; 16];
crate::crypto::create_rng().fill_bytes(&mut entropy);
let secret_vec = SecretVec::new(Box::new(entropy.clone()));
for lang in Language::iter() {

let recovery_phrase = generate_recovery_phrase(lang, &secret_vec).unwrap();
let recovery_phrase = SecretString::new(Box::new(recovery_phrase));
let mnemonic = mnemonic_to_entropy(&recovery_phrase).unwrap();
assert_eq!(entropy, mnemonic.0);
}


}
}
43 changes: 42 additions & 1 deletion src/encryptedfs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ use crate::crypto::Cipher;
use crate::expire_value::{ExpireValue, ValueProvider};
use crate::{crypto, fs_util, stream_util};
use bon::bon;
use crate::crypto::bip39::Language;

mod bench;
#[cfg(test)]
Expand Down Expand Up @@ -275,6 +276,8 @@ pub enum FsError {
Other(&'static str),
#[error("invalid password")]
InvalidPassword,
#[error("invalid recovery key")]
InvalidRecoveryKey,
Hrushi20 marked this conversation as resolved.
Show resolved Hide resolved
#[error("invalid structure of data directory")]
InvalidDataDirStructure,
#[error("crypto error: {source}")]
Expand Down Expand Up @@ -510,12 +513,17 @@ impl ValueProvider<SecretVec<u8>, FsError> for KeyProvider {
.password_provider
.get_password()
.ok_or(FsError::InvalidPassword)?;
read_or_create_key(&self.key_path, &self.salt_path, &password, self.cipher)
let recovery_phrase_lang = self.password_provider.recovery_phrase_format().unwrap_or_else(|| Language::default());
Hrushi20 marked this conversation as resolved.
Show resolved Hide resolved
read_or_create_key(&self.key_path, &self.salt_path, &password, self.cipher, recovery_phrase_lang)
}
}

pub trait PasswordProvider: Send + Sync + 'static {
fn get_password(&self) -> Option<SecretString>;

fn recovery_phrase_format(&self) -> Option<Language>{
Hrushi20 marked this conversation as resolved.
Show resolved Hide resolved
Some(Language::default())
}
}

struct DirEntryNameCacheProvider {}
Expand Down Expand Up @@ -2130,6 +2138,36 @@ impl EncryptedFs {
}

/// Change the password of the filesystem used to access the encryption key.
pub async fn update_passwd_with_recovery_key(
data_dir: &Path,
recovery_key: SecretString,
new_password: SecretString,
cipher: Cipher) -> FsResult<()>{
check_structure(data_dir, false).await?;

let salt: Vec<u8> = bincode::deserialize_from(File::open(
data_dir.join(SECURITY_DIR).join(KEY_SALT_FILENAME),
radumarias marked this conversation as resolved.
Show resolved Hide resolved
)?)?;
let decrypted_mnemonic = crypto::bip39::mnemonic_to_entropy(&recovery_key)?;
let initial_key = SecretVec::new(Box::new(decrypted_mnemonic.0));
let enc_file = data_dir.join(SECURITY_DIR).join(KEY_ENC_FILENAME);
let reader = crypto::create_read(File::open(enc_file)?, cipher, &initial_key);
let key: Vec<u8> =
bincode::deserialize_from(reader).map_err(|_| FsError::InvalidRecoveryKey)?;
let key = SecretBox::new(Box::new(key));
// encrypt it with a new key derived from new password
let new_key = crypto::derive_key(&new_password, cipher, &salt)?;
let new_recovery_key = crypto::bip39::generate_recovery_phrase(decrypted_mnemonic.1, &new_key)?;
info!("New Recovery key: {}", new_recovery_key);
crypto::atomic_serialize_encrypt_into(
&data_dir.join(SECURITY_DIR).join(KEY_ENC_FILENAME),
&*key.expose_secret(),
cipher,
&new_key,
)?;
Ok(())
}

pub async fn passwd(
data_dir: &Path,
old_password: SecretString,
Expand Down Expand Up @@ -2499,6 +2537,7 @@ fn read_or_create_key(
salt_path: &PathBuf,
password: &SecretString,
cipher: Cipher,
recovery_phrase_lang: Language
) -> FsResult<SecretVec<u8>> {
let salt = if salt_path.exists() {
bincode::deserialize_from(File::open(salt_path)?).map_err(|_| FsError::InvalidPassword)?
Expand All @@ -2519,6 +2558,8 @@ fn read_or_create_key(
};
// derive key from password
let derived_key = crypto::derive_key(password, cipher, &salt)?;
let recovery_key = crypto::bip39::generate_recovery_phrase(recovery_phrase_lang, &derived_key)?;
info!("Recovery key: {}", recovery_key);
if key_path.exists() {
// read key
let reader = crypto::create_read(File::open(key_path)?, cipher, &derived_key);
Expand Down
Loading