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;
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;
mod kdf {
pub(super) const ARGON2ID: u8 = 1;
pub(super) const PBKDF2_SHA256: u8 = 2;
pub(super) const RAW_KEY: u8 = 3;
}
#[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(),
}
}
pub(crate) struct PageHeader([u8; HEADER_SIZE]);
impl PageHeader {
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))
}
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)]
}
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(¶ms)?;
let binding: [u8; 32] = Sha256::digest(self.0).into();
Ok(ActiveCipher::from_key(
cipher_from_id(self.0[10])?,
&key,
binding,
))
}
}
#[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())
}
#[cfg(feature = "fips")]
fn new_costs(params: &ConnectionParams<PageCipher>) -> Result<[u32; 3]> {
Ok(params.kdf_costs())
}
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(¶ms("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(¶ms(&format!("key={}", "ab".repeat(32)))).unwrap();
assert!(raw.cipher(¶ms("password=pw")).is_err());
let pw = PageHeader::new(¶ms("password=pw")).unwrap();
assert!(
pw.cipher(¶ms(&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, ¶ms("password=pw")).is_err());
let foreign = dir.join("foreign");
fs::write(&foreign, [0u8; HEADER_SIZE]).unwrap();
assert!(open_or_create(&foreign, ¶ms("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());
}
}