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
*/
//! The header at the start of an encrypted VFS or Turso encrypted IO
//! keyring file.
//!
//! It records how the key is derived, so a keyring needs only its password
//! (or raw key) to reopen, and costs can rise on rekey without the caller
//! remembering old settings:
//!
//! ```text
//! magic(8) | version(1) | kdf(1) | cipher(1) | reserved(1) |
//! cost1(4) | cost2(4) | cost3(4) | salt(32) | file_id(16) | zero(56)
//! ```
//!
//! For Argon2id the costs are memory KiB, time and parallelism; for
//! PBKDF2-HMAC-SHA256 (`fips` builds) `cost1` is the iteration count. The
//! header is not encrypted. Its SHA-256 digest is bound into every page's
//! associated data (see [`page_cipher`](super::page_cipher)), so any edit to
//! it makes every page fail to decrypt.

use super::cipher::PageCipher;
use super::file_common::{
    ConnectionParams, check_stored_kdf_costs, derive_key_32, private_open_options,
};
use super::page_cipher::ActiveCipher;
use super::page_store::PageStore;
use crate::Result;
use crate::error::KeyRingError;
use sha2::{Digest, Sha256};
use std::path::Path;

/// Size of the header in bytes; the first page follows it.
pub(crate) const HEADER_SIZE: usize = 128;

const MAGIC: &[u8; 8] = b"CRYPTEXP";
const VERSION: u8 = 1;
const SALT_RANGE: std::ops::Range<usize> = 24..56;
const FILE_ID_RANGE: std::ops::Range<usize> = 56..72;

/// How the key is produced.
mod kdf {
    /// Argon2id over password + salt.
    pub(super) const ARGON2ID: u8 = 1;
    /// PBKDF2-HMAC-SHA256 over password + salt.
    pub(super) const PBKDF2_SHA256: u8 = 2;
    /// A caller-supplied 32-byte key.
    pub(super) const RAW_KEY: u8 = 3;
}

/// The password KDF this build creates and accepts.
#[cfg(not(feature = "fips"))]
const PASSWORD_KDF: u8 = kdf::ARGON2ID;
#[cfg(feature = "fips")]
const PASSWORD_KDF: u8 = kdf::PBKDF2_SHA256;

fn cipher_id(cipher: PageCipher) -> u8 {
    match cipher {
        #[cfg(not(feature = "fips"))]
        PageCipher::XChaCha20Poly1305 => 1,
        PageCipher::Aes256Gcm => 2,
    }
}

fn cipher_from_id(id: u8) -> Result<PageCipher> {
    match id {
        #[cfg(not(feature = "fips"))]
        1 => Ok(PageCipher::XChaCha20Poly1305),
        2 => Ok(PageCipher::Aes256Gcm),
        #[cfg(feature = "fips")]
        1 => Err(KeyRingError::GeneralError {
            msg: "this keyring uses XChaCha20-Poly1305, which a fips build cannot open".to_string(),
        }),
        other => Err(KeyRingError::GeneralError {
            msg: format!("unsupported cipher in keyring header: {}", other),
        }),
    }
}

fn invalid_header() -> KeyRingError {
    KeyRingError::GeneralError {
        msg: "not a cryptex keyring file, or its header is damaged".to_string(),
    }
}

/// A parsed keyring header.
pub(crate) struct PageHeader([u8; HEADER_SIZE]);

impl PageHeader {
    /// A fresh header for a new keyring: random salt and file id, the
    /// caller's cipher and costs. Costs below the defaults are refused.
    fn new(params: &ConnectionParams<PageCipher>) -> Result<Self> {
        let mut bytes = [0u8; HEADER_SIZE];
        bytes[..8].copy_from_slice(MAGIC);
        bytes[8] = VERSION;
        bytes[10] = cipher_id(params.cipher);
        let random = |out: &mut [u8]| {
            getrandom::fill(out).map_err(|e| KeyRingError::GeneralError {
                msg: format!("unable to generate a salt: {}", e),
            })
        };
        random(&mut bytes[SALT_RANGE])?;
        random(&mut bytes[FILE_ID_RANGE])?;
        if params.key.is_empty() {
            bytes[9] = PASSWORD_KDF;
            let costs = new_costs(params)?;
            for (i, cost) in costs.iter().enumerate() {
                bytes[12 + 4 * i..16 + 4 * i].copy_from_slice(&cost.to_le_bytes());
            }
        } else {
            bytes[9] = kdf::RAW_KEY;
        }
        Ok(Self(bytes))
    }

    /// Parse and sanity-check a stored header.
    fn parse(bytes: [u8; HEADER_SIZE]) -> Result<Self> {
        if &bytes[..8] != MAGIC {
            return Err(invalid_header());
        }
        if bytes[8] != VERSION {
            return Err(KeyRingError::GeneralError {
                msg: format!("unsupported keyring file version: {}", bytes[8]),
            });
        }
        cipher_from_id(bytes[10])?;
        let header = Self(bytes);
        match bytes[9] {
            kdf::RAW_KEY => {}
            id if id == PASSWORD_KDF => check_stored_kdf_costs(header.costs())?,
            kdf::ARGON2ID | kdf::PBKDF2_SHA256 => {
                return Err(KeyRingError::GeneralError {
                    msg: "this keyring was made by a build with a different password \
                          KDF (fips builds use PBKDF2, others Argon2id)"
                        .to_string(),
                });
            }
            _ => return Err(invalid_header()),
        }
        Ok(header)
    }

    fn cost(&self, i: usize) -> u32 {
        let mut b = [0u8; 4];
        b.copy_from_slice(&self.0[12 + 4 * i..16 + 4 * i]);
        u32::from_le_bytes(b)
    }

    fn costs(&self) -> [u32; 3] {
        [self.cost(0), self.cost(1), self.cost(2)]
    }

    /// Derive the key from `secret`'s password or raw key and this header's
    /// salt and costs, ready to read and write the keyring's pages.
    fn cipher(&self, secret: &ConnectionParams<PageCipher>) -> Result<ActiveCipher> {
        let raw = self.0[9] == kdf::RAW_KEY;
        if raw == secret.key.is_empty() {
            return Err(KeyRingError::AccessDenied {
                msg: if raw {
                    "this keyring was made with a raw key; open it with key="
                } else {
                    "this keyring was made with a password; open it with password="
                }
                .to_string(),
            });
        }
        let mut params = ConnectionParams::<PageCipher>::default();
        params.key.clone_from(&secret.key);
        params.password.clone_from(&secret.password);
        params.salt = self.0[SALT_RANGE].to_vec();
        params.set_kdf_costs(self.costs());
        let key = derive_key_32(&params)?;
        let binding: [u8; 32] = Sha256::digest(self.0).into();
        Ok(ActiveCipher::from_key(
            cipher_from_id(self.0[10])?,
            &key,
            binding,
        ))
    }
}

/// The costs a new header stores, after refusing any below the defaults.
#[cfg(not(feature = "fips"))]
fn new_costs(params: &ConnectionParams<PageCipher>) -> Result<[u32; 3]> {
    use argon2::Params;
    if params.memory < Params::DEFAULT_M_COST
        || params.threads < Params::DEFAULT_T_COST
        || params.parallel < Params::DEFAULT_P_COST
    {
        return Err(KeyRingError::GeneralError {
            msg: format!(
                "Argon2 costs must be at least memory={} threads={} parallel={}",
                Params::DEFAULT_M_COST,
                Params::DEFAULT_T_COST,
                Params::DEFAULT_P_COST
            ),
        });
    }
    Ok(params.kdf_costs())
}

/// The costs a new header stores. `derive_key` enforces the iteration floor.
#[cfg(feature = "fips")]
fn new_costs(params: &ConnectionParams<PageCipher>) -> Result<[u32; 3]> {
    Ok(params.kdf_costs())
}

/// Open the keyring file at `path`, writing a new header first if the file
/// is new or empty, and return the cipher for its pages.
///
/// An existing header decides the cipher and costs; `params` supplies only
/// the password or raw key. For a new file `params` also supplies the cipher
/// and costs, and the salt is generated, so `salt=` is not used.
pub(crate) fn open_or_create(
    path: &Path,
    params: &ConnectionParams<PageCipher>,
) -> Result<ActiveCipher> {
    let mut file = private_open_options()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(path)?;
    let header = if file.len()? == 0 {
        let header = PageHeader::new(params)?;
        file.write_all_at(0, &header.0)?;
        file.sync()?;
        header
    } else {
        let mut bytes = [0u8; HEADER_SIZE];
        if file.len()? < HEADER_SIZE as u64 {
            return Err(invalid_header());
        }
        file.read_exact_at(0, &mut bytes)?;
        PageHeader::parse(bytes)?
    };
    header.cipher(params)
}

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

    fn params(s: &str) -> ConnectionParams<PageCipher> {
        s.parse().unwrap()
    }

    #[test]
    fn new_headers_differ_and_round_trip() {
        let p = params("password=pw");
        let a = PageHeader::new(&p).unwrap();
        let b = PageHeader::new(&p).unwrap();
        assert_ne!(a.0[SALT_RANGE], b.0[SALT_RANGE]);
        assert_ne!(a.0[FILE_ID_RANGE], b.0[FILE_ID_RANGE]);
        let parsed = PageHeader::parse(a.0).unwrap();
        assert_eq!(parsed.0, a.0);
    }

    #[test]
    fn damaged_headers_are_rejected() {
        let good = PageHeader::new(&params("password=pw")).unwrap().0;
        for (at, value) in [(0, b'X'), (8, 9), (9, 0), (10, 0)] {
            let mut bytes = good;
            bytes[at] = value;
            assert!(PageHeader::parse(bytes).is_err(), "byte {at} = {value}");
        }
        let mut huge = good;
        huge[12..16].copy_from_slice(&u32::MAX.to_le_bytes());
        assert!(PageHeader::parse(huge).is_err());
    }

    #[test]
    fn raw_key_and_password_are_not_interchangeable() {
        let raw = PageHeader::new(&params(&format!("key={}", "ab".repeat(32)))).unwrap();
        assert!(raw.cipher(&params("password=pw")).is_err());
        let pw = PageHeader::new(&params("password=pw")).unwrap();
        assert!(
            pw.cipher(&params(&format!("key={}", "ab".repeat(32))))
                .is_err()
        );
    }

    #[test]
    fn short_or_foreign_files_are_rejected() {
        let dir = TestDir::new(".test-page-header-files");
        fs::create_dir_all(&*dir).unwrap();
        let short = dir.join("short");
        fs::write(&short, b"CRYPTEXP").unwrap();
        assert!(open_or_create(&short, &params("password=pw")).is_err());
        let foreign = dir.join("foreign");
        fs::write(&foreign, [0u8; HEADER_SIZE]).unwrap();
        assert!(open_or_create(&foreign, &params("password=pw")).is_err());
    }

    #[cfg(not(feature = "fips"))]
    #[test]
    fn weak_costs_are_refused_for_new_keyrings() {
        let mut p = params("password=pw");
        p.memory(8);
        assert!(PageHeader::new(&p).is_err());
    }
}