use std::fmt;
use aws_lc_rs::hmac;
use super::locked::LockedPage;
use super::{
FORMAT, KEY_LEN, Key, KeyError, LABEL, NONCE_LEN, TAG_LEN, gcm_open, gcm_seal, hkdf_sha256,
};
use crate::ids::TenantId;
const COLUMN_LABEL: &[u8] = b"vcon-server/v1 columns";
const INDEX_LABEL: &[u8] = b"vcon-server/v1 index";
const COLUMN_KIND: u8 = 3;
pub const REGISTRY: TenantId = TenantId([0; 16]);
pub const SEALED_COLUMN_OVERHEAD: usize = 1 + NONCE_LEN + TAG_LEN;
pub struct ColumnKeys {
column: Key,
index: Key,
}
impl fmt::Debug for ColumnKeys {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ColumnKeys").finish_non_exhaustive()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ColumnContext<'a> {
pub tenant: TenantId,
pub table: &'a str,
pub column: &'a str,
pub row: &'a [u8],
}
impl ColumnKeys {
pub fn derive(catalog: &Key) -> Result<ColumnKeys, KeyError> {
Ok(ColumnKeys {
column: derive_key(catalog.bytes(), COLUMN_LABEL)?,
index: derive_key(catalog.bytes(), INDEX_LABEL)?,
})
}
}
fn field(out: &mut Vec<u8>, bytes: &[u8]) {
let len = u32::try_from(bytes.len()).expect("a table, column or row key is under 4 GiB");
out.extend(len.to_be_bytes());
out.extend(bytes);
}
fn derive_key(parent: &[u8], info: &[u8]) -> Result<Key, KeyError> {
let mut page = LockedPage::new().map_err(KeyError::Memory)?;
hkdf_sha256(&[], parent, info, &mut page.bytes_mut()[..KEY_LEN]);
Ok(Key { page })
}
fn subkey_info(ctx: &ColumnContext<'_>) -> Vec<u8> {
let mut info = Vec::new();
field(&mut info, ctx.table.as_bytes());
field(&mut info, ctx.column.as_bytes());
field(&mut info, ctx.row);
info
}
fn associated_data(ctx: &ColumnContext<'_>, format: u8) -> Vec<u8> {
let mut ad = LABEL.to_vec();
ad.push(format);
ad.push(COLUMN_KIND);
ad.extend(ctx.tenant.0);
ad.extend(subkey_info(ctx));
ad
}
fn subkey(keys: &ColumnKeys, ctx: &ColumnContext<'_>) -> Result<Key, KeyError> {
derive_key(keys.column.bytes(), &subkey_info(ctx))
}
pub fn seal_column(
keys: &ColumnKeys,
ctx: &ColumnContext<'_>,
plaintext: &[u8],
) -> Result<Vec<u8>, KeyError> {
let nonce: [u8; NONCE_LEN] = aws_lc_rs::rand::generate(&aws_lc_rs::rand::SystemRandom::new())
.expect("AWS-LC aborts instead of failing")
.expose();
seal_column_with_nonce(keys, ctx, nonce, plaintext)
}
fn seal_column_with_nonce(
keys: &ColumnKeys,
ctx: &ColumnContext<'_>,
nonce: [u8; NONCE_LEN],
plaintext: &[u8],
) -> Result<Vec<u8>, KeyError> {
let key = subkey(keys, ctx)?;
let mut blob = Vec::with_capacity(SEALED_COLUMN_OVERHEAD + plaintext.len());
blob.push(FORMAT);
blob.extend(nonce);
blob.extend(plaintext);
let ad = associated_data(ctx, FORMAT);
let tag = gcm_seal(key.bytes(), nonce, &ad, &mut blob[1 + NONCE_LEN..]);
blob.extend(tag);
Ok(blob)
}
pub fn open_column(
keys: &ColumnKeys,
ctx: &ColumnContext<'_>,
blob: &[u8],
) -> Result<Vec<u8>, KeyError> {
let (&format, rest) = blob.split_first().ok_or(KeyError::Damaged)?;
let (nonce, sealed) = rest
.split_first_chunk::<NONCE_LEN>()
.ok_or(KeyError::Damaged)?;
if sealed.len() < TAG_LEN {
return Err(KeyError::Damaged);
}
let key = subkey(keys, ctx)?;
let mut text = sealed.to_vec();
let len = gcm_open(
key.bytes(),
*nonce,
&associated_data(ctx, format),
&mut text,
)
.map_err(|_| KeyError::Damaged)?;
text.truncate(len);
Ok(text)
}
#[must_use]
pub fn mac(keys: &ColumnKeys, value: &[u8]) -> [u8; 32] {
hmac_sha256(keys.index.bytes(), value)
}
fn hmac_sha256(key: &[u8], value: &[u8]) -> [u8; 32] {
let key = hmac::Key::new(hmac::HMAC_SHA256, key);
hmac::sign(&key, value)
.as_ref()
.try_into()
.expect("HMAC-SHA256 is 32 bytes")
}
#[cfg(test)]
mod tests;