cryptex 3.0.0

Store and retrieve secrets in OS keyrings, encrypted SQLite or Turso files, in-memory and browser keyrings, or under a YubiHSM 2 or Nitrokey 3
/*
    Copyright Michael Lodder. All Rights Reserved.
    SPDX-License-Identifier: Apache-2.0
*/
//! Read a keyring file written by cryptex 2.x's encrypted VFS or Turso
//! encrypted IO backend, so its secrets can move into a 3.0 keyring.
//!
//! 2.x stored every page as `[ciphertext(4096) | nonce(12) | tag(16)]` with
//! only the page number as associated data, ChaCha20-Poly1305 or AES-256-GCM
//! as the cipher, and a key from Argon2id over the caller's password and
//! salt. Nothing about the key was stored in the file, so the 2.x connection
//! string is needed again here.
//!
//! The old file is decrypted page by page straight into SQLite's memory and
//! read from there; no plaintext is written to disk.
//!
//! ```no_run
//! use cryptex::DynKeyRing;
//! use cryptex::encrypted_vfs::EncryptedVfsKeyring;
//! use cryptex::migrate::{V2ConnectionParams, migrate_v2};
//!
//! let old: V2ConnectionParams = "password=old salt=0okm9ijn8uhb7ygv".parse().unwrap();
//! let new = "password=new".parse().unwrap();
//! let mut keyring = EncryptedVfsKeyring::with_params(&new, None).unwrap();
//! let moved = migrate_v2("/home/me/.cryptex-2x/keyring.db3".as_ref(), &old, &mut keyring).unwrap();
//! println!("moved {} secrets", moved);
//! ```

use super::file_common::{self, CipherParam, derive_key_32, sibling_path};
use crate::error::KeyRingError;
use crate::{DynKeyRing, Result};
use aes_gcm::Aes256Gcm;
use chacha20poly1305::ChaCha20Poly1305;
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use rusqlite::Connection;
use std::fs::File;
use std::io::{self, Read};
use std::path::Path;
use zeroize::{Zeroize, Zeroizing};

const LOGICAL_PAGE_SIZE: usize = 4096;
const NONCE_SIZE: usize = 12;
const TAG_SIZE: usize = 16;
const PHYSICAL_PAGE_SIZE: usize = LOGICAL_PAGE_SIZE + NONCE_SIZE + TAG_SIZE;

/// The page ciphers cryptex 2.x offered.
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
pub enum V2Cipher {
    /// ChaCha20-Poly1305, the 2.x default
    #[default]
    ChaCha20Poly1305,
    /// AES-256-GCM
    Aes256Gcm,
}

impl Zeroize for V2Cipher {
    fn zeroize(&mut self) {
        *self = V2Cipher::default();
    }
}

impl CipherParam for V2Cipher {
    fn parse(value: &str) -> Result<Self> {
        match value {
            "chacha20poly1305" | "chacha20" => Ok(V2Cipher::ChaCha20Poly1305),
            "aes256gcm" | "aes" => Ok(V2Cipher::Aes256Gcm),
            other => Err(KeyRingError::GeneralError {
                msg: format!(
                    "unknown 2.x cipher '{}'; use chacha20poly1305 or aes256gcm",
                    other
                ),
            }),
        }
    }
}

/// The connection string a 2.x keyring was opened with, in the same syntax:
/// `password=... salt=... [memory=... threads=... parallel=...]
/// [cipher=chacha20poly1305|aes256gcm]`, or `key=<hex>`.
pub type V2ConnectionParams = file_common::ConnectionParams<V2Cipher>;

enum V2Sealer {
    ChaCha(Box<ChaCha20Poly1305>),
    Aes(Box<Aes256Gcm>),
}

/// Decrypts a 2.x page file into a byte stream, one page at a time.
struct V2Pages {
    file: File,
    sealer: V2Sealer,
    page_no: u64,
    pages: u64,
    page: Zeroizing<[u8; LOGICAL_PAGE_SIZE]>,
    pos: usize,
}

impl V2Pages {
    fn open(path: &Path, params: &V2ConnectionParams) -> Result<Self> {
        let key = derive_key_32(params)?;
        let sealer = match params.cipher {
            V2Cipher::ChaCha20Poly1305 => {
                V2Sealer::ChaCha(Box::new(ChaCha20Poly1305::new((&*key).into())))
            }
            V2Cipher::Aes256Gcm => V2Sealer::Aes(Box::new(Aes256Gcm::new((&*key).into()))),
        };
        let file = File::open(path)?;
        let pages = file.metadata()?.len() / PHYSICAL_PAGE_SIZE as u64;
        Ok(Self {
            file,
            sealer,
            page_no: 0,
            pages,
            page: Zeroizing::new([0u8; LOGICAL_PAGE_SIZE]),
            // Nothing decrypted yet, so the first read loads page 0.
            pos: LOGICAL_PAGE_SIZE,
        })
    }

    fn logical_len(&self) -> usize {
        self.pages as usize * LOGICAL_PAGE_SIZE
    }

    fn load_next(&mut self) -> io::Result<()> {
        let mut block = [0u8; PHYSICAL_PAGE_SIZE];
        self.file.read_exact(&mut block)?;
        let (ct, rest) = block.split_at(LOGICAL_PAGE_SIZE);
        let (nonce, tag) = rest.split_at(NONCE_SIZE);
        let mut ct_with_tag = Vec::with_capacity(LOGICAL_PAGE_SIZE + TAG_SIZE);
        ct_with_tag.extend_from_slice(ct);
        ct_with_tag.extend_from_slice(tag);
        let aad = self.page_no.to_le_bytes();
        let payload = Payload {
            msg: &ct_with_tag,
            aad: &aad,
        };
        let failed = || io::Error::other("wrong 2.x key or damaged keyring file");
        let nonce: [u8; NONCE_SIZE] = nonce.try_into().map_err(|_| failed())?;
        let pt = Zeroizing::new(
            match &self.sealer {
                V2Sealer::ChaCha(c) => c.decrypt(&nonce.into(), payload),
                V2Sealer::Aes(c) => c.decrypt(&nonce.into(), payload),
            }
            .map_err(|_| failed())?,
        );
        self.page.copy_from_slice(&pt);
        self.page_no += 1;
        self.pos = 0;
        Ok(())
    }
}

impl Read for V2Pages {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if self.pos == LOGICAL_PAGE_SIZE {
            if self.page_no == self.pages {
                return Ok(0);
            }
            self.load_next()?;
        }
        let n = buf.len().min(LOGICAL_PAGE_SIZE - self.pos);
        buf[..n].copy_from_slice(&self.page[self.pos..self.pos + n]);
        self.pos += n;
        Ok(n)
    }
}

/// Every secret in a 2.x keyring file, as `(id, secret)` pairs in id order.
///
/// `path` is the database file itself (`keyring.db3` for the encrypted VFS,
/// `keyring-turso.db3` for Turso encrypted IO). A Turso keyring whose `-wal`
/// file still holds data is refused, since those writes have not reached the
/// database file yet: open it once with 2.x and close it cleanly first.
pub fn read_v2(
    path: &Path,
    params: &V2ConnectionParams,
) -> Result<Vec<(String, Zeroizing<Vec<u8>>)>> {
    let wal = sibling_path(path, "-wal");
    if wal.metadata().map(|m| m.len() > 0).unwrap_or(false) {
        return Err(KeyRingError::GeneralError {
            msg: format!(
                "{} still holds unwritten changes; open the keyring once with cryptex 2.x \
                 and close it cleanly, then migrate",
                wal.display()
            ),
        });
    }
    let pages = V2Pages::open(path, params)?;
    let len = pages.logical_len();
    let mut conn = Connection::open_in_memory()?;
    conn.deserialize_read_exact("main", pages, len, true)
        .map_err(|_| KeyRingError::AccessDenied {
            msg: "wrong 2.x key or damaged keyring file".to_string(),
        })?;
    let mut stmt = conn.prepare("SELECT id, value FROM secrets ORDER BY id")?;
    let rows = stmt.query_map([], |row| {
        Ok((
            row.get::<_, String>(0)?,
            Zeroizing::new(row.get::<_, String>(1)?),
        ))
    })?;
    rows.map(|row| {
        let (id, hex_value) = row?;
        let value = hex::decode(hex_value.as_str()).map_err(|_| KeyRingError::GeneralError {
            msg: format!("secret {} is not stored as hex", id),
        })?;
        Ok((id, Zeroizing::new(value)))
    })
    .collect()
}

/// Copy every secret from the 2.x keyring file at `path` into `keyring`,
/// returning how many moved. The old file is not changed or removed.
pub fn migrate_v2<K: DynKeyRing + ?Sized>(
    path: &Path,
    params: &V2ConnectionParams,
    keyring: &mut K,
) -> Result<usize> {
    let secrets = read_v2(path, params)?;
    for (id, secret) in &secrets {
        keyring.set_secret(id, secret)?;
    }
    Ok(secrets.len())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::encrypted_vfs::{self, EncryptedVfsKeyring};
    use crate::file_common::test_support::TestDir;
    use std::fs;

    /// Write a database the way cryptex 2.x did: a plain SQLite image whose
    /// pages are sealed with the page number as associated data.
    fn write_v2(path: &Path, params: &V2ConnectionParams, secrets: &[(&str, &[u8])]) {
        let mut conn = Connection::open_in_memory().unwrap();
        conn.pragma_update(None, "page_size", LOGICAL_PAGE_SIZE as i64)
            .unwrap();
        conn.execute(
            "CREATE TABLE secrets (id TEXT UNIQUE NOT NULL, value TEXT NOT NULL)",
            [],
        )
        .unwrap();
        for (id, value) in secrets {
            conn.execute(
                "INSERT INTO secrets (id, value) VALUES (?1, ?2)",
                [*id, hex::encode(value).as_str()],
            )
            .unwrap();
        }
        let image = conn.serialize("main").unwrap();
        let key = derive_key_32(params).unwrap();
        let mut out = Vec::new();
        for (page_no, page) in image.chunks(LOGICAL_PAGE_SIZE).enumerate() {
            let nonce = [page_no as u8; NONCE_SIZE];
            let aad = (page_no as u64).to_le_bytes();
            let payload = Payload {
                msg: page,
                aad: &aad,
            };
            let ct = match params.cipher {
                V2Cipher::ChaCha20Poly1305 => {
                    ChaCha20Poly1305::new((&*key).into()).encrypt(&nonce.into(), payload)
                }
                V2Cipher::Aes256Gcm => {
                    Aes256Gcm::new((&*key).into()).encrypt(&nonce.into(), payload)
                }
            }
            .unwrap();
            out.extend_from_slice(&ct[..LOGICAL_PAGE_SIZE]);
            out.extend_from_slice(&nonce);
            out.extend_from_slice(&ct[LOGICAL_PAGE_SIZE..]);
        }
        fs::write(path, out).unwrap();
    }

    #[test]
    fn moves_secrets_from_both_2x_ciphers() {
        for cipher in ["chacha20poly1305", "aes256gcm"] {
            let dir = TestDir::new(&format!(".test-migrate-{cipher}"));
            fs::create_dir_all(&*dir).unwrap();
            let old_path = dir.join("old.db3");
            let old: V2ConnectionParams =
                format!("password=old salt=0okm9ijn8uhb7ygv cipher={cipher}")
                    .parse()
                    .unwrap();
            write_v2(&old_path, &old, &[("a", b"one"), ("b", b"two")]);

            let new: encrypted_vfs::ConnectionParams = "password=new".parse().unwrap();
            let new_dir = dir.join("new");
            let mut kr = EncryptedVfsKeyring::with_params(&new, Some(new_dir)).unwrap();
            assert_eq!(migrate_v2(&old_path, &old, &mut kr).unwrap(), 2);
            assert_eq!(kr.get_secret("a").unwrap().0, b"one");
            assert_eq!(kr.get_secret("b").unwrap().0, b"two");
        }
    }

    #[test]
    fn wrong_key_and_pending_wal_are_refused() {
        let dir = TestDir::new(".test-migrate-refusals");
        fs::create_dir_all(&*dir).unwrap();
        let old_path = dir.join("old.db3");
        let old: V2ConnectionParams = "password=old salt=0okm9ijn8uhb7ygv".parse().unwrap();
        write_v2(&old_path, &old, &[("a", b"one")]);

        let wrong: V2ConnectionParams = "password=nope salt=0okm9ijn8uhb7ygv".parse().unwrap();
        assert!(read_v2(&old_path, &wrong).is_err());

        fs::write(sibling_path(&old_path, "-wal"), b"pending").unwrap();
        assert!(read_v2(&old_path, &old).is_err());
    }
}