use crate::crypto::{DerivedKey, NONCE_LEN, SALT_LEN, TAG_LEN};
use crate::error::{Error, Result};
use zeroize::Zeroizing;
pub const FORMAT_VERSION: u8 = 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Sealing {
pub format: u8,
pub kdf: &'static str,
pub memory_kib: u32,
pub passes: u32,
pub lanes: u32,
pub cipher: &'static str,
pub salt_len: usize,
pub nonce_len: usize,
pub tag_len: usize,
}
pub const SEALING: Sealing = Sealing {
format: FORMAT_VERSION,
kdf: "Argon2id",
memory_kib: crate::crypto::ARGON2_MEMORY_KIB,
passes: crate::crypto::ARGON2_ITERATIONS,
lanes: crate::crypto::ARGON2_PARALLELISM,
cipher: "XChaCha20-Poly1305",
salt_len: SALT_LEN,
nonce_len: NONCE_LEN,
tag_len: TAG_LEN,
};
const MIN_FILE_LEN: usize = SALT_LEN + NONCE_LEN + TAG_LEN + 1;
pub fn encode(password: &[u8], database: &[u8]) -> Result<Vec<u8>> {
let salt = crate::crypto::random_bytes::<SALT_LEN>()?;
let key = DerivedKey::derive(password, &salt)?;
seal_under(&salt, &key, database)
}
pub fn seal_under(salt: &[u8; SALT_LEN], key: &DerivedKey, database: &[u8]) -> Result<Vec<u8>> {
let mut plaintext = Zeroizing::new(Vec::with_capacity(database.len() + 1));
plaintext.push(FORMAT_VERSION);
plaintext.extend_from_slice(database);
let (nonce, ciphertext) = key.seal(&plaintext)?;
let mut file = Vec::with_capacity(SALT_LEN + NONCE_LEN + ciphertext.len());
file.extend_from_slice(salt);
file.extend_from_slice(&nonce);
file.extend_from_slice(&ciphertext);
Ok(file)
}
pub fn salt_of(file: &[u8]) -> Result<[u8; SALT_LEN]> {
if file.len() < MIN_FILE_LEN {
return Err(Error::TooSmall);
}
let mut salt = [0u8; SALT_LEN];
salt.copy_from_slice(&file[..SALT_LEN]);
Ok(salt)
}
pub fn decode(password: &[u8], file: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
let salt = salt_of(file)?;
let key = DerivedKey::derive(password, &salt)?;
open_under(&key, file)
}
pub fn open_under(key: &DerivedKey, file: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
if file.len() < MIN_FILE_LEN {
return Err(Error::TooSmall);
}
let mut nonce = [0u8; NONCE_LEN];
nonce.copy_from_slice(&file[SALT_LEN..SALT_LEN + NONCE_LEN]);
let ciphertext = &file[SALT_LEN + NONCE_LEN..];
let plaintext = key.open(&nonce, ciphertext)?;
match plaintext.first() {
Some(&FORMAT_VERSION) => {}
Some(&other) => return Err(Error::UnsupportedFormat(other)),
None => return Err(Error::WrongPasswordOrNotAVault),
}
Ok(Zeroizing::new(plaintext[1..].to_vec()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_description_names_what_the_key_is_derived_with() {
assert_eq!(
SEALING.kdf.to_lowercase(),
crate::crypto::ARGON2_ALGORITHM.as_str()
);
assert!(SEALING.cipher.starts_with("XChaCha20"));
assert_eq!(SEALING.nonce_len, 24);
assert_eq!(SEALING.format, FORMAT_VERSION);
}
#[test]
fn a_key_derived_elsewhere_makes_the_file_the_password_opens() {
let salt = crate::crypto::random_bytes::<SALT_LEN>().unwrap();
let key = DerivedKey::derive(b"pw", &salt).unwrap();
let file = seal_under(&salt, &key, b"SQLite format 3\0rest").unwrap();
assert_eq!(salt_of(&file).unwrap(), salt);
assert_eq!(
decode(b"pw", &file).unwrap().as_slice(),
b"SQLite format 3\0rest"
);
assert_eq!(
open_under(&key, &file).unwrap().as_slice(),
b"SQLite format 3\0rest"
);
}
#[test]
fn a_key_for_another_salt_opens_nothing() {
let file = encode(b"pw", b"payload").unwrap();
let other = DerivedKey::derive(b"pw", &[1u8; SALT_LEN]).unwrap();
assert!(matches!(
open_under(&other, &file),
Err(Error::WrongPasswordOrNotAVault)
));
}
#[test]
fn encode_decode_roundtrip() {
let file = encode(b"pw", b"SQLite format 3\0rest").unwrap();
let database = decode(b"pw", &file).unwrap();
assert_eq!(database.as_slice(), b"SQLite format 3\0rest");
}
#[test]
fn wrong_password_is_rejected() {
let file = encode(b"pw", b"payload").unwrap();
assert!(matches!(
decode(b"other", &file),
Err(Error::WrongPasswordOrNotAVault)
));
}
#[test]
fn truncated_file_is_rejected() {
let file = encode(b"pw", b"payload").unwrap();
assert!(matches!(
decode(b"pw", &file[..MIN_FILE_LEN - 1]),
Err(Error::TooSmall)
));
assert!(matches!(
decode(b"pw", &file[..file.len() - 1]),
Err(Error::WrongPasswordOrNotAVault)
));
}
#[test]
fn corrupted_file_is_rejected() {
let mut file = encode(b"pw", b"payload").unwrap();
let last = file.len() - 1;
file[last] ^= 0xff;
assert!(matches!(
decode(b"pw", &file),
Err(Error::WrongPasswordOrNotAVault)
));
}
#[test]
fn file_starts_with_no_recognizable_signature() {
let first = encode(b"pw", b"payload").unwrap();
let second = encode(b"pw", b"payload").unwrap();
assert_ne!(
first[..SALT_LEN + NONCE_LEN],
second[..SALT_LEN + NONCE_LEN]
);
assert_ne!(first, second);
}
#[test]
fn plaintext_database_bytes_are_not_visible_in_the_file() {
let database = b"SQLite format 3\0this must never appear in the open";
let file = encode(b"pw", database).unwrap();
assert!(
!file
.windows(database.len())
.any(|window| window == database.as_slice())
);
}
}