krab-crypt 0.2.2

AES-256-GCM encryption at rest for krabkube secrets with key rotation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
use std::fmt;
use std::fs::{self, OpenOptions};
use std::io::{self, Write};
use std::path::Path;

use ring::aead::{AES_256_GCM, Aad, LessSafeKey, Nonce, UnboundKey};
use ring::rand::{SecureRandom, SystemRandom};

#[cfg(unix)]
use std::fs::Permissions;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;

mod base64;

const VERSION: u8 = 1;
const KEY_LEN: usize = 32;
const NONCE_LEN: usize = 12;
const TAG_LEN: usize = 16;
const MAX_ID_LEN: usize = 16;

#[derive(Debug)]
pub enum CryptError {
    Io(io::Error),
    Key(String),
    Format(&'static str),
    UnknownKey(String),
    Truncated,
    Integrity,
}

impl fmt::Display for CryptError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CryptError::Io(e) => write!(f, "io: {e}"),
            CryptError::Key(e) => write!(f, "key: {e}"),
            CryptError::Format(e) => write!(f, "format: {e}"),
            CryptError::UnknownKey(id) => write!(f, "unknown key id: {id}"),
            CryptError::Truncated => write!(f, "truncated ciphertext"),
            CryptError::Integrity => write!(f, "tampered ciphertext or wrong aad"),
        }
    }
}

impl std::error::Error for CryptError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            CryptError::Io(e) => Some(e),
            _ => None,
        }
    }
}

impl From<io::Error> for CryptError {
    fn from(e: io::Error) -> Self {
        CryptError::Io(e)
    }
}

#[derive(Clone)]
struct Key {
    id: String,
    bytes: [u8; KEY_LEN],
}

pub struct Keyring {
    keys: Vec<Key>,
    rng: SystemRandom,
}

impl Keyring {
    pub fn from_file(path: &Path) -> Result<Self, CryptError> {
        check_perm(path)?;
        let text = fs::read_to_string(path)?;
        Self::parse(&text)
    }

    pub fn generate_file(path: &Path, id: &str) -> Result<(), CryptError> {
        validate_id(id).map_err(|e| CryptError::Key(e.into()))?;
        let rng = SystemRandom::new();
        let mut bytes = [0u8; KEY_LEN];
        rng.fill(&mut bytes)
            .map_err(|_| CryptError::Key("system random failed".into()))?;
        let content = format!("{id}:{}\n", base64::encode(&bytes));
        let mut opts = OpenOptions::new();
        opts.write(true).create_new(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            opts.mode(0o600);
        }
        let mut file = opts.open(path)?;
        #[cfg(unix)]
        file.set_permissions(Permissions::from_mode(0o600))?;
        file.write_all(content.as_bytes())?;
        Ok(())
    }

    pub fn encrypt(&self, plaintext: &[u8], aad: &[u8]) -> Vec<u8> {
        let key = &self.keys[0];
        let mut nonce = [0u8; NONCE_LEN];
        self.rng
            .fill(&mut nonce)
            .expect("system random source failed");
        let mut out = Vec::with_capacity(2 + key.id.len() + NONCE_LEN + plaintext.len() + TAG_LEN);
        out.push(VERSION);
        out.push(key.id.len() as u8);
        out.extend_from_slice(key.id.as_bytes());
        out.extend_from_slice(&nonce);
        let head = out.len();
        out.extend_from_slice(plaintext);
        let sealing =
            LessSafeKey::new(UnboundKey::new(&AES_256_GCM, &key.bytes).expect("32-byte key"));
        let tag = sealing
            .seal_in_place_separate_tag(
                Nonce::assume_unique_for_key(nonce),
                Aad::from(aad),
                &mut out[head..],
            )
            .expect("seal in place");
        out.extend_from_slice(tag.as_ref());
        out
    }

    pub fn decrypt(&self, data: &[u8], aad: &[u8]) -> Result<Vec<u8>, CryptError> {
        let parts = parts(data)?;
        let key = self
            .keys
            .iter()
            .find(|k| k.id == parts.id)
            .ok_or_else(|| CryptError::UnknownKey(parts.id.to_owned()))?;
        let nonce = Nonce::try_assume_unique_for_key(parts.nonce)
            .map_err(|_| CryptError::Format("bad nonce length"))?;
        let unbound = UnboundKey::new(&AES_256_GCM, &key.bytes)
            .map_err(|_| CryptError::Key("bad key length".into()))?;
        let opening = LessSafeKey::new(unbound);
        let mut buf = parts.sealed.to_vec();
        let plaintext = opening
            .open_in_place(nonce, Aad::from(aad), &mut buf)
            .map_err(|_| CryptError::Integrity)?;
        Ok(plaintext.to_vec())
    }

    fn parse(text: &str) -> Result<Self, CryptError> {
        let mut keys: Vec<Key> = Vec::new();
        for (n, line) in text.lines().enumerate() {
            let line = line.trim();
            if line.is_empty() {
                continue;
            }
            let (id, enc) = line
                .split_once(':')
                .ok_or_else(|| line_err(n, "expected <id>:<base64>"))?;
            validate_id(id).map_err(|e| line_err(n, e))?;
            let bytes = base64::decode(enc).map_err(|e| line_err(n, e))?;
            let bytes: [u8; KEY_LEN] = bytes
                .as_slice()
                .try_into()
                .map_err(|_| line_err(n, "key must be 32 bytes"))?;
            if keys.iter().any(|k| k.id == id) {
                return Err(line_err(n, "duplicate key id"));
            }
            keys.push(Key {
                id: id.to_owned(),
                bytes,
            });
        }
        if keys.is_empty() {
            return Err(CryptError::Key("no keys in keyring".into()));
        }
        Ok(Self {
            keys,
            rng: SystemRandom::new(),
        })
    }
}

pub fn is_encrypted(data: &[u8]) -> bool {
    parts(data).is_ok()
}

struct Parts<'a> {
    id: &'a str,
    nonce: &'a [u8],
    sealed: &'a [u8],
}

fn parts(data: &[u8]) -> Result<Parts<'_>, CryptError> {
    let (&version, rest) = data.split_first().ok_or(CryptError::Truncated)?;
    if version != VERSION {
        return Err(CryptError::Format("unsupported version"));
    }
    let (&id_len, rest) = rest.split_first().ok_or(CryptError::Truncated)?;
    if id_len == 0 || id_len as usize > MAX_ID_LEN {
        return Err(CryptError::Format("bad key id length"));
    }
    let id_len = id_len as usize;
    if rest.len() < id_len + NONCE_LEN + TAG_LEN {
        return Err(CryptError::Truncated);
    }
    let (id, rest) = rest.split_at(id_len);
    let id = std::str::from_utf8(id).map_err(|_| CryptError::Format("bad key id"))?;
    validate_id(id).map_err(|_| CryptError::Format("bad key id"))?;
    let (nonce, sealed) = rest.split_at(NONCE_LEN);
    Ok(Parts { id, nonce, sealed })
}

fn validate_id(id: &str) -> Result<(), &'static str> {
    if id.is_empty() {
        return Err("empty key id");
    }
    if id.len() > MAX_ID_LEN {
        return Err("key id too long");
    }
    if !id
        .bytes()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
    {
        return Err("key id must match [a-z0-9-]");
    }
    Ok(())
}

fn line_err(n: usize, what: impl Into<String>) -> CryptError {
    CryptError::Key(format!("line {}: {}", n + 1, what.into()))
}

#[cfg(unix)]
fn check_perm(path: &Path) -> Result<(), CryptError> {
    let mode = fs::metadata(path)?.permissions().mode() & 0o777;
    if mode & 0o077 != 0 {
        return Err(CryptError::Key(format!(
            "{path:?} mode {mode:04o} allows access to group or others, need 0600 or stricter"
        )));
    }
    Ok(())
}

#[cfg(not(unix))]
fn check_perm(_path: &Path) -> Result<(), CryptError> {
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;
    use std::sync::atomic::{AtomicU32, Ordering};
    use std::time::{SystemTime, UNIX_EPOCH};

    static SEQ: AtomicU32 = AtomicU32::new(0);

    struct TmpDir(PathBuf);

    impl TmpDir {
        fn new(tag: &str) -> Self {
            let nanos = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_nanos();
            let path = std::env::temp_dir().join(format!(
                "krab-crypt-{tag}-{}-{}-{nanos}",
                std::process::id(),
                SEQ.fetch_add(1, Ordering::Relaxed)
            ));
            fs::create_dir(&path).unwrap();
            Self(path)
        }

        fn path(&self) -> &Path {
            &self.0
        }
    }

    impl Drop for TmpDir {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.0);
        }
    }

    fn key_line(id: &str, seed: u8) -> String {
        format!("{id}:{}\n", base64::encode(&[seed; KEY_LEN]))
    }

    fn write_ring(dir: &Path, name: &str, content: &str) -> PathBuf {
        let p = dir.join(name);
        fs::write(&p, content).unwrap();
        #[cfg(unix)]
        fs::set_permissions(&p, Permissions::from_mode(0o600)).unwrap();
        p
    }

    fn load_ring(dir: &Path, name: &str, content: &str) -> Keyring {
        Keyring::from_file(&write_ring(dir, name, content)).unwrap()
    }

    #[test]
    fn roundtrip() {
        let dir = TmpDir::new("rt");
        let ring = load_ring(dir.path(), "keys", &key_line("k1", 7));
        let aad = b"secrets/default/app";
        let ct = ring.encrypt(b"hunter2", aad);
        assert_ne!(ct.as_slice(), b"hunter2");
        assert!(is_encrypted(&ct));
        assert_eq!(ring.decrypt(&ct, aad).unwrap(), b"hunter2");
        assert_eq!(
            ring.decrypt(&ring.encrypt(b"", aad), aad).unwrap(),
            Vec::<u8>::new()
        );
    }

    #[test]
    fn tampered_byte() {
        let dir = TmpDir::new("tamper");
        let ring = load_ring(dir.path(), "keys", &key_line("k1", 7));
        let ct = ring.encrypt(b"payload data", b"aad");
        let mut bad_ct = ct.clone();
        let mid = bad_ct.len() - 20;
        bad_ct[mid] ^= 1;
        assert!(matches!(
            ring.decrypt(&bad_ct, b"aad"),
            Err(CryptError::Integrity)
        ));
        let mut bad_tag = ct.clone();
        let last = bad_tag.len() - 1;
        bad_tag[last] ^= 0x80;
        assert!(matches!(
            ring.decrypt(&bad_tag, b"aad"),
            Err(CryptError::Integrity)
        ));
    }

    #[test]
    fn wrong_aad() {
        let dir = TmpDir::new("aad");
        let ring = load_ring(dir.path(), "keys", &key_line("k1", 7));
        let ct = ring.encrypt(b"payload", b"secrets/ns/name");
        assert!(matches!(
            ring.decrypt(&ct, b"secrets/ns/other"),
            Err(CryptError::Integrity)
        ));
        assert!(matches!(ring.decrypt(&ct, b""), Err(CryptError::Integrity)));
    }

    #[test]
    fn rotation() {
        let dir = TmpDir::new("rot");
        let ring = load_ring(
            dir.path(),
            "keys",
            &format!("{}{}", key_line("v2", 9), key_line("v1", 3)),
        );
        let only_new = load_ring(dir.path(), "new", &key_line("v2", 9));
        let only_old = load_ring(dir.path(), "old", &key_line("v1", 3));
        let old_ct = only_old.encrypt(b"old data", b"aad");
        assert_eq!(&old_ct[2..4], b"v1");
        assert_eq!(ring.decrypt(&old_ct, b"aad").unwrap(), b"old data");
        let ct = ring.encrypt(b"old data", b"aad");
        assert_eq!(&ct[2..4], b"v2");
        assert_eq!(only_new.decrypt(&ct, b"aad").unwrap(), b"old data");
        assert!(matches!(
            only_new.decrypt(&old_ct, b"aad"),
            Err(CryptError::UnknownKey(id)) if id == "v1"
        ));
    }

    #[test]
    fn unknown_key_id() {
        let dir = TmpDir::new("unknown");
        let ring_a = load_ring(dir.path(), "a", &key_line("aaa", 1));
        let ring_b = load_ring(dir.path(), "b", &key_line("bbb", 2));
        let ct = ring_b.encrypt(b"x", b"aad");
        assert!(matches!(
            ring_a.decrypt(&ct, b"aad"),
            Err(CryptError::UnknownKey(id)) if id == "bbb"
        ));
    }

    #[test]
    fn truncated_and_bad_format() {
        let dir = TmpDir::new("trunc");
        let ring = load_ring(dir.path(), "keys", &key_line("k1", 7));
        let ct = ring.encrypt(b"payload", b"aad");
        assert_eq!(ct.len(), 2 + 2 + NONCE_LEN + 7 + TAG_LEN);
        for len in [0usize, 1, 2, 5, ct.len() - TAG_LEN - 8] {
            assert!(
                matches!(ring.decrypt(&ct[..len], b"aad"), Err(CryptError::Truncated)),
                "len {len}"
            );
        }
        assert!(matches!(
            ring.decrypt(&ct[..ct.len() - 1], b"aad"),
            Err(CryptError::Integrity)
        ));
        let mut bad_version = ct.clone();
        bad_version[0] = 2;
        assert!(matches!(
            ring.decrypt(&bad_version, b"aad"),
            Err(CryptError::Format(_))
        ));
        let mut bad_id = ct.clone();
        bad_id[2] = b'A';
        assert!(matches!(
            ring.decrypt(&bad_id, b"aad"),
            Err(CryptError::Format(_))
        ));
    }

    #[test]
    #[cfg(unix)]
    fn keyring_file_permissions() {
        let dir = TmpDir::new("perm");
        let p = dir.path().join("keys");
        fs::write(&p, key_line("k1", 1)).unwrap();
        for (mode, ok) in [
            (0o600, true),
            (0o400, true),
            (0o640, false),
            (0o604, false),
            (0o644, false),
            (0o666, false),
        ] {
            fs::set_permissions(&p, Permissions::from_mode(0o600)).unwrap();
            fs::write(&p, key_line("k1", 1)).unwrap();
            fs::set_permissions(&p, Permissions::from_mode(mode)).unwrap();
            assert_eq!(Keyring::from_file(&p).is_ok(), ok, "mode {mode:04o}");
        }
    }

    #[test]
    fn generate_file_no_overwrite() {
        let dir = TmpDir::new("gen");
        let p = dir.path().join("new-key");
        Keyring::generate_file(&p, "app-key").unwrap();
        let ring = Keyring::from_file(&p).unwrap();
        let ct = ring.encrypt(b"abc", b"aad");
        assert_eq!(ring.decrypt(&ct, b"aad").unwrap(), b"abc");
        let before = fs::read(&p).unwrap();
        assert!(Keyring::generate_file(&p, "other").is_err());
        assert_eq!(fs::read(&p).unwrap(), before);
        #[cfg(unix)]
        assert_eq!(
            fs::metadata(&p).unwrap().permissions().mode() & 0o777,
            0o600
        );
        assert!(matches!(
            Keyring::generate_file(&dir.path().join("bad"), "BAD ID"),
            Err(CryptError::Key(_))
        ));
    }

    #[test]
    fn keyring_file_errors() {
        let dir = TmpDir::new("errs");
        for content in [
            "",
            "k1",
            "K1:QUJDRA==",
            "abcdefghijklmnopq:QUJDRA==",
            "k1:QUJDRA==",
            "k1:QUJDRA==\nk1:Zm9vYmFy",
            "k1:!!bad!!",
        ] {
            let p = write_ring(dir.path(), "keys", content);
            assert!(
                matches!(Keyring::from_file(&p), Err(CryptError::Key(_))),
                "content {content:?}"
            );
        }
    }

    #[test]
    fn is_encrypted_rejects_garbage() {
        assert!(!is_encrypted(b""));
        assert!(!is_encrypted(b"plain secret"));
        assert!(!is_encrypted(&[1]));
        assert!(!is_encrypted(&[1, 2]));
        let mut fake = vec![1u8, 3];
        fake.extend(b"ABC");
        fake.extend([0u8; 28]);
        assert!(!is_encrypted(&fake));
        let dir = TmpDir::new("isenc");
        let ring = load_ring(dir.path(), "keys", &key_line("k1", 7));
        let ct = ring.encrypt(b"payload", b"aad");
        assert!(is_encrypted(&ct));
        let mut truncated = ct.clone();
        truncated.truncate(truncated.len() - TAG_LEN);
        assert!(!is_encrypted(&truncated));
    }
}