revault_lockbox_api 0.0.49

reVault lockbox API to create and manage lockboxes
Documentation
use chacha20poly1305::aead::{Aead, AeadInOut, KeyInit, Payload};
use chacha20poly1305::Tag;
use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce};
use getrandom::fill as getrandom;
use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};
use zeroize::Zeroize;

use crate::secret_vec::SecureVec;
use crate::{Error, Result};

pub(crate) fn seal_with_random_nonce(
    payload: &[u8],
    key: &[u8],
    aad: &[u8],
) -> Result<([u8; 12], Vec<u8>)> {
    let mut content_key = derive_content_key(key);
    let cipher = ChaCha20Poly1305::new(&Key::from(content_key));
    content_key.zeroize();
    let mut nonce = [0u8; 12];
    getrandom(&mut nonce).map_err(|err| Error::Io(err.to_string()))?;
    let ciphertext = cipher
        .encrypt(&Nonce::from(nonce), Payload { msg: payload, aad })
        .map_err(|_| Error::SecurityLimitExceeded("encryption failed".to_string()))?;
    Ok((nonce, ciphertext))
}

pub(crate) fn seal_in_place_with_random_nonce(
    payload: &mut [u8],
    key: &[u8],
    aad: &[u8],
) -> Result<([u8; 12], [u8; 16])> {
    let mut content_key = derive_content_key(key);
    let cipher = ChaCha20Poly1305::new(&Key::from(content_key));
    content_key.zeroize();
    let mut nonce = [0u8; 12];
    getrandom(&mut nonce).map_err(|err| Error::Io(err.to_string()))?;
    let tag = cipher
        .encrypt_inout_detached(&Nonce::from(nonce), aad, payload.into())
        .map_err(|_| Error::SecurityLimitExceeded("encryption failed".to_string()))?;
    Ok((nonce, tag.into()))
}

pub(crate) fn open_with_nonce(
    payload: &[u8],
    key: &[u8],
    nonce: &[u8],
    aad: &[u8],
) -> Result<Vec<u8>> {
    if nonce.len() != 12 {
        return Err(Error::CorruptRecord);
    }
    let mut content_key = derive_content_key(key);
    let cipher = ChaCha20Poly1305::new(&Key::from(content_key));
    content_key.zeroize();
    let nonce = Nonce::try_from(nonce).map_err(|_| Error::CorruptRecord)?;
    cipher
        .decrypt(&nonce, Payload { msg: payload, aad })
        .map_err(|_| Error::InvalidKey)
}

/// Authenticate/decrypt an already guarded owned page body without allocating
/// a second body. The caller must retain its wiping owner on every exit.
pub(crate) fn open_in_place_with_nonce(
    payload: &mut [u8],
    key: &[u8],
    nonce: &[u8],
    aad: &[u8],
) -> Result<usize> {
    if nonce.len() != 12 {
        return Err(Error::CorruptRecord);
    }
    // Aead::decrypt reports InvalidKey for a missing/truncated tag as well.
    let message_len = payload.len().checked_sub(16).ok_or(Error::InvalidKey)?;
    let mut content_key = derive_content_key(key);
    let cipher = ChaCha20Poly1305::new(&Key::from(content_key));
    content_key.zeroize();
    let nonce = Nonce::try_from(nonce).map_err(|_| Error::CorruptRecord)?;
    let (message, tag_bytes) = payload.split_at_mut(message_len);
    let tag = Tag::try_from(&*tag_bytes).map_err(|_| Error::CorruptRecord)?;
    cipher
        .decrypt_inout_detached(&nonce, aad, message.into(), &tag)
        .map_err(|_| Error::InvalidKey)?;
    Ok(message_len)
}

pub(crate) fn open_with_content_key_secure(
    payload: &mut SecureVec,
    content_key: &[u8; 32],
    nonce: &[u8],
    aad: &[u8],
) -> Result<()> {
    if nonce.len() != 12 {
        return Err(Error::CorruptRecord);
    }
    if payload.len() < 16 {
        return Err(Error::CorruptRecord);
    }
    let cipher = ChaCha20Poly1305::new(&Key::from(*content_key));
    let nonce = Nonce::try_from(nonce).map_err(|_| Error::CorruptRecord)?;
    payload.with_mut_bytes(|bytes| {
        let tag_offset = bytes.len() - 16;
        let (message, tag_bytes) = bytes.split_at_mut(tag_offset);
        let tag = Tag::try_from(&*tag_bytes).map_err(|_| Error::CorruptRecord)?;
        cipher
            .decrypt_inout_detached(&nonce, aad, message.into(), &tag)
            .map_err(|_| Error::InvalidKey)
    })??;
    payload.truncate(payload.len() - 16)?;
    Ok(())
}

pub(crate) fn seal_with_content_key_secure(
    payload: &mut SecureVec,
    content_key: &[u8; 32],
    aad: &[u8],
) -> Result<[u8; 12]> {
    let mut nonce = [0u8; 12];
    getrandom(&mut nonce).map_err(|err| Error::Io(err.to_string()))?;
    seal_secure_nonce(payload, content_key, aad, nonce)
}

// Test-only prepared-page reproduction. The caller must prove the complete
// plaintext and seal context unchanged before reusing a previously fresh nonce.
#[cfg(test)]
pub(crate) fn seal_prepared_content_secure(
    payload: &mut SecureVec,
    content_key: &[u8; 32],
    aad: &[u8],
    nonce: [u8; 12],
) -> Result<[u8; 12]> {
    seal_secure_nonce(payload, content_key, aad, nonce)
}
fn seal_secure_nonce(
    payload: &mut SecureVec,
    content_key: &[u8; 32],
    aad: &[u8],
    nonce: [u8; 12],
) -> Result<[u8; 12]> {
    let cipher = ChaCha20Poly1305::new(&Key::from(*content_key));
    let tag = payload.with_mut_bytes(|bytes| {
        cipher
            .encrypt_inout_detached(&Nonce::from(nonce), aad, bytes.into())
            .map_err(|_| Error::SecurityLimitExceeded("encryption failed".to_string()))
    })??;
    payload.try_extend_from_slice(&tag)?;
    Ok(nonce)
}

pub(crate) fn derive_page_content_key(key: &[u8]) -> [u8; 32] {
    derive_content_key(key)
}

pub(crate) fn strong_checksum(data: &[u8]) -> [u8; 32] {
    let mut hasher = strong_checksum_hasher(data.len() as u64);
    hasher.update(data);
    hasher.finalize().into()
}

/// Incremental checksum state with the same domain and total-length binding as
/// `strong_checksum`. The caller must hash exactly `length` bytes before finalizing.
pub(crate) fn strong_checksum_hasher(length: u64) -> Sha256 {
    let mut hasher = Sha256::new();
    hasher.update(b"lockbox-v1-public-checksum/sha256");
    hasher.update(length.to_le_bytes());
    hasher
}

pub(crate) fn metadata_auth_tag(key: &[u8], message: &[u8]) -> [u8; 24] {
    let mut mac = Hmac::<Sha256>::new_from_slice(key).expect("HMAC accepts arbitrary key lengths");
    mac.update(b"lockbox-v2-header-metadata-auth/hmac-sha256");
    mac.update(&(message.len() as u64).to_le_bytes());
    mac.update(message);
    let digest = mac.finalize().into_bytes();
    let mut tag = [0u8; 24];
    tag.copy_from_slice(&digest[..24]);
    tag
}

fn derive_content_key(key: &[u8]) -> [u8; 32] {
    let mut hasher = Sha256::new();
    hasher.update(b"lockbox-v1-content-key/chacha20poly1305");
    hasher.update((key.len() as u64).to_le_bytes());
    hasher.update(key);
    hasher.finalize().into()
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn owned_in_place_open_matches_allocating_authentication_and_errors() {
        let key = b"in-place test key";
        let aad = b"authenticated test header";
        let plaintext = vec![0x6a; 4097];
        let (nonce, ciphertext) = seal_with_random_nonce(&plaintext, key, aad).unwrap();
        let mut cases = vec![(
            ciphertext.clone(),
            key.to_vec(),
            nonce.to_vec(),
            aad.to_vec(),
        )];
        for index in [0, ciphertext.len() - 1] {
            let mut changed = ciphertext.clone();
            changed[index] ^= 1;
            cases.push((changed, key.to_vec(), nonce.to_vec(), aad.to_vec()));
        }
        cases.push((
            ciphertext.clone(),
            b"wrong key".to_vec(),
            nonce.to_vec(),
            aad.to_vec(),
        ));
        cases.push((
            ciphertext.clone(),
            key.to_vec(),
            nonce.to_vec(),
            b"wrong header".to_vec(),
        ));
        let mut wrong_nonce = nonce;
        wrong_nonce[0] ^= 1;
        cases.push((
            ciphertext.clone(),
            key.to_vec(),
            wrong_nonce.to_vec(),
            aad.to_vec(),
        ));
        for len in [0, 1, 15] {
            cases.push((
                ciphertext[..len].to_vec(),
                key.to_vec(),
                nonce.to_vec(),
                aad.to_vec(),
            ));
        }
        for len in [0, 11, 13] {
            cases.push((ciphertext.clone(), key.to_vec(), vec![0; len], aad.to_vec()));
        }
        for (index, (input, key, nonce, aad)) in cases.into_iter().enumerate() {
            let expected = open_with_nonce(&input, &key, &nonce, &aad);
            let mut guarded = crate::page_buffer::SensitiveBytes::new(input, true);
            let pointer = guarded.as_ptr();
            let capacity = guarded.capacity();
            let actual = open_in_place_with_nonce(&mut guarded, &key, &nonce, &aad);
            assert_eq!(guarded.as_ptr(), pointer);
            assert_eq!(guarded.capacity(), capacity);
            match (expected, actual) {
                (Ok(expected), Ok(len)) => {
                    assert_eq!(index, 0);
                    assert_eq!(&guarded[..len], expected);
                    assert_eq!(expected, plaintext);
                }
                (Err(expected), Err(actual)) => assert_eq!(
                    std::mem::discriminant(&expected),
                    std::mem::discriminant(&actual)
                ),
                _ => panic!("allocating and in-place authentication differ"),
            }
        }
    }

    #[test]
    fn seal_with_random_nonce_uses_unique_nonce() {
        let key = b"secret";
        let aad = b"test-aad";
        let (first_nonce, first) = seal_with_random_nonce(b"payload", key, aad).unwrap();
        let (second_nonce, second) = seal_with_random_nonce(b"payload", key, aad).unwrap();

        assert_ne!(first, second);
        assert_ne!(first_nonce, second_nonce);
        assert_eq!(
            open_with_nonce(&first, key, &first_nonce, aad).unwrap(),
            b"payload"
        );
        assert_eq!(
            open_with_nonce(&second, key, &second_nonce, aad).unwrap(),
            b"payload"
        );
    }
}