garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /sync/src/backup.rs

raw

//! A backup of the vault on a disk of its own, encrypted: at
//! `<disk>:/pinnacle/<device>/`,
//! - `key`: a random backup key, sealed under the vault's password
//!   stretched by PBKDF2 ([`seal_key`]);
//! - `index`: every file's path, size and hash, sealed under the key;
//! - `blobs/<name>`: each file's contents sealed under the key, named by a
//!   keyed hash of them ([`blob_name`]), so a file backed up already is not
//!   written again and the names say nothing of what is in them.

use crate::{Agreed, Entry, Hash, base_from_bytes, base_to_bytes, hash};
use alloc::collections::BTreeSet;
use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_crypto::aead::{open as aead_open, seal};
use pinnacle_crypto::sha2::{hmac, pbkdf2};

const MAGIC: &[u8; 8] = b"PBACKUP1";
/// As the vault's passphrase slot: about a second's work for a guess.
pub const ROUNDS: u32 = 100_000;

pub type Key = [u8; 32];

fn stretch(password: &str, salt: &[u8; 16], rounds: u32) -> Key {
    let mut k = [0u8; 32];
    pbkdf2(password.as_bytes(), salt, rounds, &mut k);
    k
}

/// The backup key, sealed under `password` (`salt` random).
pub fn seal_key(password: &str, salt: [u8; 16], rounds: u32, key: &Key) -> Vec<u8> {
    let mut sealed = *key;
    let tag = seal(&stretch(password, &salt, rounds), &[0; 12], MAGIC, &mut sealed);
    [&MAGIC[..], &salt, &rounds.to_le_bytes(), &sealed, &tag].concat()
}

/// The backup key, if `password` opens it.
pub fn open_key(password: &str, sealed: &[u8]) -> Option<Key> {
    if sealed.len() != 8 + 16 + 4 + 32 + 16 || &sealed[..8] != MAGIC {
        return None;
    }
    let salt: [u8; 16] = sealed[8..24].try_into().ok()?;
    let rounds = u32::from_le_bytes(sealed[24..28].try_into().ok()?);
    let mut key: Key = sealed[28..60].try_into().ok()?;
    let tag: [u8; 16] = sealed[60..76].try_into().ok()?;
    aead_open(&stretch(password, &salt, rounds), &[0; 12], MAGIC, &mut key, &tag).then_some(key)
}

/// Where a file's contents are kept: a keyed hash of them, 32 hex digits.
pub fn blob_name(key: &Key, contents: &Hash) -> String {
    hmac(key, &[b"blob", contents])[..16]
        .iter()
        .map(|b| alloc::format!("{b:02x}"))
        .collect()
}

fn nonce(key: &Key, contents: &Hash) -> [u8; 12] {
    hmac(key, &[b"nonce", contents])[..12].try_into().unwrap()
}

/// A file's contents as the backup keeps them.
pub fn seal_blob(key: &Key, data: &[u8]) -> Vec<u8> {
    let h = hash(data);
    let mut out = data.to_vec();
    let tag = seal(key, &nonce(key, &h), &h, &mut out);
    out.extend_from_slice(&tag);
    out
}

/// The contents back, if the blob is the one `contents` names, whole.
pub fn open_blob(key: &Key, contents: &Hash, blob: &[u8]) -> Option<Vec<u8>> {
    let (data, tag) = blob.split_at_checked(blob.len().checked_sub(16)?)?;
    let mut data = data.to_vec();
    let ok = aead_open(
        key,
        &nonce(key, contents),
        contents,
        &mut data,
        tag.try_into().ok()?,
    );
    (ok && hash(&data) == *contents).then_some(data)
}

/// The index, sealed: `nonce` random, as each backup writes a new one.
pub fn seal_index(key: &Key, nonce: [u8; 12], files: &[Agreed]) -> Vec<u8> {
    let mut body = base_to_bytes(files);
    let tag = seal(key, &nonce, b"index", &mut body);
    [&nonce[..], &body, &tag].concat()
}

pub fn open_index(key: &Key, sealed: &[u8]) -> Option<Vec<Agreed>> {
    if sealed.len() < 28 {
        return None;
    }
    let nonce: [u8; 12] = sealed[..12].try_into().ok()?;
    let (body, tag) = sealed[12..].split_at(sealed.len() - 28);
    let mut body = body.to_vec();
    aead_open(key, &nonce, b"index", &mut body, tag.try_into().ok()?).then(|| base_from_bytes(&body))
}

/// What a backup writes: the files whose blob the disk does not hold
/// (`present`, the names in `blobs/`), and the blobs no file needs any more.
pub fn backup_plan<'a>(key: &Key, files: &'a [Entry], present: &[String]) -> (Vec<&'a Entry>, Vec<String>) {
    let have: BTreeSet<&str> = present.iter().map(String::as_str).collect();
    let needed: BTreeSet<String> = files.iter().map(|e| blob_name(key, &e.hash)).collect();
    let mut seen = BTreeSet::new();
    let write = files
        .iter()
        .filter(|e| {
            let name = blob_name(key, &e.hash);
            !have.contains(name.as_str()) && seen.insert(name)
        })
        .collect();
    let stale = present.iter().filter(|n| !needed.contains(*n)).cloned().collect();
    (write, stale)
}

/// What a restore writes: every file of the backup this device does not
/// hold as it is there.
pub fn restore_plan<'a>(index: &'a [Agreed], local: &[Entry]) -> Vec<&'a Agreed> {
    index
        .iter()
        .filter(|a| !local.iter().any(|e| e.path == a.path && e.hash == a.hash))
        .collect()
}

/// The index of `files`: what the backup holds.
pub fn index_of(files: &[Entry]) -> Vec<Agreed> {
    files
        .iter()
        .map(|e| Agreed {
            path: e.path.clone(),
            size: e.size,
            hash: e.hash,
        })
        .collect()
}