Skip to main content

vcon_server/
key_wrap.rs

1//! The key-wrapping backend: what holds the root of the key hierarchy and
2//! wraps each tenant key under it. The registry asks it for the root, from
3//! which the server catalog key is derived, and has it wrap and unwrap
4//! tenant keys; it never sees a data key or a body.
5//!
6//! [`FileWrap`] is the backend every release so far has used: the master key
7//! from its file is the root, and a tenant key is wrapped under it with
8//! AES-256-GCM bound to the tenant id ([`envelope::wrap`] with
9//! [`Context::Tenant`]). What it writes is byte for byte what the code before
10//! this trait wrote, so data made by an older release opens unchanged.
11//!
12//! [`BackendWrap`] puts a key [`Backend`] (a KMS or an HSM, whose key never
13//! leaves it) at the root instead. The root is a random key the backend
14//! wraps, kept as a `key-wrap` blob ([`blob`]) where the registry is. Each
15//! tenant key is wrapped locally under a key-encryption key of its own,
16//! with the same AES-256-GCM binding to the tenant id, and the backend
17//! wraps that key-encryption key.
18
19use std::borrow::Borrow;
20use std::{fmt, io};
21
22use crate::envelope::{self, Context, Key, KeyError};
23use crate::ids::{KeyId, TenantId};
24
25pub mod blob;
26
27use blob::{Blob, BlobError, WrapRef};
28
29/// Why a backend could not wrap or unwrap a key.
30#[derive(Debug)]
31#[non_exhaustive]
32pub enum WrapError {
33    /// The wrapped key did not open under the backend's key for this
34    /// tenant: it was changed, cut short, moved from another tenant's row,
35    /// or made under another key. It does not say which part was wrong.
36    Damaged,
37    /// The key's memory could not be locked or kept out of core dumps.
38    Memory(io::Error),
39    /// The wrapped key is under another key than this backend's, so
40    /// nothing was asked of the backend: under the key backend key
41    /// `wrap_ref` names, or, when it is None, under the master key file.
42    Elsewhere {
43        /// The key backend's key the wrapped key is under, as
44        /// [`WrapRef`] writes it; None for the master key file.
45        wrap_ref: Option<String>,
46    },
47    /// A `key-wrap` blob could not be read, or the backend's wrapped key
48    /// does not fit in one.
49    Blob(BlobError),
50}
51
52/// The I/O error and the blob's error are given by `source`, not repeated
53/// here.
54impl fmt::Display for WrapError {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        match self {
57            WrapError::Damaged => f.write_str("a wrapped tenant key did not open"),
58            WrapError::Memory(_) => {
59                f.write_str("the key's memory could not be locked or kept out of core dumps")
60            }
61            WrapError::Elsewhere { wrap_ref: None } => f.write_str(
62                "the key is wrapped under the master key file, not under the key backend's key",
63            ),
64            WrapError::Elsewhere {
65                wrap_ref: Some(wrap_ref),
66            } => write!(
67                f,
68                "the key is wrapped under the key backend key {wrap_ref}, not under this \
69                 backend's key"
70            ),
71            WrapError::Blob(_) => f.write_str("a key-wrap blob could not be read or made"),
72        }
73    }
74}
75
76impl std::error::Error for WrapError {
77    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
78        match self {
79            WrapError::Memory(e) => Some(e),
80            WrapError::Blob(e) => Some(e),
81            WrapError::Damaged | WrapError::Elsewhere { .. } => None,
82        }
83    }
84}
85
86/// The one rule for what an envelope failure is to a backend: a page that
87/// cannot be locked is [`WrapError::Memory`], and every other failure means
88/// the wrapped key did not open (`envelope::unwrap` fails only with
89/// `Memory` and `Damaged`).
90fn from_key_error(e: KeyError) -> WrapError {
91    match e {
92        KeyError::Memory(e) => WrapError::Memory(e),
93        KeyError::Damaged | KeyError::Read(_) | KeyError::Refused(_) | KeyError::WrongSize => {
94            WrapError::Damaged
95        }
96    }
97}
98
99/// A tenant's key-encryption key as a key backend wrapped it: the
100/// backend's key as [`WrapRef`] writes it, and the `key-wrap` blob. A
101/// registry keeps both or neither.
102#[derive(Debug, Clone, PartialEq, Eq)]
103#[non_exhaustive]
104pub struct WrappedKek {
105    /// The key backend's key, as [`WrapRef`] writes it.
106    pub wrap_ref: String,
107    /// The `key-wrap` blob of the key-encryption key.
108    pub blob: Vec<u8>,
109}
110
111/// A tenant key as a backend wrapped it, as the registry keeps it: the
112/// wrapped key, and the key-encryption key it is wrapped under, as the key
113/// backend wrapped that; None when the wrapped key is under the master key
114/// file.
115#[derive(Debug, Clone, PartialEq, Eq)]
116#[non_exhaustive]
117pub struct Wrapped {
118    /// The tenant key, wrapped bound to its tenant.
119    pub key: Vec<u8>,
120    /// The key it is wrapped under, as the key backend wrapped that.
121    pub kek: Option<WrappedKek>,
122}
123
124/// A key-wrapping backend. Its methods are synchronous: the registry calls
125/// them from blocking threads.
126pub trait KeyWrap: Send + Sync + fmt::Debug {
127    /// The id of the key that wraps tenant keys. The registry counts each
128    /// wrap against it, and a key rotation records when its use began.
129    fn key_id(&self) -> KeyId;
130
131    /// The root of the hierarchy: the key the server catalog key is derived
132    /// from ([`envelope::catalog_key`]).
133    fn root(&self) -> &Key;
134
135    /// Wraps `key`, the tenant key of `tenant`, bound to that tenant.
136    ///
137    /// # Errors
138    ///
139    /// A [`WrapError`] when the backend cannot wrap it.
140    fn wrap(&self, tenant: TenantId, key: &Key) -> Result<Wrapped, WrapError>;
141
142    /// Unwraps a key [`KeyWrap::wrap`] made for `tenant`, into a locked page
143    /// of its own: `wrapped` under the key-encryption key `kek`, or under
144    /// the master key file when `kek` is None.
145    ///
146    /// # Errors
147    ///
148    /// [`WrapError::Elsewhere`] when the key is under another key than this
149    /// backend's, [`WrapError::Damaged`] when `wrapped` does not open for
150    /// `tenant` under the backend's key, [`WrapError::Blob`] when `kek`'s
151    /// blob cannot be read, and [`WrapError::Memory`] when the key's page
152    /// cannot be locked.
153    fn unwrap(
154        &self,
155        tenant: TenantId,
156        wrapped: &[u8],
157        kek: Option<&WrappedKek>,
158    ) -> Result<Key, WrapError>;
159}
160
161/// The master key file's backend: the master key is the root, and tenant
162/// keys are wrapped under it locally. It holds the key, or borrows it
163/// (`K` is `&Key`) for a rotation that has the key already. Debug shows
164/// only the key's id.
165#[derive(Debug)]
166pub struct FileWrap<K = Key> {
167    master: K,
168}
169
170impl FileWrap {
171    /// The backend over `master`, as loaded by [`Key::load_master`].
172    #[must_use]
173    pub fn new(master: Key) -> FileWrap {
174        FileWrap { master }
175    }
176}
177
178impl<'a> FileWrap<&'a Key> {
179    /// The backend over a master key the caller keeps.
180    #[must_use]
181    pub fn borrowing(master: &'a Key) -> FileWrap<&'a Key> {
182        FileWrap { master }
183    }
184}
185
186impl<K: Borrow<Key> + Send + Sync + fmt::Debug> KeyWrap for FileWrap<K> {
187    fn key_id(&self) -> KeyId {
188        self.master.borrow().id()
189    }
190
191    fn root(&self) -> &Key {
192        self.master.borrow()
193    }
194
195    fn wrap(&self, tenant: TenantId, key: &Key) -> Result<Wrapped, WrapError> {
196        Ok(Wrapped {
197            key: envelope::wrap(self.master.borrow(), &Context::Tenant { tenant }, key),
198            kek: None,
199        })
200    }
201
202    fn unwrap(
203        &self,
204        tenant: TenantId,
205        wrapped: &[u8],
206        kek: Option<&WrappedKek>,
207    ) -> Result<Key, WrapError> {
208        if let Some(kek) = kek {
209            return Err(WrapError::Elsewhere {
210                wrap_ref: Some(kek.wrap_ref.clone()),
211            });
212        }
213        envelope::unwrap(self.master.borrow(), &Context::Tenant { tenant }, wrapped)
214            .map_err(from_key_error)
215    }
216}
217
218/// What a key backend is asked to wrap or unwrap: the registry root, or
219/// the key-encryption key of one tenant. A backend that can bind a context
220/// to what it wraps binds this one, so a blob made for one does not open
221/// as another.
222#[derive(Debug, Clone, Copy, PartialEq, Eq)]
223#[non_exhaustive]
224pub enum WrapContext {
225    /// The root, from which the server catalog key is derived.
226    Registry,
227    /// The key-encryption key of this tenant's key.
228    Tenant(TenantId),
229}
230
231/// A key backend: a service or a device that holds a key which never
232/// leaves it, and wraps and unwraps keys under that key. Its methods are
233/// synchronous: the registry calls them from blocking threads.
234pub trait Backend: Send + Sync + fmt::Debug {
235    /// The backend's key, as every blob it makes records it.
236    fn reference(&self) -> WrapRef;
237
238    /// Wraps `key` for `ctx`, and gives the backend's ciphertext.
239    ///
240    /// # Errors
241    ///
242    /// A [`WrapError`] when the backend does not wrap it.
243    fn wrap(&self, ctx: WrapContext, key: &Key) -> Result<Vec<u8>, WrapError>;
244
245    /// Unwraps the ciphertext of `blob`, made for `ctx`, into a locked page
246    /// of its own.
247    ///
248    /// # Errors
249    ///
250    /// [`WrapError::Damaged`] when the ciphertext does not open for `ctx`,
251    /// and any other [`WrapError`] when the backend does not unwrap it.
252    fn unwrap(&self, ctx: WrapContext, blob: &Blob) -> Result<Key, WrapError>;
253}
254
255/// The backend over a key [`Backend`]: its root is a random key the
256/// backend wraps, and each tenant key is wrapped locally under a new
257/// key-encryption key of its own, bound to the tenant, which the backend
258/// wraps. Debug shows the backend, its key and the root's id only.
259#[derive(Debug)]
260pub struct BackendWrap<B> {
261    backend: B,
262    reference: WrapRef,
263    root: Key,
264}
265
266impl<B: Backend> BackendWrap<B> {
267    /// A new root, wrapped by `backend`: the backend over it, and the
268    /// root's `key-wrap` blob, to be kept where the registry's root is
269    /// read from.
270    ///
271    /// # Errors
272    ///
273    /// A [`WrapError`] when the root cannot be made or the backend does not
274    /// wrap it.
275    pub fn create(backend: B) -> Result<(BackendWrap<B>, Vec<u8>), WrapError> {
276        let root = Key::generate().map_err(from_key_error)?;
277        let reference = backend.reference();
278        let ciphertext = backend.wrap(WrapContext::Registry, &root)?;
279        let blob = Blob::new(reference.clone(), ciphertext).map_err(WrapError::Blob)?;
280        Ok((
281            BackendWrap {
282                backend,
283                reference,
284                root,
285            },
286            blob.encode(),
287        ))
288    }
289
290    /// The backend over the root `root_blob` holds, as [`BackendWrap::create`]
291    /// gave it; nothing is asked of the backend when the blob names another
292    /// key than its own.
293    ///
294    /// # Errors
295    ///
296    /// [`WrapError::Blob`] when the blob cannot be read,
297    /// [`WrapError::Elsewhere`] when it names another key, and any error
298    /// of the backend's unwrap.
299    pub fn open(backend: B, root_blob: &[u8]) -> Result<BackendWrap<B>, WrapError> {
300        let reference = backend.reference();
301        let blob = under(&reference, root_blob)?;
302        let root = backend.unwrap(WrapContext::Registry, &blob)?;
303        Ok(BackendWrap {
304            backend,
305            reference,
306            root,
307        })
308    }
309}
310
311/// The blob `bytes` holds, when it is under the key `reference` names; a
312/// blob under another key is [`WrapError::Elsewhere`], found before any
313/// backend is asked.
314fn under(reference: &WrapRef, bytes: &[u8]) -> Result<Blob, WrapError> {
315    let blob = Blob::decode(bytes).map_err(WrapError::Blob)?;
316    if blob.reference() != reference {
317        return Err(WrapError::Elsewhere {
318            wrap_ref: Some(blob.reference().to_string()),
319        });
320    }
321    Ok(blob)
322}
323
324impl<B: Backend> KeyWrap for BackendWrap<B> {
325    /// The root's id: each key-encryption key wraps one tenant key only, so
326    /// the count of wraps against the root bounds nothing else.
327    fn key_id(&self) -> KeyId {
328        self.root.id()
329    }
330
331    fn root(&self) -> &Key {
332        &self.root
333    }
334
335    fn wrap(&self, tenant: TenantId, key: &Key) -> Result<Wrapped, WrapError> {
336        let kek = Key::generate().map_err(from_key_error)?;
337        let wrapped = envelope::wrap(&kek, &Context::Tenant { tenant }, key);
338        let ciphertext = self.backend.wrap(WrapContext::Tenant(tenant), &kek)?;
339        let blob = Blob::new(self.reference.clone(), ciphertext).map_err(WrapError::Blob)?;
340        Ok(Wrapped {
341            key: wrapped,
342            kek: Some(WrappedKek {
343                wrap_ref: self.reference.to_string(),
344                blob: blob.encode(),
345            }),
346        })
347    }
348
349    fn unwrap(
350        &self,
351        tenant: TenantId,
352        wrapped: &[u8],
353        kek: Option<&WrappedKek>,
354    ) -> Result<Key, WrapError> {
355        let kek = kek.ok_or(WrapError::Elsewhere { wrap_ref: None })?;
356        let blob = under(&self.reference, &kek.blob)?;
357        // The row keeps the reference beside the blob, which names it too:
358        // two that disagree are a row no build writes.
359        if blob.reference().to_string() != kek.wrap_ref {
360            return Err(WrapError::Damaged);
361        }
362        let kek = self.backend.unwrap(WrapContext::Tenant(tenant), &blob)?;
363        envelope::unwrap(&kek, &Context::Tenant { tenant }, wrapped).map_err(from_key_error)
364    }
365}
366
367#[cfg(test)]
368pub(crate) mod testing;
369
370#[cfg(test)]
371mod tests;
372
373#[cfg(test)]
374mod backend_tests;