Merge branch 'main' of github.com:betrusted-io/xous-core into main

This commit is contained in:
bunnie 2022-08-14 00:02:04 +08:00
commit fca4848061
6 changed files with 249 additions and 8 deletions

12
Cargo.lock generated
View file

@ -3291,6 +3291,17 @@ dependencies = [
"serde",
]
[[package]]
name = "serde_repr"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fe39d9fbb0ebf5eb2c7cb7e2a47e4f462fad1379f1166b8ae49ad9eae89a7ca"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_with"
version = "1.14.0"
@ -4201,6 +4212,7 @@ dependencies = [
"log",
"serde",
"serde_json",
"serde_repr",
]
[[package]]

View file

@ -202,7 +202,7 @@ impl TryFrom<cbor::Value> for PasswordEntry {
type Error = CborConversionError;
}
#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Default)]
pub struct PasswordEntries(pub Vec<PasswordEntry>);
impl From<&PasswordEntries> for cbor::Value {

View file

@ -18,3 +18,4 @@ clap = { version = "3.2.12", features = ["derive"] }
anyhow = "1.0.58"
log = "0.4.17"
env_logger = "0.9.0"
serde_repr = "0.1.9"

View file

@ -44,6 +44,7 @@ OPTIONS:
SUBCOMMANDS:
backup Backup data from device
format Format a known password manager export for Vault
help Print this message or the help of the given subcommand(s)
restore Restore data to device
```
@ -64,3 +65,18 @@ vaultbackup-rs <ACTION> <TARGET> <PATH>
`PATH` specifies the path where `vaultbackup-rs` reads/writes data.
The output format is JSON.
## Importing other password manager's exports
`vaultbackup-rs` supports importing other password manager's export data in Vault, but to do so, you have to format it to Vault's format first.
The `subcommand` does this for you.
Supported password managers:
- Bitwarden: TOTP, logins
Example:
```bash
$ vaultbackup-rs format bitwarden your-bitwarden-export.json
```

View file

@ -0,0 +1,123 @@
use serde::{Deserialize, Serialize};
use serde_json;
use serde_repr::{Deserialize_repr, Serialize_repr};
#[derive(Serialize_repr, Debug, Deserialize_repr, PartialEq)]
#[repr(u8)]
pub enum EntryType {
Login = 1,
SecureNote = 2,
Card = 3,
Identity = 4,
}
#[derive(Serialize, Debug, Deserialize)]
pub struct Entry {
#[serde(rename = "type")]
pub entry_type: EntryType,
pub name: String,
pub login: Option<Login>,
pub notes: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Login {
pub username: Option<String>,
pub password: Option<String>,
pub totp: Option<String>,
}
#[derive(Debug)]
pub enum LoginSanificationError {
BadUsername,
BadPassword,
}
impl std::fmt::Display for LoginSanificationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::BadUsername => write!(f, "bad username format"),
Self::BadPassword => write!(f, "bad password format"),
}
}
}
impl std::error::Error for LoginSanificationError {}
impl Login {
pub fn sane(&self) -> Result<(), LoginSanificationError> {
if self.username.is_none() {
return Err(LoginSanificationError::BadUsername);
} else {
if self.username.as_ref().unwrap_or(&String::new()).is_empty() {
return Err(LoginSanificationError::BadUsername);
}
}
if self.password.is_none() {
return Err(LoginSanificationError::BadPassword);
} else {
if self.password.as_ref().unwrap_or(&String::new()).is_empty() {
return Err(LoginSanificationError::BadPassword);
}
}
Ok(())
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Items {
pub items: Vec<Entry>,
}
impl Items {
pub fn logins(&self) -> Vec<&Entry> {
let ret: Vec<&Entry> = self
.items
.iter()
.filter(|element| element.entry_type == EntryType::Login && element.login.is_some())
.collect();
ret
}
}
#[derive(Debug)]
pub enum FormatError {
SerdeError(serde_json::Error),
}
impl std::fmt::Display for FormatError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::SerdeError(err) => write!(f, "bitwarden deserialization error, {:?}", err),
}
}
}
impl std::error::Error for FormatError {}
impl From<serde_json::Error> for FormatError {
fn from(e: serde_json::Error) -> FormatError {
FormatError::SerdeError(e)
}
}
impl TryFrom<Vec<u8>> for Items {
type Error = FormatError;
fn try_from(data: Vec<u8>) -> Result<Items, Self::Error> {
let ret: Items = serde_json::from_slice(&data)?;
Ok(ret)
}
}
impl TryFrom<std::fs::File> for Items {
type Error = FormatError;
fn try_from(data: std::fs::File) -> Result<Items, Self::Error> {
let ret: Items = serde_json::from_reader(data)?;
Ok(ret)
}
}

View file

@ -1,8 +1,8 @@
use std::time::Instant;
mod bitwarden;
use anyhow::Result;
use clap::Parser;
use clap::Subcommand;
use std::time::Instant;
#[derive(Debug, Parser)]
#[clap(name = "vaultbackup")]
@ -38,6 +38,22 @@ struct SubcommandFields {
path: String,
}
#[derive(Debug, PartialEq, clap::ValueEnum, Clone)]
enum FormatTargets {
Bitwarden,
}
#[derive(Debug, PartialEq, clap::Args, Clone)]
struct FormatFields {
/// The target for which to run the action
#[clap(required = true, value_enum)]
target: FormatTargets,
/// The path to read input data from
#[clap(required = true, value_parser)]
path: String,
}
#[derive(Debug, Subcommand)]
enum Commands {
/// Backup data from device
@ -47,6 +63,10 @@ enum Commands {
/// Restore data to device
#[clap(arg_required_else_help = true)]
Restore(SubcommandFields),
/// Format a known password manager export for Vault.
#[clap(arg_required_else_help = true)]
Format(FormatFields),
}
#[derive(Debug)]
@ -69,10 +89,7 @@ impl std::error::Error for ProgramError {}
const PRECURSOR_VENDOR_ID: u16 = 0x1209;
const PRECURSOR_PRODUCT_ID: u16 = 0x3613;
fn main() -> Result<()> {
env_logger::init();
let wp = CLI::parse();
fn open_precursor() -> Result<ctaphid::Device> {
let ha = hidapi::HidApi::new()?;
let dl = ha.device_list();
@ -95,10 +112,81 @@ fn main() -> Result<()> {
device.vendor_command(ctaphid::command::VendorCommand::H74, &vec![])?;
log::debug!("sent session reset command");
Ok(device)
}
fn main() -> Result<()> {
env_logger::init();
let wp = CLI::parse();
let start = Instant::now();
match wp.command {
Commands::Format(params) => {
let f = std::fs::File::open(params.path)?;
match params.target {
FormatTargets::Bitwarden => {
let items = bitwarden::Items::try_from(f)?;
let items = items.logins();
let mut passwords = backup::PasswordEntries::default();
let mut totps = backup::TotpEntries::default();
for (idx, item) in items.into_iter().enumerate() {
let mut pw = backup::PasswordEntry::default();
let login = item.login.as_ref().unwrap();
match login.sane() {
Ok(()) => (),
Err(err) => {
log::error!("entry {} is invalid: {}", idx, err);
continue
}
}
pw.password = login.password.as_ref().unwrap().clone();
pw.username = login.username.as_ref().unwrap().clone();
pw.description = item.name.clone();
pw.notes = item.notes.as_ref().unwrap_or(&String::new()).clone();
passwords.0.push(pw);
if login.totp.is_some() {
let totp = login.totp.as_ref().unwrap();
let mut t = backup::TotpEntry::default();
t.name = item.name.clone();
t.algorithm = backup::HashAlgorithms::SHA256;
t.digit_count = 6;
t.step_seconds = 30;
t.shared_secret = totp
.strip_prefix("otpauth://totp/")
.unwrap_or(&totp)
.to_string();
totps.0.push(t);
}
}
std::fs::write(
"bitwarden_to_vault_passwords.json",
serde_json::ser::to_vec(&passwords)?,
)?;
if totps.0.len() > 0 {
std::fs::write(
"bitwarden_to_vault_totps.json",
serde_json::ser::to_vec(&totps)?,
)?;
}
Ok(())
}
}
}
Commands::Backup(params) => {
let device = open_precursor()?;
log::info!("receiving data...");
let bd = {
let mut data = vec![];
@ -145,13 +233,14 @@ fn main() -> Result<()> {
data
};
let json = unmarshal_backup_data( bd)?;
let json = unmarshal_backup_data(bd)?;
std::fs::write(params.path, json)?;
log::info!("done! elapsed: {:?}", start.elapsed());
Ok(())
}
Commands::Restore(params) => {
let device = open_precursor()?;
log::info!("sending data...");
let hbf = read_human_backup_file(&params.path, params.target)?;
let chunks: backup::Wires = backup::Wires::from(hbf);