Skip to main content

vcon_server/envelope/
column.rs

1//! The codec of the PostgreSQL catalog's sensitive columns. A stored
2//! value is sealed under a key of its own, bound to the tenant, table,
3//! column and row, so a value copied to another row, column or tenant does
4//! not open; a value SQL must find or compare is kept as a MAC under
5//! another key derived from the same catalog key. Both keys are derived
6//! from the catalog key, so the same rotation that makes a local catalog
7//! unreadable on old copies does so for sealed columns and MACs.
8//!
9//! The local backend keeps SQLCipher and does not use this.
10
11use std::fmt;
12
13use aws_lc_rs::hmac;
14
15use super::locked::LockedPage;
16use super::{
17    FORMAT, KEY_LEN, Key, KeyError, LABEL, NONCE_LEN, TAG_LEN, gcm_open, gcm_seal, hkdf_sha256,
18};
19use crate::ids::TenantId;
20
21/// The HKDF info that makes the key sealed columns are derived from.
22const COLUMN_LABEL: &[u8] = b"vcon-server/v1 columns";
23
24/// The HKDF info that makes the key of every MAC.
25const INDEX_LABEL: &[u8] = b"vcon-server/v1 index";
26
27/// The kind byte in a sealed column's associated data: 1 and 2 are
28/// [`super::Context`]'s, 3 is a column value.
29const COLUMN_KIND: u8 = 3;
30
31/// The tenant field of a registry column: the registry belongs to no
32/// tenant, and no tenant id is all zeros (ids are random, 128 bits).
33pub const REGISTRY: TenantId = TenantId([0; 16]);
34
35/// How many bytes a sealed column value holds beyond its plaintext: the
36/// format byte, the nonce and the tag.
37pub const SEALED_COLUMN_OVERHEAD: usize = 1 + NONCE_LEN + TAG_LEN;
38
39/// The two keys derived from a catalog key at open, held in locked pages
40/// and never stored.
41pub struct ColumnKeys {
42    column: Key,
43    index: Key,
44}
45
46impl fmt::Debug for ColumnKeys {
47    /// Shows nothing of the keys, not even their ids.
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        f.debug_struct("ColumnKeys").finish_non_exhaustive()
50    }
51}
52
53/// Where a sealed value belongs. The tenant is [`REGISTRY`] for a registry
54/// column, the table and column are the SQL names, and the row key is what
55/// identifies the row within its tenant (such as a version id, or a uuid's
56/// MAC).
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub struct ColumnContext<'a> {
59    /// The tenant the row belongs to.
60    pub tenant: TenantId,
61    /// The table.
62    pub table: &'a str,
63    /// The column.
64    pub column: &'a str,
65    /// The row's key.
66    pub row: &'a [u8],
67}
68
69impl ColumnKeys {
70    /// The column and index keys of the catalog under `catalog`.
71    ///
72    /// # Errors
73    ///
74    /// [`KeyError::Memory`] if a key's page cannot be locked.
75    pub fn derive(catalog: &Key) -> Result<ColumnKeys, KeyError> {
76        Ok(ColumnKeys {
77            column: derive_key(catalog.bytes(), COLUMN_LABEL)?,
78            index: derive_key(catalog.bytes(), INDEX_LABEL)?,
79        })
80    }
81}
82
83/// Appends `bytes` after its length, four bytes big-endian, so that two
84/// different sequences of fields cannot give the same bytes.
85fn field(out: &mut Vec<u8>, bytes: &[u8]) {
86    let len = u32::try_from(bytes.len()).expect("a table, column or row key is under 4 GiB");
87    out.extend(len.to_be_bytes());
88    out.extend(bytes);
89}
90
91/// A key of 32 bytes made by HKDF-SHA256 of `parent` with no salt and the
92/// info `info`, in a locked page of its own.
93fn derive_key(parent: &[u8], info: &[u8]) -> Result<Key, KeyError> {
94    let mut page = LockedPage::new().map_err(KeyError::Memory)?;
95    hkdf_sha256(&[], parent, info, &mut page.bytes_mut()[..KEY_LEN]);
96    Ok(Key { page })
97}
98
99/// The HKDF info of a row's subkey: the table, the column and the row key,
100/// each after its length.
101fn subkey_info(ctx: &ColumnContext<'_>) -> Vec<u8> {
102    let mut info = Vec::new();
103    field(&mut info, ctx.table.as_bytes());
104    field(&mut info, ctx.column.as_bytes());
105    field(&mut info, ctx.row);
106    info
107}
108
109/// The associated data of a sealed value: the label, the blob's format
110/// byte, the kind byte, the tenant, then the table, the column and the row
111/// key, each after its length.
112fn associated_data(ctx: &ColumnContext<'_>, format: u8) -> Vec<u8> {
113    let mut ad = LABEL.to_vec();
114    ad.push(format);
115    ad.push(COLUMN_KIND);
116    ad.extend(ctx.tenant.0);
117    ad.extend(subkey_info(ctx));
118    ad
119}
120
121/// The subkey of one row's column, made in a locked page of its own that is
122/// zeroed when dropped.
123fn subkey(keys: &ColumnKeys, ctx: &ColumnContext<'_>) -> Result<Key, KeyError> {
124    derive_key(keys.column.bytes(), &subkey_info(ctx))
125}
126
127/// Seals `plaintext` for the place `ctx` names, with a random nonce. The
128/// blob is the format byte, the nonce, the ciphertext and the tag.
129///
130/// # Errors
131///
132/// [`KeyError::Memory`] if the subkey's page cannot be locked.
133///
134/// # Panics
135///
136/// Never: AWS-LC aborts the process rather than fail to give random bytes.
137pub fn seal_column(
138    keys: &ColumnKeys,
139    ctx: &ColumnContext<'_>,
140    plaintext: &[u8],
141) -> Result<Vec<u8>, KeyError> {
142    // Drawn whole from the system generator, as `seal` draws its nonce.
143    let nonce: [u8; NONCE_LEN] = aws_lc_rs::rand::generate(&aws_lc_rs::rand::SystemRandom::new())
144        .expect("AWS-LC aborts instead of failing")
145        .expose();
146    seal_column_with_nonce(keys, ctx, nonce, plaintext)
147}
148
149fn seal_column_with_nonce(
150    keys: &ColumnKeys,
151    ctx: &ColumnContext<'_>,
152    nonce: [u8; NONCE_LEN],
153    plaintext: &[u8],
154) -> Result<Vec<u8>, KeyError> {
155    let key = subkey(keys, ctx)?;
156    let mut blob = Vec::with_capacity(SEALED_COLUMN_OVERHEAD + plaintext.len());
157    blob.push(FORMAT);
158    blob.extend(nonce);
159    blob.extend(plaintext);
160    let ad = associated_data(ctx, FORMAT);
161    let tag = gcm_seal(key.bytes(), nonce, &ad, &mut blob[1 + NONCE_LEN..]);
162    blob.extend(tag);
163    Ok(blob)
164}
165
166/// Opens a value [`seal_column`] made for the same keys and context; any
167/// change to the blob, the keys or the context is an error, never partial
168/// plaintext.
169///
170/// # Errors
171///
172/// [`KeyError::Damaged`] for a blob that does not open, and
173/// [`KeyError::Memory`] if the subkey's page cannot be locked.
174pub fn open_column(
175    keys: &ColumnKeys,
176    ctx: &ColumnContext<'_>,
177    blob: &[u8],
178) -> Result<Vec<u8>, KeyError> {
179    let (&format, rest) = blob.split_first().ok_or(KeyError::Damaged)?;
180    let (nonce, sealed) = rest
181        .split_first_chunk::<NONCE_LEN>()
182        .ok_or(KeyError::Damaged)?;
183    if sealed.len() < TAG_LEN {
184        return Err(KeyError::Damaged);
185    }
186    let key = subkey(keys, ctx)?;
187    let mut text = sealed.to_vec();
188    let len = gcm_open(
189        key.bytes(),
190        *nonce,
191        &associated_data(ctx, format),
192        &mut text,
193    )
194    .map_err(|_| KeyError::Damaged)?;
195    text.truncate(len);
196    Ok(text)
197}
198
199/// Seals `key` as the column value of the place `ctx` names: a blob like
200/// [`seal_column`]'s, whose plaintext is the key.
201///
202/// # Errors
203///
204/// [`KeyError::Memory`] if the subkey's page cannot be locked.
205pub fn wrap_key(
206    keys: &ColumnKeys,
207    ctx: &ColumnContext<'_>,
208    key: &Key,
209) -> Result<Vec<u8>, KeyError> {
210    seal_column(keys, ctx, key.bytes())
211}
212
213/// Opens a key [`wrap_key`] made for the same keys and context. It is
214/// opened straight into the new key's own locked page, so the plain key
215/// is never anywhere else; on any error that page is dropped, and so
216/// zeroed.
217///
218/// # Errors
219///
220/// [`KeyError::Damaged`] for a blob that does not open under these keys
221/// and this context to exactly 32 bytes, and [`KeyError::Memory`] if a
222/// page cannot be locked.
223pub fn unwrap_key(
224    keys: &ColumnKeys,
225    ctx: &ColumnContext<'_>,
226    wrapped: &[u8],
227) -> Result<Key, KeyError> {
228    let (&format, rest) = wrapped.split_first().ok_or(KeyError::Damaged)?;
229    let (nonce, sealed) = rest
230        .split_first_chunk::<NONCE_LEN>()
231        .ok_or(KeyError::Damaged)?;
232    // Only a key's ciphertext and its tag fit: any other length is not a
233    // key, and is refused before anything is opened.
234    if sealed.len() != KEY_LEN + TAG_LEN {
235        return Err(KeyError::Damaged);
236    }
237    let subkey = subkey(keys, ctx)?;
238    let mut page = LockedPage::new().map_err(KeyError::Memory)?;
239    let text = &mut page.bytes_mut()[..KEY_LEN + TAG_LEN];
240    text.copy_from_slice(sealed);
241    match gcm_open(subkey.bytes(), *nonce, &associated_data(ctx, format), text) {
242        Ok(KEY_LEN) => Ok(Key { page }),
243        _ => Err(KeyError::Damaged),
244    }
245}
246
247/// HMAC-SHA256 of `value`'s fixed bytes under the index key: equal values
248/// give equal MACs, which SQL needs to find them, and which is all a MAC
249/// shows.
250#[must_use]
251pub fn mac(keys: &ColumnKeys, value: &[u8]) -> [u8; 32] {
252    hmac_sha256(keys.index.bytes(), value)
253}
254
255fn hmac_sha256(key: &[u8], value: &[u8]) -> [u8; 32] {
256    let key = hmac::Key::new(hmac::HMAC_SHA256, key);
257    hmac::sign(&key, value)
258        .as_ref()
259        .try_into()
260        .expect("HMAC-SHA256 is 32 bytes")
261}
262
263#[cfg(test)]
264mod key_tests;
265#[cfg(test)]
266mod tests;