diff --git a/Cargo.lock b/Cargo.lock index 3107e3a6a..73a7f3879 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -209,6 +209,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23ce669cd6c8588f79e15cf450314f9638f967fc5770ff1c7c1deb0925ea7cfa" +[[package]] +name = "base64" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33678aec1839cd59fbb29a90950baa95fc4a5464711a7858f5ba68dbc3d3eab2" +dependencies = [ + "byteorder", +] + [[package]] name = "base64" version = "0.13.0" @@ -2587,7 +2596,7 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd56cbd21fea48d0c440b41cd69c589faacade08c992d9a54e471b79d0fd13eb" dependencies = [ - "base64", + "base64 0.13.0", "once_cell", "regex", ] @@ -2724,6 +2733,57 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "protobuf" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ee4a7d8b91800c8f167a6268d1a1026607368e1adc84e98fe044aeb905302f7" +dependencies = [ + "once_cell", + "protobuf-support", + "thiserror", +] + +[[package]] +name = "protobuf-codegen" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07b893e5e7d3395545d5244f8c0d33674025bd566b26c03bfda49b82c6dec45e" +dependencies = [ + "anyhow", + "once_cell", + "protobuf", + "protobuf-parse", + "regex", + "tempfile", + "thiserror", +] + +[[package]] +name = "protobuf-parse" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b1447dd751c434cc1b415579837ebd0411ed7d67d465f38010da5d7cd33af4d" +dependencies = [ + "anyhow", + "indexmap", + "log", + "protobuf", + "protobuf-support", + "tempfile", + "thiserror", + "which", +] + +[[package]] +name = "protobuf-support" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ca157fe12fc7ee2e315f2f735e27df41b3d97cdd70ea112824dac1ffb08ee1c" +dependencies = [ + "thiserror", +] + [[package]] name = "ptr_meta" version = "0.1.4" @@ -3996,7 +4056,7 @@ version = "0.17.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e27992fd6a8c29ee7eef28fc78349aa244134e10ad447ce3b9f0ac0ed0fa4ce0" dependencies = [ - "base64", + "base64 0.13.0", "byteorder", "bytes", "http", @@ -4079,7 +4139,7 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97acb4c28a254fd7a4aeec976c46a7fa404eac4d7c134b30c75144846d7cb8f" dependencies = [ - "base64", + "base64 0.13.0", "chunked_transfer", "flate2", "log", @@ -4273,6 +4333,8 @@ dependencies = [ "anyhow", "argh", "backup", + "base32", + "base64 0.3.1", "cbor", "clap 3.2.12", "ctaphid", @@ -4280,9 +4342,12 @@ dependencies = [ "hex 0.4.3", "hidapi", "log", + "protobuf", + "protobuf-codegen", "serde", "serde_json", "serde_repr", + "url", ] [[package]] @@ -4550,6 +4615,17 @@ dependencies = [ "webpki", ] +[[package]] +name = "which" +version = "4.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c831fbbee9e129a8cf93e7747a82da9d95ba8e16621cae60ec2cdc849bacb7b" +dependencies = [ + "either", + "libc", + "once_cell", +] + [[package]] name = "winapi" version = "0.3.9" diff --git a/apps/vault/libraries/backup/src/lib.rs b/apps/vault/libraries/backup/src/lib.rs index 8b23856dc..b2efb05b6 100644 --- a/apps/vault/libraries/backup/src/lib.rs +++ b/apps/vault/libraries/backup/src/lib.rs @@ -28,6 +28,21 @@ impl Display for CborConversionError { impl std::error::Error for CborConversionError {} +#[derive(Debug)] +pub enum HashFromStrError { + UnknownHash, +} + +impl Display for HashFromStrError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + HashFromStrError::UnknownHash => write!(f, "unknown hash type"), + } + } +} + +impl std::error::Error for HashFromStrError {} + #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub enum HashAlgorithms { #[default] @@ -62,6 +77,19 @@ impl TryFrom for HashAlgorithms { type Error = CborConversionError; } +impl std::str::FromStr for HashAlgorithms { + fn from_str(input: &str) -> Result { + match input { + "SHA1" => Ok(HashAlgorithms::SHA1), + "SHA256" => Ok(HashAlgorithms::SHA256), + "SHA512" => Ok(HashAlgorithms::SHA512), + _ => Err(HashFromStrError::UnknownHash), + } + } + + type Err = HashFromStrError; +} + #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct TotpEntry { pub step_seconds: u64, diff --git a/apps/vault/tools/vaultbackup-rs/Cargo.toml b/apps/vault/tools/vaultbackup-rs/Cargo.toml index 4a0840903..aed6e2ceb 100644 --- a/apps/vault/tools/vaultbackup-rs/Cargo.toml +++ b/apps/vault/tools/vaultbackup-rs/Cargo.toml @@ -19,3 +19,10 @@ anyhow = "1.0.58" log = "0.4.17" env_logger = "0.9.0" serde_repr = "0.1.9" +url = "2.2.2" +base64 = "0.3.0" +base32 = "0.4.0" +protobuf = "3.1.0" + +[build-dependencies] +protobuf-codegen = "3.1.0" diff --git a/apps/vault/tools/vaultbackup-rs/README.md b/apps/vault/tools/vaultbackup-rs/README.md index 3c37b8d4d..d8738fb81 100644 --- a/apps/vault/tools/vaultbackup-rs/README.md +++ b/apps/vault/tools/vaultbackup-rs/README.md @@ -77,9 +77,20 @@ The `subcommand` does this for you. Supported password managers: - Bitwarden: TOTP, logins + - Google Authenticator: TOTP Example: ```bash $ vaultbackup-rs format bitwarden your-bitwarden-export.json ``` + +For Google Authenticator, the input file is expected to contain +`otpauth://` or `otpauth-migration://` URIs, one per line; for example, +to import QR codes from the Google Authenticator app: + +```bash +$ zbarcam --raw | tee authenticator-export.txt +$ vaultbackup-rs format authenticator authenticator-export.txt +$ vaultbackup-rs restore totp authenticator_to_vault_totps.json +``` diff --git a/apps/vault/tools/vaultbackup-rs/build.rs b/apps/vault/tools/vaultbackup-rs/build.rs new file mode 100644 index 000000000..5efbb537c --- /dev/null +++ b/apps/vault/tools/vaultbackup-rs/build.rs @@ -0,0 +1,7 @@ +fn main() { + protobuf_codegen::Codegen::new() + .cargo_out_dir("protos") + .include("src") + .input("src/otpauth_migration.proto") + .run_from_script(); +} diff --git a/apps/vault/tools/vaultbackup-rs/src/authenticator.rs b/apps/vault/tools/vaultbackup-rs/src/authenticator.rs new file mode 100644 index 000000000..03e4be96d --- /dev/null +++ b/apps/vault/tools/vaultbackup-rs/src/authenticator.rs @@ -0,0 +1,106 @@ +use anyhow::{Result, anyhow, bail}; +use std::str::FromStr; +use protobuf::Message; + +include!(concat!(env!("OUT_DIR"), "/protos/mod.rs")); + +fn set_issuer(t: &mut backup::TotpEntry, issuer: String) { + let mut issuer = issuer; + issuer.push_str(":"); + if !t.name.starts_with(&issuer) { + issuer.push_str(&t.name); + t.name = issuer + } +} + +pub fn otpauth_to_entry(uri: &url::Url) -> Result { + let mut t = backup::TotpEntry::default(); + + t.algorithm = backup::HashAlgorithms::SHA1; + t.digit_count = 6; + t.step_seconds = 30; + t.name = uri.path()[1..].to_string(); + + for (k, v) in uri.query_pairs() { + match k.as_ref() { + "secret" => { + t.shared_secret = v.to_string(); + } + "issuer" => { + set_issuer(&mut t, v.to_string()); + } + "algorithm" => { + t.algorithm = backup::HashAlgorithms::from_str(&v)?; + } + "digits" => { + t.digit_count = v.parse::()?; + } + "period" => { + t.step_seconds = v.parse::()?; + } + k => { + bail!("unexpected parameter {} in URI: {}", k, uri) + } + } + } + + Ok(t) +} + +fn migration_payload_to_entry(param: otpauth_migration::migration_payload::OtpParameters) -> Result { + match param.type_.enum_value_or_default() { + otpauth_migration::migration_payload::OtpType::OTP_TYPE_TOTP => { + let mut t = backup::TotpEntry::default(); + t.step_seconds = 30; + match param.digits.enum_value_or_default() { + otpauth_migration::migration_payload::DigitCount::DIGIT_COUNT_UNSPECIFIED => + t.digit_count = 6, + otpauth_migration::migration_payload::DigitCount::DIGIT_COUNT_SIX => + t.digit_count = 6, + otpauth_migration::migration_payload::DigitCount::DIGIT_COUNT_EIGHT => + t.digit_count = 8, + } + match param.algorithm.enum_value_or_default() { + otpauth_migration::migration_payload::Algorithm::ALGORITHM_UNSPECIFIED => + t.algorithm = backup::HashAlgorithms::SHA1, + otpauth_migration::migration_payload::Algorithm::ALGORITHM_SHA1 => + t.algorithm = backup::HashAlgorithms::SHA1, + otpauth_migration::migration_payload::Algorithm::ALGORITHM_SHA256 => + t.algorithm = backup::HashAlgorithms::SHA256, + otpauth_migration::migration_payload::Algorithm::ALGORITHM_SHA512 => + t.algorithm = backup::HashAlgorithms::SHA512, + otpauth_migration::migration_payload::Algorithm::ALGORITHM_MD5 => + bail!("ALGORITHM_MD5 not supported") + } + t.name = param.name; + set_issuer(&mut t, param.issuer); + t.shared_secret = base32::encode(base32::Alphabet::RFC4648 { padding: false }, ¶m.secret); + Ok(t) + } + otpauth_migration::migration_payload::OtpType::OTP_TYPE_HOTP => + Err(anyhow!("OTP_TYPE_HOTP not supported")), + otpauth_migration::migration_payload::OtpType::OTP_TYPE_UNSPECIFIED => + Err(anyhow!("OTP_TYPE_UNSPECIFIED not supported")), + } +} + +pub fn otpauth_migration_to_entries(uri: &url::Url) -> Result, anyhow::Error> { + let mut entries = Vec::new(); + + for (k, v) in uri.query_pairs() { + match k.as_ref() { + "data" => { + let data = base64::decode(&v)?; + let payload = otpauth_migration::MigrationPayload::parse_from_bytes(&data)?; + for param in payload.otp_parameters { + entries.push(migration_payload_to_entry(param)?) + } + } + k => { + bail!("unexpected parameter {} in URI: {}", k, uri) + } + } + } + + Ok(entries) +} diff --git a/apps/vault/tools/vaultbackup-rs/src/main.rs b/apps/vault/tools/vaultbackup-rs/src/main.rs index d709478cd..446130c03 100644 --- a/apps/vault/tools/vaultbackup-rs/src/main.rs +++ b/apps/vault/tools/vaultbackup-rs/src/main.rs @@ -1,8 +1,12 @@ mod bitwarden; +mod authenticator; use anyhow::Result; use clap::Parser; use clap::Subcommand; use std::time::Instant; +use std::io::BufRead; + +include!(concat!(env!("OUT_DIR"), "/protos/mod.rs")); #[derive(Debug, Parser)] #[clap(name = "vaultbackup")] @@ -41,6 +45,7 @@ struct SubcommandFields { #[derive(Debug, PartialEq, clap::ValueEnum, Clone)] enum FormatTargets { Bitwarden, + Authenticator, } #[derive(Debug, PartialEq, clap::Args, Clone)] @@ -181,6 +186,33 @@ fn main() -> Result<()> { )?; } + Ok(()) + } + FormatTargets::Authenticator => { + let mut totps = backup::TotpEntries::default(); + + for uri in std::io::BufReader::new(f).lines() { + let uri = url::Url::parse(&uri?)?; + match (uri.scheme(), uri.host_str()) { + ("otpauth", Some("totp")) => { + totps.0.push(authenticator::otpauth_to_entry(&uri)?) + } + ("otpauth-migration", Some("offline")) => { + for t in authenticator::otpauth_migration_to_entries(&uri)? { + totps.0.push(t); + } + } + _ => { + log::error!("unsupported URI: {}", uri) + } + } + } + + std::fs::write( + "authenticator_to_vault_totps.json", + serde_json::ser::to_vec(&totps)?, + )?; + Ok(()) } } diff --git a/apps/vault/tools/vaultbackup-rs/src/otpauth_migration.proto b/apps/vault/tools/vaultbackup-rs/src/otpauth_migration.proto new file mode 100644 index 000000000..709a435de --- /dev/null +++ b/apps/vault/tools/vaultbackup-rs/src/otpauth_migration.proto @@ -0,0 +1,35 @@ +syntax = "proto3"; + +message MigrationPayload { + enum Algorithm { + ALGORITHM_UNSPECIFIED = 0; + ALGORITHM_SHA1 = 1; + ALGORITHM_SHA256 = 2; + ALGORITHM_SHA512 = 3; + ALGORITHM_MD5 = 4; + } + enum DigitCount { + DIGIT_COUNT_UNSPECIFIED = 0; + DIGIT_COUNT_SIX = 1; + DIGIT_COUNT_EIGHT = 2; + } + enum OtpType { + OTP_TYPE_UNSPECIFIED = 0; + OTP_TYPE_HOTP = 1; + OTP_TYPE_TOTP = 2; + } + message OtpParameters { + bytes secret = 1; + string name = 2; + string issuer = 3; + Algorithm algorithm = 4; + DigitCount digits = 5; + OtpType type = 6; + uint64 counter = 7; + } + repeated OtpParameters otp_parameters = 1; + int32 version = 2; + int32 batch_size = 3; + int32 batch_index = 4; + int32 batch_id = 5; +}