Skip to main content

vcon_server/key_wrap/
blob.rs

1//! The `key-wrap` format: a key as a key backend wrapped it, with the
2//! backend's kind and the reference of the key that wrapped it, so a reader
3//! knows which backend and key opens it before it calls any backend.
4//!
5//! The layout, version 1 (every length big-endian):
6//!
7//! | Bytes | What |
8//! |---|---|
9//! | 1 | the format, [`FORMAT`] |
10//! | 1 | the backend's kind ([`BackendKind`]) |
11//! | 2 | the length of the key reference, 1 to [`MAX_KEY_REF`] |
12//! | that many | the key reference, printable ASCII with no space |
13//! | 4 | the length of the ciphertext, 1 to [`MAX_CIPHERTEXT`] |
14//! | that many | the ciphertext, as the backend returned it |
15//!
16//! Nothing follows the ciphertext. A reader refuses a format it does not
17//! know, and names it, before it reads anything else.
18
19use std::fmt;
20
21/// The version of the `key-wrap` format this build writes and reads.
22pub const FORMAT: u8 = 1;
23
24/// The longest key reference a blob holds, in bytes.
25pub const MAX_KEY_REF: usize = 1024;
26
27/// The longest ciphertext a blob holds, in bytes.
28pub const MAX_CIPHERTEXT: usize = 8192;
29
30/// The kind of key backend that wrapped a key. The file backend wraps
31/// nothing in this format (a tenant key under the master key file is an
32/// `envelope` blob), so it has no kind here.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34#[non_exhaustive]
35pub enum BackendKind {
36    /// AWS Key Management Service.
37    AwsKms,
38    /// Google Cloud Key Management.
39    GcpKms,
40    /// Azure Key Vault.
41    AzureKeyVault,
42    /// HashiCorp Vault's transit engine.
43    VaultTransit,
44    /// OpenBao's transit engine.
45    OpenbaoTransit,
46    /// A PKCS#11 token or hardware security module.
47    Pkcs11,
48}
49
50impl BackendKind {
51    /// Every kind, in the order of their bytes.
52    pub const ALL: [BackendKind; 6] = [
53        BackendKind::AwsKms,
54        BackendKind::GcpKms,
55        BackendKind::AzureKeyVault,
56        BackendKind::VaultTransit,
57        BackendKind::OpenbaoTransit,
58        BackendKind::Pkcs11,
59    ];
60
61    /// The kind's name, as the configuration and a key reference's text
62    /// give it.
63    #[must_use]
64    pub fn name(self) -> &'static str {
65        match self {
66            BackendKind::AwsKms => "aws-kms",
67            BackendKind::GcpKms => "gcp-kms",
68            BackendKind::AzureKeyVault => "azure-key-vault",
69            BackendKind::VaultTransit => "vault-transit",
70            BackendKind::OpenbaoTransit => "openbao-transit",
71            BackendKind::Pkcs11 => "pkcs11",
72        }
73    }
74
75    /// The kind named `name`, if there is one. Names are lowercase.
76    #[must_use]
77    pub fn from_name(name: &str) -> Option<BackendKind> {
78        BackendKind::ALL.into_iter().find(|k| k.name() == name)
79    }
80
81    /// The kind's byte in a blob: its place in [`BackendKind::ALL`], from 1.
82    fn byte(self) -> u8 {
83        match self {
84            BackendKind::AwsKms => 1,
85            BackendKind::GcpKms => 2,
86            BackendKind::AzureKeyVault => 3,
87            BackendKind::VaultTransit => 4,
88            BackendKind::OpenbaoTransit => 5,
89            BackendKind::Pkcs11 => 6,
90        }
91    }
92
93    /// The kind whose byte is `byte`, if there is one.
94    fn from_byte(byte: u8) -> Option<BackendKind> {
95        BackendKind::ALL.into_iter().find(|k| k.byte() == byte)
96    }
97}
98
99impl fmt::Display for BackendKind {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        f.write_str(self.name())
102    }
103}
104
105/// Why a `key-wrap` blob, or a part of one, was refused.
106#[derive(Debug, Clone, PartialEq, Eq)]
107#[non_exhaustive]
108pub enum BlobError {
109    /// The blob has no bytes.
110    Empty,
111    /// The blob's first byte is a format this build does not know.
112    UnknownFormat(u8),
113    /// The blob names a backend kind this build does not know.
114    UnknownKind(u8),
115    /// The blob ends before its last field does.
116    Truncated,
117    /// Bytes follow the blob's ciphertext.
118    TrailingBytes,
119    /// The key reference is empty, too long, or not printable ASCII.
120    KeyRef,
121    /// The ciphertext is empty or too long.
122    Ciphertext,
123    /// A key reference's text does not start with a known kind's name and
124    /// a colon.
125    RefText,
126}
127
128impl fmt::Display for BlobError {
129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130        match self {
131            BlobError::Empty => f.write_str("a key-wrap blob is empty"),
132            BlobError::UnknownFormat(n) => {
133                write!(f, "key-wrap format {n} is not one this build knows")
134            }
135            BlobError::UnknownKind(n) => write!(
136                f,
137                "a key-wrap blob names key backend {n}, which this build does not know"
138            ),
139            BlobError::Truncated => f.write_str("a key-wrap blob is cut short"),
140            BlobError::TrailingBytes => f.write_str("a key-wrap blob has bytes after its end"),
141            BlobError::KeyRef => write!(
142                f,
143                "a key reference is empty, longer than {MAX_KEY_REF} bytes, or not printable ASCII"
144            ),
145            BlobError::Ciphertext => write!(
146                f,
147                "a wrapped key's ciphertext is empty or longer than {MAX_CIPHERTEXT} bytes"
148            ),
149            BlobError::RefText => {
150                f.write_str("a key reference does not start with a key backend's name and a colon")
151            }
152        }
153    }
154}
155
156impl std::error::Error for BlobError {}
157
158/// The key a backend wrapped under: its backend's kind and the backend's
159/// own reference of the key and its version (an ARN, a key URL with its
160/// version, a transit mount and key, a token object's id).
161#[derive(Debug, Clone, PartialEq, Eq, Hash)]
162pub struct WrapRef {
163    kind: BackendKind,
164    key: String,
165}
166
167impl WrapRef {
168    /// The reference of `key` at a backend of `kind`.
169    ///
170    /// # Errors
171    ///
172    /// [`BlobError::KeyRef`] when `key` is empty, longer than
173    /// [`MAX_KEY_REF`] bytes, or holds a byte that is not printable ASCII
174    /// (a space included).
175    pub fn new(kind: BackendKind, key: impl Into<String>) -> Result<WrapRef, BlobError> {
176        let key = key.into();
177        if !valid_key(key.as_bytes()) {
178            return Err(BlobError::KeyRef);
179        }
180        Ok(WrapRef { kind, key })
181    }
182
183    /// The reference as [`WrapRef`]'s `Display` writes it: the kind's name,
184    /// a colon, the key.
185    ///
186    /// # Errors
187    ///
188    /// [`BlobError::RefText`] when the text does not start with a known
189    /// kind's name and a colon, and [`BlobError::KeyRef`] when the key after
190    /// it is not one [`WrapRef::new`] takes.
191    pub fn parse(text: &str) -> Result<WrapRef, BlobError> {
192        let (name, key) = text.split_once(':').ok_or(BlobError::RefText)?;
193        let kind = BackendKind::from_name(name).ok_or(BlobError::RefText)?;
194        WrapRef::new(kind, key)
195    }
196
197    /// The backend's kind.
198    #[must_use]
199    pub fn kind(&self) -> BackendKind {
200        self.kind
201    }
202
203    /// The backend's reference of the key.
204    #[must_use]
205    pub fn key(&self) -> &str {
206        &self.key
207    }
208}
209
210impl fmt::Display for WrapRef {
211    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212        write!(f, "{}:{}", self.kind, self.key)
213    }
214}
215
216/// A key as a backend wrapped it. Debug shows the reference and the
217/// ciphertext's length, never its bytes.
218#[derive(Clone, PartialEq, Eq)]
219pub struct Blob {
220    reference: WrapRef,
221    ciphertext: Vec<u8>,
222}
223
224impl Blob {
225    /// The blob of `ciphertext`, made by the key `reference` names.
226    ///
227    /// # Errors
228    ///
229    /// [`BlobError::Ciphertext`] when `ciphertext` is empty or longer than
230    /// [`MAX_CIPHERTEXT`] bytes.
231    pub fn new(reference: WrapRef, ciphertext: Vec<u8>) -> Result<Blob, BlobError> {
232        if !(1..=MAX_CIPHERTEXT).contains(&ciphertext.len()) {
233            return Err(BlobError::Ciphertext);
234        }
235        Ok(Blob {
236            reference,
237            ciphertext,
238        })
239    }
240
241    /// The blob's bytes, in the layout of format [`FORMAT`].
242    #[must_use]
243    pub fn encode(&self) -> Vec<u8> {
244        let key = self.reference.key.as_bytes();
245        // Both lengths fit: `WrapRef::new` and `Blob::new` hold them to
246        // their limits, which fit in two and four bytes.
247        let key_len = u16::try_from(key.len()).unwrap_or(u16::MAX);
248        let ct_len = u32::try_from(self.ciphertext.len()).unwrap_or(u32::MAX);
249        let mut out = Vec::with_capacity(8 + key.len() + self.ciphertext.len());
250        out.push(FORMAT);
251        out.push(self.reference.kind.byte());
252        out.extend_from_slice(&key_len.to_be_bytes());
253        out.extend_from_slice(key);
254        out.extend_from_slice(&ct_len.to_be_bytes());
255        out.extend_from_slice(&self.ciphertext);
256        out
257    }
258
259    /// The blob `bytes` hold.
260    ///
261    /// # Errors
262    ///
263    /// A [`BlobError`] naming the first thing wrong, the format first.
264    pub fn decode(bytes: &[u8]) -> Result<Blob, BlobError> {
265        let (&format, rest) = bytes.split_first().ok_or(BlobError::Empty)?;
266        if format != FORMAT {
267            return Err(BlobError::UnknownFormat(format));
268        }
269        let (&kind, rest) = rest.split_first().ok_or(BlobError::Truncated)?;
270        let kind = BackendKind::from_byte(kind).ok_or(BlobError::UnknownKind(kind))?;
271        let (key_len, rest) = take::<2>(rest)?;
272        let key_len = usize::from(u16::from_be_bytes(key_len));
273        if !(1..=MAX_KEY_REF).contains(&key_len) {
274            return Err(BlobError::KeyRef);
275        }
276        let (key, rest) = rest.split_at_checked(key_len).ok_or(BlobError::Truncated)?;
277        if !valid_key(key) {
278            return Err(BlobError::KeyRef);
279        }
280        let (ct_len, rest) = take::<4>(rest)?;
281        let ct_len = usize::try_from(u32::from_be_bytes(ct_len)).unwrap_or(usize::MAX);
282        if !(1..=MAX_CIPHERTEXT).contains(&ct_len) {
283            return Err(BlobError::Ciphertext);
284        }
285        let (ciphertext, rest) = rest.split_at_checked(ct_len).ok_or(BlobError::Truncated)?;
286        if !rest.is_empty() {
287            return Err(BlobError::TrailingBytes);
288        }
289        // `valid_key` took only ASCII bytes, so the key is UTF-8.
290        let key = String::from_utf8(key.to_vec()).map_err(|_| BlobError::KeyRef)?;
291        Ok(Blob {
292            reference: WrapRef { kind, key },
293            ciphertext: ciphertext.to_vec(),
294        })
295    }
296
297    /// The key that wrapped it.
298    #[must_use]
299    pub fn reference(&self) -> &WrapRef {
300        &self.reference
301    }
302
303    /// The backend's ciphertext.
304    #[must_use]
305    pub fn ciphertext(&self) -> &[u8] {
306        &self.ciphertext
307    }
308}
309
310impl fmt::Debug for Blob {
311    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312        f.debug_struct("Blob")
313            .field("reference", &self.reference)
314            .field("ciphertext_len", &self.ciphertext.len())
315            .finish()
316    }
317}
318
319/// Whether `key` is a key reference a blob may hold: 1 to [`MAX_KEY_REF`]
320/// bytes, each printable ASCII other than the space (`!` to `~`), so it is
321/// safe in a log line and in a TEXT column.
322fn valid_key(key: &[u8]) -> bool {
323    (1..=MAX_KEY_REF).contains(&key.len()) && key.iter().all(u8::is_ascii_graphic)
324}
325
326/// The first `N` bytes of `bytes` and the rest.
327fn take<const N: usize>(bytes: &[u8]) -> Result<([u8; N], &[u8]), BlobError> {
328    let (head, rest) = bytes.split_at_checked(N).ok_or(BlobError::Truncated)?;
329    let head = head.try_into().map_err(|_| BlobError::Truncated)?;
330    Ok((head, rest))
331}
332
333#[cfg(test)]
334mod tests;