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
*/
//! Page-level AEAD encryption shared by the SQLite encrypted VFS and the
//! Turso encrypted IO backend.
//!
//! Every 4096-byte logical page is stored as
//! `[ciphertext(4096) | nonce(24) | tag(16)]`. XChaCha20-Poly1305 fills the
//! nonce slot; AES-256-GCM uses its first 12 bytes and leaves the rest zero.
//!
//! The associated data binds each page to its keyring, to the kind of file
//! it sits in and to its position:
//! `SHA-256(keyring header)(32) | role(1) | page_no(8)`. A page therefore
//! cannot be swapped with another page, copied out of a journal or WAL into
//! the database, or moved between keyrings, and editing the header breaks
//! every page.

use super::cipher::PageCipher;
use super::page_store::PageStore;
use aes_gcm::Aes256Gcm;
#[cfg(not(feature = "fips"))]
use chacha20poly1305::XChaCha20Poly1305;
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use std::io;
use std::iter;
use zeroize::Zeroizing;

pub(crate) const LOGICAL_PAGE_SIZE: usize = 4096;
const NONCE_SLOT: usize = 24;
const AES_NONCE_SIZE: usize = 12;
const TAG_SIZE: usize = 16;
/// Physical block on disk = [ciphertext(4096) | nonce(24) | tag(16)]
pub(crate) const PHYSICAL_PAGE_SIZE: usize = LOGICAL_PAGE_SIZE + NONCE_SLOT + TAG_SIZE; // 4136

/// Where a file's pages start and which role its pages are bound to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct PageFile {
    /// Bytes before the first page: the keyring header in the database file.
    base: u64,
    role: u8,
}

impl PageFile {
    /// The database file, whose pages follow the keyring header.
    pub(crate) const fn main(header_size: usize) -> Self {
        Self {
            base: header_size as u64,
            role: 0,
        }
    }

    /// A rollback journal or write-ahead log.
    pub(crate) const JOURNAL: Self = Self { base: 0, role: 1 };

    /// A temporary or transient database.
    pub(crate) const TEMP: Self = Self { base: 0, role: 2 };

    fn offset(&self, page_no: usize) -> u64 {
        self.base + (page_no * PHYSICAL_PAGE_SIZE) as u64
    }
}

enum Sealer {
    #[cfg(not(feature = "fips"))]
    XChaCha(Box<XChaCha20Poly1305>),
    Aes(Box<Aes256Gcm>),
}

/// The AEAD for one keyring together with the header digest its pages are
/// bound to.
pub(crate) struct ActiveCipher {
    sealer: Sealer,
    binding: [u8; 32],
}

impl ActiveCipher {
    /// `binding` is the SHA-256 digest of the keyring header.
    pub(crate) fn from_key(alg: PageCipher, key: &[u8; 32], binding: [u8; 32]) -> Self {
        let sealer = match alg {
            #[cfg(not(feature = "fips"))]
            PageCipher::XChaCha20Poly1305 => {
                Sealer::XChaCha(Box::new(XChaCha20Poly1305::new(key.into())))
            }
            PageCipher::Aes256Gcm => Sealer::Aes(Box::new(Aes256Gcm::new(key.into()))),
        };
        Self { sealer, binding }
    }

    fn aad(&self, file: PageFile, page_no: u64) -> [u8; 41] {
        let mut aad = [0u8; 41];
        aad[..32].copy_from_slice(&self.binding);
        aad[32] = file.role;
        aad[33..].copy_from_slice(&page_no.to_le_bytes());
        aad
    }

    fn encrypt_page(
        &self,
        file: PageFile,
        page_no: u64,
        plaintext: &[u8; LOGICAL_PAGE_SIZE],
    ) -> io::Result<[u8; PHYSICAL_PAGE_SIZE]> {
        let mut nonce = [0u8; NONCE_SLOT];
        let aad = self.aad(file, page_no);
        let payload = Payload {
            msg: plaintext.as_slice(),
            aad: &aad,
        };
        let ct = match &self.sealer {
            #[cfg(not(feature = "fips"))]
            Sealer::XChaCha(c) => {
                getrandom::fill(&mut nonce).map_err(|e| io::Error::other(e.to_string()))?;
                c.encrypt(&nonce.into(), payload)
            }
            Sealer::Aes(c) => {
                let short = &mut nonce[..AES_NONCE_SIZE];
                getrandom::fill(short).map_err(|e| io::Error::other(e.to_string()))?;
                let short: [u8; AES_NONCE_SIZE] = nonce[..AES_NONCE_SIZE]
                    .try_into()
                    .map_err(|_| io::Error::other("invalid nonce length"))?;
                c.encrypt(&short.into(), payload)
            }
        }
        .map_err(|_| io::Error::other("encryption failed"))?;

        let mut block = [0u8; PHYSICAL_PAGE_SIZE];
        block[..LOGICAL_PAGE_SIZE].copy_from_slice(&ct[..LOGICAL_PAGE_SIZE]);
        block[LOGICAL_PAGE_SIZE..LOGICAL_PAGE_SIZE + NONCE_SLOT].copy_from_slice(&nonce);
        block[LOGICAL_PAGE_SIZE + NONCE_SLOT..].copy_from_slice(&ct[LOGICAL_PAGE_SIZE..]);
        Ok(block)
    }

    fn decrypt_page(
        &self,
        file: PageFile,
        page_no: u64,
        block: &[u8; PHYSICAL_PAGE_SIZE],
    ) -> io::Result<[u8; LOGICAL_PAGE_SIZE]> {
        let nonce = &block[LOGICAL_PAGE_SIZE..LOGICAL_PAGE_SIZE + NONCE_SLOT];
        let mut ct_with_tag = Vec::with_capacity(LOGICAL_PAGE_SIZE + TAG_SIZE);
        ct_with_tag.extend_from_slice(&block[..LOGICAL_PAGE_SIZE]);
        ct_with_tag.extend_from_slice(&block[LOGICAL_PAGE_SIZE + NONCE_SLOT..]);
        let aad = self.aad(file, page_no);
        let payload = Payload {
            msg: &ct_with_tag,
            aad: &aad,
        };
        let failed = || io::Error::other("decryption failed");

        let pt = Zeroizing::new(match &self.sealer {
            #[cfg(not(feature = "fips"))]
            Sealer::XChaCha(c) => {
                let nonce: [u8; NONCE_SLOT] = nonce.try_into().map_err(|_| failed())?;
                c.decrypt(&nonce.into(), payload).map_err(|_| failed())?
            }
            Sealer::Aes(c) => {
                // The unused half of the slot is not authenticated, so insist
                // it is zero rather than let it carry anything.
                let (short, pad) = nonce.split_at(AES_NONCE_SIZE);
                if pad.iter().any(|&b| b != 0) {
                    return Err(failed());
                }
                let short: [u8; AES_NONCE_SIZE] = short.try_into().map_err(|_| failed())?;
                c.decrypt(&short.into(), payload).map_err(|_| failed())?
            }
        });

        let mut result = [0u8; LOGICAL_PAGE_SIZE];
        result.copy_from_slice(&pt);
        Ok(result)
    }

    /// Read and decrypt page `page_no`, or return zeros if it lies past the
    /// end of the file.
    fn load_page<S: PageStore>(
        &self,
        store: &mut S,
        file: PageFile,
        page_no: usize,
    ) -> io::Result<[u8; LOGICAL_PAGE_SIZE]> {
        let physical_offset = file.offset(page_no);
        if physical_offset >= store.len()? {
            return Ok([0u8; LOGICAL_PAGE_SIZE]);
        }
        let mut block = [0u8; PHYSICAL_PAGE_SIZE];
        store.read_exact_at(physical_offset, &mut block)?;
        self.decrypt_page(file, page_no as u64, &block)
    }

    /// Read `data.len()` logical bytes starting at logical `offset`.
    /// Bytes past the end of the file read as zeros.
    pub(crate) fn read_at<S: PageStore>(
        &self,
        store: &mut S,
        file: PageFile,
        offset: usize,
        data: &mut [u8],
    ) -> io::Result<usize> {
        for chunk in page_chunks(offset, data.len()) {
            let page = Zeroizing::new(self.load_page(store, file, chunk.page_no)?);
            data[chunk.buf_pos..chunk.buf_pos + chunk.len]
                .copy_from_slice(&page[chunk.intra..chunk.intra + chunk.len]);
        }
        Ok(data.len())
    }

    /// Write `data` at logical `offset`, re-encrypting every touched page.
    pub(crate) fn write_at<S: PageStore>(
        &self,
        store: &mut S,
        file: PageFile,
        offset: usize,
        data: &[u8],
    ) -> io::Result<usize> {
        for chunk in page_chunks(offset, data.len()) {
            let mut page = Zeroizing::new(if chunk.len == LOGICAL_PAGE_SIZE {
                [0u8; LOGICAL_PAGE_SIZE]
            } else {
                self.load_page(store, file, chunk.page_no)?
            });
            page[chunk.intra..chunk.intra + chunk.len]
                .copy_from_slice(&data[chunk.buf_pos..chunk.buf_pos + chunk.len]);

            let block = self.encrypt_page(file, chunk.page_no as u64, &page)?;
            store.write_all_at(file.offset(chunk.page_no), &block)?;
        }
        Ok(data.len())
    }
}

/// Logical size of an encrypted store: whole physical pages × logical page size.
pub(crate) fn logical_size<S: PageStore + ?Sized>(store: &S, file: PageFile) -> io::Result<u64> {
    let phys = store.len()?.saturating_sub(file.base);
    Ok((phys / PHYSICAL_PAGE_SIZE as u64) * LOGICAL_PAGE_SIZE as u64)
}

/// Truncate an encrypted store to hold `logical_size` bytes (rounded up to a page).
pub(crate) fn truncate<S: PageStore + ?Sized>(
    store: &mut S,
    file: PageFile,
    logical_size: usize,
) -> io::Result<()> {
    let num_pages = logical_size.div_ceil(LOGICAL_PAGE_SIZE);
    store.set_len(file.offset(num_pages))
}

/// The part of one logical page touched by a byte-range access.
struct PageChunk {
    page_no: usize,
    /// Offset within the page.
    intra: usize,
    /// Offset within the caller's buffer.
    buf_pos: usize,
    len: usize,
}

/// Split the logical range `[offset, offset + len)` into per-page chunks.
fn page_chunks(offset: usize, len: usize) -> impl Iterator<Item = PageChunk> {
    let mut buf_pos = 0usize;
    iter::from_fn(move || {
        if buf_pos >= len {
            return None;
        }
        let logical_off = offset + buf_pos;
        let intra = logical_off % LOGICAL_PAGE_SIZE;
        let take = (len - buf_pos).min(LOGICAL_PAGE_SIZE - intra);
        let chunk = PageChunk {
            page_no: logical_off / LOGICAL_PAGE_SIZE,
            intra,
            buf_pos,
            len: take,
        };
        buf_pos += take;
        Some(chunk)
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::fs::File;
    use std::path::PathBuf;

    fn temp_file(name: &str) -> (PathBuf, File) {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(name);
        let _ = fs::remove_file(&path);
        let f = File::options()
            .read(true)
            .write(true)
            .create(true)
            .truncate(true)
            .open(&path)
            .unwrap();
        (path, f)
    }

    fn ciphers() -> Vec<PageCipher> {
        vec![
            #[cfg(not(feature = "fips"))]
            PageCipher::XChaCha20Poly1305,
            PageCipher::Aes256Gcm,
        ]
    }

    #[test]
    fn page_chunks_split_on_boundaries() {
        let chunks: Vec<_> = page_chunks(4000, 5000)
            .map(|c| (c.page_no, c.intra, c.buf_pos, c.len))
            .collect();
        assert_eq!(
            chunks,
            vec![(0, 4000, 0, 96), (1, 0, 96, 4096), (2, 0, 4192, 808)]
        );
        assert_eq!(page_chunks(0, 0).count(), 0);
    }

    #[test]
    fn unaligned_round_trip_and_tamper_detection() {
        let main = PageFile::main(128);
        for alg in ciphers() {
            let (path, mut f) = temp_file(&format!(".test-page-cipher-{:?}", alg));
            let cipher = ActiveCipher::from_key(alg, &[7u8; 32], [1u8; 32]);
            let data: Vec<u8> = (0..9000u32).map(|i| i as u8).collect();

            assert_eq!(
                cipher.write_at(&mut f, main, 100, &data).unwrap(),
                data.len()
            );
            assert_eq!(
                logical_size(&f, main).unwrap(),
                3 * LOGICAL_PAGE_SIZE as u64
            );
            assert_eq!(
                f.metadata().unwrap().len(),
                128 + 3 * PHYSICAL_PAGE_SIZE as u64
            );

            let mut out = vec![0u8; data.len()];
            cipher.read_at(&mut f, main, 100, &mut out).unwrap();
            assert_eq!(out, data);

            // Past EOF reads as zeros.
            let mut tail = [1u8; 16];
            cipher
                .read_at(&mut f, main, 10 * LOGICAL_PAGE_SIZE, &mut tail)
                .unwrap();
            assert_eq!(tail, [0u8; 16]);

            // A wrong key, another keyring's header or another file role
            // cannot read the pages.
            let wrong_key = ActiveCipher::from_key(alg, &[8u8; 32], [1u8; 32]);
            assert!(wrong_key.read_at(&mut f, main, 0, &mut out).is_err());
            let wrong_header = ActiveCipher::from_key(alg, &[7u8; 32], [2u8; 32]);
            assert!(wrong_header.read_at(&mut f, main, 0, &mut out).is_err());
            let as_journal = PageFile {
                base: 128,
                role: PageFile::JOURNAL.role,
            };
            assert!(cipher.read_at(&mut f, as_journal, 0, &mut out).is_err());

            truncate(&mut f, main, 1).unwrap();
            assert_eq!(logical_size(&f, main).unwrap(), LOGICAL_PAGE_SIZE as u64);

            // Close the file before removing it, for Windows.
            f.sync_all().unwrap();
            #[allow(clippy::drop_non_drop)]
            drop(f);
            let _ = fs::remove_file(path);
        }
    }

    #[test]
    fn swapped_pages_are_rejected() {
        let main = PageFile::main(0);
        for alg in ciphers() {
            let (path, mut f) = temp_file(&format!(".test-page-swap-{:?}", alg));
            let cipher = ActiveCipher::from_key(alg, &[7u8; 32], [1u8; 32]);
            cipher
                .write_at(&mut f, main, 0, &[5u8; 2 * LOGICAL_PAGE_SIZE])
                .unwrap();
            let mut first = [0u8; PHYSICAL_PAGE_SIZE];
            f.read_exact_at(0, &mut first).unwrap();
            f.write_all_at(PHYSICAL_PAGE_SIZE as u64, &first).unwrap();
            let mut out = [0u8; LOGICAL_PAGE_SIZE];
            assert!(
                cipher
                    .read_at(&mut f, main, LOGICAL_PAGE_SIZE, &mut out)
                    .is_err()
            );

            f.sync_all().unwrap();
            #[allow(clippy::drop_non_drop)]
            drop(f);
            let _ = fs::remove_file(path);
        }
    }
}