garage44.eu/jeroen/pinnacle

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

.. /pfs/src/vault.rs

raw

//! A vault: a disk whose blocks are encrypted, opened with a passphrase,
//! on which an ordinary file system lives.
//!
//! Block 0 holds the vault's header: key slots, each the data key sealed
//! (ChaCha20-Poly1305) under a key of its own. A passphrase slot's key is
//! stretched from the passphrase by PBKDF2-HMAC-SHA-256 with its salt; a
//! wrong passphrase fails to open any seal. Other kinds of slot are kept
//! for later: a key a secure element releases after a fingerprint, say,
//! goes in a slot beside the passphrase's, and the data key, and so the
//! disk, stays as it is. Changing the passphrase seals the data key again
//! in its slot, and nothing else changes.
//!
//! The file system's block `n` is the disk's block `n + 1`, encrypted as a
//! whole with a wide-block cipher built the LIONESS way (Anderson and
//! Biham) from ChaCha20 and HMAC-SHA-256, the block number as its tweak:
//! its first 32 bytes and the rest are mixed into each other four times,
//! so a change to any byte changes every byte of what is stored. A stream
//! cipher keyed by the block number alone would not do: the file system
//! writes new contents to blocks it freed, and two contents under one
//! key stream give each other away. What the disk still shows is only
//! whether a block holds exactly what it held before at that place.
//! There is no integrity: a block changed on the disk reads as noise.

use crate::{BLOCK, Disk};
use pinnacle_crypto::aead::{chacha20, open as aead_open, seal};
use pinnacle_crypto::sha2::{hkdf, hmac, pbkdf2};

const MAGIC: &[u8; 8] = b"PVAULT02";
/// PBKDF2's rounds for the passphrase: about a second's work for a guess.
pub const ROUNDS: u32 = 100_000;
const HALF: usize = 32;
/// Key slots in the header, and where each is: a kind, a salt, the sealed
/// data key, its tag, and a passphrase slot's PBKDF2 rounds.
pub const SLOTS: usize = 8;
const SLOT: usize = 96;
const FIRST_SLOT: usize = 64;

/// What opens a key slot.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[repr(u8)]
pub enum Kind {
    Empty = 0,
    Passphrase = 1,
    /// A key held by hardware (a secure element, TrustZone), released
    /// after the device's own check (a fingerprint): its 32 bytes seal
    /// the data key, with no stretching.
    Hardware = 2,
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Error {
    /// The disk holds no vault.
    NotAVault,
    WrongPassphrase,
    /// No slot free for another way in.
    NoSlot,
}

/// The four round keys, from the data key.
struct Keys([[u8; 32]; 4]);

impl Keys {
    fn from(data_key: &[u8; 32]) -> Keys {
        let mut all = [0u8; 128];
        hkdf(b"pinnacle vault", data_key, b"lioness rounds", &mut all);
        let mut keys = [[0u8; 32]; 4];
        for (k, chunk) in keys.iter_mut().zip(all.chunks(32)) {
            k.copy_from_slice(chunk);
        }
        Keys(keys)
    }

    /// The rest of the block XOR a ChaCha20 stream keyed by the round key,
    /// the first half and the tweak.
    fn stream(&self, round: usize, block: &mut [u8; BLOCK], tweak: &[u8; 4]) {
        let (left, right) = block.split_at_mut(HALF);
        let key = hmac(&self.0[round], &[left, tweak]);
        chacha20(&key, 0, &[0; 12], right);
    }

    /// The first half XOR a keyed hash of the rest and the tweak.
    fn hash(&self, round: usize, block: &mut [u8; BLOCK], tweak: &[u8; 4]) {
        let (left, right) = block.split_at_mut(HALF);
        let mac = hmac(&self.0[round], &[right, tweak]);
        for (l, m) in left.iter_mut().zip(mac) {
            *l ^= m;
        }
    }

    fn encrypt(&self, block: &mut [u8; BLOCK], number: u32) {
        let tweak = number.to_le_bytes();
        self.stream(0, block, &tweak);
        self.hash(1, block, &tweak);
        self.stream(2, block, &tweak);
        self.hash(3, block, &tweak);
    }

    fn decrypt(&self, block: &mut [u8; BLOCK], number: u32) {
        let tweak = number.to_le_bytes();
        self.hash(3, block, &tweak);
        self.stream(2, block, &tweak);
        self.hash(1, block, &tweak);
        self.stream(0, block, &tweak);
    }
}

/// The key a passphrase slot is sealed under.
fn sealing_key(passphrase: &str, salt: &[u8; 16], rounds: u32) -> [u8; 32] {
    let mut key = [0u8; 32];
    pbkdf2(passphrase.as_bytes(), salt, rounds, &mut key);
    key
}

fn slot_at(header: &[u8; BLOCK], i: usize) -> &[u8] {
    &header[FIRST_SLOT + i * SLOT..FIRST_SLOT + (i + 1) * SLOT]
}

/// Seals `data_key` into slot `i` under `key`, of `kind`; a passphrase
/// slot also keeps the `rounds` its key was stretched by.
fn put_slot(
    header: &mut [u8; BLOCK],
    i: usize,
    kind: Kind,
    salt: &[u8; 16],
    rounds: u32,
    key: &[u8; 32],
    data_key: &[u8; 32],
) {
    let s = &mut header[FIRST_SLOT + i * SLOT..FIRST_SLOT + (i + 1) * SLOT];
    s.fill(0);
    s[0] = kind as u8;
    s[1..17].copy_from_slice(salt);
    let mut sealed = *data_key;
    // The slot's number goes into what the tag covers: a seal moved to
    // another slot does not open.
    let tag = seal(
        key,
        &[0; 12],
        &[MAGIC.as_slice(), &[i as u8]].concat(),
        &mut sealed,
    );
    s[17..49].copy_from_slice(&sealed);
    s[49..65].copy_from_slice(&tag);
    s[65..69].copy_from_slice(&rounds.to_le_bytes());
}

/// The data key, if `key` opens slot `i`.
fn open_slot(header: &[u8; BLOCK], i: usize, key: &[u8; 32]) -> Option<[u8; 32]> {
    let s = slot_at(header, i);
    let mut data_key: [u8; 32] = s[17..49].try_into().unwrap();
    let tag: [u8; 16] = s[49..65].try_into().unwrap();
    aead_open(
        key,
        &[0; 12],
        &[MAGIC.as_slice(), &[i as u8]].concat(),
        &mut data_key,
        &tag,
    )
    .then_some(data_key)
}

fn kind_of(header: &[u8; BLOCK], i: usize) -> u8 {
    slot_at(header, i)[0]
}

fn salt_of(header: &[u8; BLOCK], i: usize) -> [u8; 16] {
    slot_at(header, i)[1..17].try_into().unwrap()
}

fn rounds_of(header: &[u8; BLOCK], i: usize) -> u32 {
    u32::from_le_bytes(slot_at(header, i)[65..69].try_into().unwrap())
}

/// The data key and the slot a passphrase opens.
fn by_passphrase(header: &[u8; BLOCK], passphrase: &str) -> Option<([u8; 32], usize)> {
    (0..SLOTS)
        .filter(|&i| kind_of(header, i) == Kind::Passphrase as u8)
        .find_map(|i| {
            Some((
                open_slot(
                    header,
                    i,
                    &sealing_key(passphrase, &salt_of(header, i), rounds_of(header, i)),
                )?,
                i,
            ))
        })
}

/// Whether `disk` holds a vault.
pub fn is_vault<D: Disk>(disk: &mut D) -> bool {
    let mut block = crate::zeroed();
    disk.read(0, &mut block);
    &block[..8] == MAGIC
}

/// An open vault: a [`Disk`] of the blocks after the header, read and
/// written in the clear.
pub struct Vault<D: Disk> {
    disk: D,
    keys: Keys,
    data_key: [u8; 32],
}

impl<D: Disk> Vault<D> {
    /// Makes `disk` a new vault opened by `passphrase`, its data key
    /// `data_key`; `salt` and `data_key` are random, which the caller has
    /// (this crate has no source of randomness). What was on it is gone.
    pub fn create(disk: D, passphrase: &str, salt: [u8; 16], data_key: [u8; 32]) -> Vault<D> {
        Self::create_with_rounds(disk, passphrase, ROUNDS, salt, data_key)
    }

    /// As [`create`](Self::create), the passphrase stretched by `rounds`
    /// rounds: fewer for a test that must be quick, more as machines speed up.
    pub fn create_with_rounds(
        mut disk: D,
        passphrase: &str,
        rounds: u32,
        salt: [u8; 16],
        data_key: [u8; 32],
    ) -> Vault<D> {
        let mut header = crate::zeroed();
        header[..8].copy_from_slice(MAGIC);
        put_slot(
            &mut header,
            0,
            Kind::Passphrase,
            &salt,
            rounds,
            &sealing_key(passphrase, &salt, rounds),
            &data_key,
        );
        disk.write(0, &header);
        disk.flush();
        Vault {
            disk,
            keys: Keys::from(&data_key),
            data_key,
        }
    }

    pub fn open(mut disk: D, passphrase: &str) -> Result<Vault<D>, (D, Error)> {
        let header = self_header(&mut disk);
        if &header[..8] != MAGIC {
            return Err((disk, Error::NotAVault));
        }
        match by_passphrase(&header, passphrase) {
            Some((data_key, _)) => Ok(Vault {
                disk,
                keys: Keys::from(&data_key),
                data_key,
            }),
            None => Err((disk, Error::WrongPassphrase)),
        }
    }

    /// Opens with a key held by hardware ([`Kind::Hardware`]).
    pub fn open_with_key(mut disk: D, key: &[u8; 32]) -> Result<Vault<D>, (D, Error)> {
        let header = self_header(&mut disk);
        if &header[..8] != MAGIC {
            return Err((disk, Error::NotAVault));
        }
        let found = (0..SLOTS)
            .filter(|&i| kind_of(&header, i) == Kind::Hardware as u8)
            .find_map(|i| open_slot(&header, i, key));
        match found {
            Some(data_key) => Ok(Vault {
                disk,
                keys: Keys::from(&data_key),
                data_key,
            }),
            None => Err((disk, Error::WrongPassphrase)),
        }
    }

    /// Whether `passphrase` opens this vault: what a lock screen asks while
    /// the vault stays open.
    pub fn check_passphrase(&mut self, passphrase: &str) -> bool {
        by_passphrase(&self_header(&mut self.disk), passphrase).is_some()
    }

    /// Seals the data key under a new passphrase (`salt` fresh and
    /// random), in the slot the old one opens. Nothing else changes.
    pub fn change_passphrase(&mut self, old: &str, new: &str, salt: [u8; 16]) -> Result<(), Error> {
        let mut header = self_header(&mut self.disk);
        let (_, slot) = by_passphrase(&header, old).ok_or(Error::WrongPassphrase)?;
        put_slot(
            &mut header,
            slot,
            Kind::Passphrase,
            &salt,
            ROUNDS,
            &sealing_key(new, &salt, ROUNDS),
            &self.data_key,
        );
        self.disk.write(0, &header);
        self.disk.flush();
        Ok(())
    }

    /// Adds a way in: the data key sealed under a key hardware holds.
    /// Returns its slot.
    pub fn add_hardware_key(&mut self, key: &[u8; 32]) -> Result<usize, Error> {
        let mut header = self_header(&mut self.disk);
        let slot = (0..SLOTS)
            .find(|&i| kind_of(&header, i) == Kind::Empty as u8)
            .ok_or(Error::NoSlot)?;
        put_slot(
            &mut header,
            slot,
            Kind::Hardware,
            &[0; 16],
            0,
            key,
            &self.data_key,
        );
        self.disk.write(0, &header);
        self.disk.flush();
        Ok(slot)
    }

    /// The disk under it, as it is stored.
    pub fn into_inner(self) -> D {
        self.disk
    }
}

fn self_header<D: Disk>(disk: &mut D) -> alloc::boxed::Box<[u8; BLOCK]> {
    let mut header = crate::zeroed();
    disk.read(0, &mut header);
    header
}

impl<D: Disk> Disk for Vault<D> {
    fn read(&mut self, block: u32, into: &mut [u8; BLOCK]) {
        self.disk.read(block + 1, into);
        self.keys.decrypt(into, block);
    }

    fn write(&mut self, block: u32, from: &[u8; BLOCK]) {
        let mut sealed = crate::zeroed();
        sealed.copy_from_slice(from);
        self.keys.encrypt(&mut sealed, block);
        self.disk.write(block + 1, &sealed);
    }

    fn read_many(&mut self, blocks: &[u32], into: &mut [[u8; BLOCK]]) {
        let stored: alloc::vec::Vec<u32> = blocks.iter().map(|b| b + 1).collect();
        self.disk.read_many(&stored, into);
        for (block, data) in blocks.iter().zip(into) {
            self.keys.decrypt(data, *block);
        }
    }

    fn write_many(&mut self, blocks: &[u32], from: &[[u8; BLOCK]]) {
        let stored: alloc::vec::Vec<u32> = blocks.iter().map(|b| b + 1).collect();
        let mut sealed = from.to_vec();
        for (block, data) in blocks.iter().zip(&mut sealed) {
            self.keys.encrypt(data, *block);
        }
        self.disk.write_many(&stored, &sealed);
    }

    fn blocks(&self) -> u32 {
        self.disk.blocks() - 1
    }

    fn flush(&mut self) {
        self.disk.flush();
    }
}