sefy-core 0.20.0

Core library for sefy: an inconspicuous encrypted secret store in a single file
Documentation
//! On-disk layout of a vault file.
//!
//! ```text
//! salt (16 B) ‖ nonce (24 B) ‖ ciphertext (SQLite bytes + Poly1305 tag)
//! ```
//!
//! There is no magic number, no header and no extension convention: salt and
//! nonce are uniformly random, and everything after them is indistinguishable
//! from random to anyone without the password. The format version lives inside
//! the ciphertext — a version byte in the clear would be a signature.
//!
//! The plaintext under the seal is `version (1 B) ‖ serialized SQLite database`.

use crate::crypto::{DerivedKey, NONCE_LEN, SALT_LEN, TAG_LEN};
use crate::error::{Error, Result};
use zeroize::Zeroizing;

/// Format version this build writes.
pub const FORMAT_VERSION: u8 = 1;

/// How a vault file is sealed, described rather than only done.
///
/// Whatever shows a person what protects their vault — `sefy status`, the
/// desktop app's passport of the file — reads it from here, and the numbers
/// are the ones the key derivation itself runs on. A front end that wrote
/// "Argon2id, 64 MiB" into its own text would be right until the day the
/// format moved, and then it would be the one place still saying so.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Sealing {
    /// Format version these parameters belong to.
    pub format: u8,
    /// The key derivation function the password is stretched with.
    pub kdf: &'static str,
    /// Memory it uses, in KiB.
    pub memory_kib: u32,
    /// Passes it makes over that memory.
    pub passes: u32,
    /// Lanes it computes in parallel.
    pub lanes: u32,
    /// The authenticated cipher the database is sealed with.
    pub cipher: &'static str,
    /// Bytes of salt at the front of the file.
    pub salt_len: usize,
    /// Bytes of nonce after the salt.
    pub nonce_len: usize,
    /// Bytes of authentication tag at the end of the ciphertext.
    pub tag_len: usize,
}

/// How this build seals a vault: format version 1.
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,
};

/// Smallest possible vault file: salt, nonce, tag and a version byte.
const MIN_FILE_LEN: usize = SALT_LEN + NONCE_LEN + TAG_LEN + 1;

/// Encrypts a serialized database into the bytes of a vault file.
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)
}

/// Encrypts a serialized database under a key already derived for `salt`.
///
/// For a key that came from whoever holds the password. The salt has to be a
/// fresh one, as [`encode`] samples: a salt kept from one write to the next
/// would be sixteen bytes every version of the file shares, in a format whose
/// point is to share none.
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)
}

/// The salt at the front of a vault file.
///
/// Public by construction: it is the first thing in the file, and all a key
/// for that file can be asked for by.
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)
}

/// Decrypts the bytes of a vault file back into a serialized database.
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)
}

/// Decrypts the bytes of a vault file under a key already derived for its salt.
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)),
        // An empty plaintext cannot come out of `encode`, but a valid tag over
        // zero bytes is still conceivable input.
        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() {
        // The numbers are the derivation's own constants; the names are text,
        // and text is what drifts. The variant the derivation runs is read off
        // the same constant it uses, so naming a different one fails here.
        assert_eq!(
            SEALING.kdf.to_lowercase(),
            crate::crypto::ARGON2_ALGORITHM.as_str()
        );
        // The X in XChaCha20 is the 24-byte nonce: a cipher described as plain
        // ChaCha20-Poly1305 would have a 12-byte one.
        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() {
        // Sealed under a key an agent derived, the file is one the password
        // alone opens: nothing about it says how it was written.
        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() {
        // Two vaults with identical content and password must share no prefix:
        // salt and nonce are freshly random every write.
        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())
        );
    }
}