Skip to main content

krab_crypt/
lib.rs

1use std::fmt;
2use std::fs::{self, OpenOptions};
3use std::io::{self, Write};
4use std::path::Path;
5
6use ring::aead::{AES_256_GCM, Aad, LessSafeKey, Nonce, UnboundKey};
7use ring::rand::{SecureRandom, SystemRandom};
8
9#[cfg(unix)]
10use std::fs::Permissions;
11#[cfg(unix)]
12use std::os::unix::fs::PermissionsExt;
13
14mod base64;
15
16const VERSION: u8 = 1;
17const KEY_LEN: usize = 32;
18const NONCE_LEN: usize = 12;
19const TAG_LEN: usize = 16;
20const MAX_ID_LEN: usize = 16;
21
22#[derive(Debug)]
23pub enum CryptError {
24    Io(io::Error),
25    Key(String),
26    Format(&'static str),
27    UnknownKey(String),
28    Truncated,
29    Integrity,
30}
31
32impl fmt::Display for CryptError {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            CryptError::Io(e) => write!(f, "io: {e}"),
36            CryptError::Key(e) => write!(f, "key: {e}"),
37            CryptError::Format(e) => write!(f, "format: {e}"),
38            CryptError::UnknownKey(id) => write!(f, "unknown key id: {id}"),
39            CryptError::Truncated => write!(f, "truncated ciphertext"),
40            CryptError::Integrity => write!(f, "tampered ciphertext or wrong aad"),
41        }
42    }
43}
44
45impl std::error::Error for CryptError {
46    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
47        match self {
48            CryptError::Io(e) => Some(e),
49            _ => None,
50        }
51    }
52}
53
54impl From<io::Error> for CryptError {
55    fn from(e: io::Error) -> Self {
56        CryptError::Io(e)
57    }
58}
59
60#[derive(Clone)]
61struct Key {
62    id: String,
63    bytes: [u8; KEY_LEN],
64}
65
66pub struct Keyring {
67    keys: Vec<Key>,
68    rng: SystemRandom,
69}
70
71impl Keyring {
72    pub fn from_file(path: &Path) -> Result<Self, CryptError> {
73        check_perm(path)?;
74        let text = fs::read_to_string(path)?;
75        Self::parse(&text)
76    }
77
78    pub fn generate_file(path: &Path, id: &str) -> Result<(), CryptError> {
79        validate_id(id).map_err(|e| CryptError::Key(e.into()))?;
80        let rng = SystemRandom::new();
81        let mut bytes = [0u8; KEY_LEN];
82        rng.fill(&mut bytes)
83            .map_err(|_| CryptError::Key("system random failed".into()))?;
84        let content = format!("{id}:{}\n", base64::encode(&bytes));
85        let mut opts = OpenOptions::new();
86        opts.write(true).create_new(true);
87        #[cfg(unix)]
88        {
89            use std::os::unix::fs::OpenOptionsExt;
90            opts.mode(0o600);
91        }
92        let mut file = opts.open(path)?;
93        #[cfg(unix)]
94        file.set_permissions(Permissions::from_mode(0o600))?;
95        file.write_all(content.as_bytes())?;
96        Ok(())
97    }
98
99    pub fn encrypt(&self, plaintext: &[u8], aad: &[u8]) -> Vec<u8> {
100        let key = &self.keys[0];
101        let mut nonce = [0u8; NONCE_LEN];
102        self.rng
103            .fill(&mut nonce)
104            .expect("system random source failed");
105        let mut out = Vec::with_capacity(2 + key.id.len() + NONCE_LEN + plaintext.len() + TAG_LEN);
106        out.push(VERSION);
107        out.push(key.id.len() as u8);
108        out.extend_from_slice(key.id.as_bytes());
109        out.extend_from_slice(&nonce);
110        let head = out.len();
111        out.extend_from_slice(plaintext);
112        let sealing =
113            LessSafeKey::new(UnboundKey::new(&AES_256_GCM, &key.bytes).expect("32-byte key"));
114        let tag = sealing
115            .seal_in_place_separate_tag(
116                Nonce::assume_unique_for_key(nonce),
117                Aad::from(aad),
118                &mut out[head..],
119            )
120            .expect("seal in place");
121        out.extend_from_slice(tag.as_ref());
122        out
123    }
124
125    pub fn decrypt(&self, data: &[u8], aad: &[u8]) -> Result<Vec<u8>, CryptError> {
126        let parts = parts(data)?;
127        let key = self
128            .keys
129            .iter()
130            .find(|k| k.id == parts.id)
131            .ok_or_else(|| CryptError::UnknownKey(parts.id.to_owned()))?;
132        let nonce = Nonce::try_assume_unique_for_key(parts.nonce)
133            .map_err(|_| CryptError::Format("bad nonce length"))?;
134        let unbound = UnboundKey::new(&AES_256_GCM, &key.bytes)
135            .map_err(|_| CryptError::Key("bad key length".into()))?;
136        let opening = LessSafeKey::new(unbound);
137        let mut buf = parts.sealed.to_vec();
138        let plaintext = opening
139            .open_in_place(nonce, Aad::from(aad), &mut buf)
140            .map_err(|_| CryptError::Integrity)?;
141        Ok(plaintext.to_vec())
142    }
143
144    fn parse(text: &str) -> Result<Self, CryptError> {
145        let mut keys: Vec<Key> = Vec::new();
146        for (n, line) in text.lines().enumerate() {
147            let line = line.trim();
148            if line.is_empty() {
149                continue;
150            }
151            let (id, enc) = line
152                .split_once(':')
153                .ok_or_else(|| line_err(n, "expected <id>:<base64>"))?;
154            validate_id(id).map_err(|e| line_err(n, e))?;
155            let bytes = base64::decode(enc).map_err(|e| line_err(n, e))?;
156            let bytes: [u8; KEY_LEN] = bytes
157                .as_slice()
158                .try_into()
159                .map_err(|_| line_err(n, "key must be 32 bytes"))?;
160            if keys.iter().any(|k| k.id == id) {
161                return Err(line_err(n, "duplicate key id"));
162            }
163            keys.push(Key {
164                id: id.to_owned(),
165                bytes,
166            });
167        }
168        if keys.is_empty() {
169            return Err(CryptError::Key("no keys in keyring".into()));
170        }
171        Ok(Self {
172            keys,
173            rng: SystemRandom::new(),
174        })
175    }
176}
177
178pub fn is_encrypted(data: &[u8]) -> bool {
179    parts(data).is_ok()
180}
181
182struct Parts<'a> {
183    id: &'a str,
184    nonce: &'a [u8],
185    sealed: &'a [u8],
186}
187
188fn parts(data: &[u8]) -> Result<Parts<'_>, CryptError> {
189    let (&version, rest) = data.split_first().ok_or(CryptError::Truncated)?;
190    if version != VERSION {
191        return Err(CryptError::Format("unsupported version"));
192    }
193    let (&id_len, rest) = rest.split_first().ok_or(CryptError::Truncated)?;
194    if id_len == 0 || id_len as usize > MAX_ID_LEN {
195        return Err(CryptError::Format("bad key id length"));
196    }
197    let id_len = id_len as usize;
198    if rest.len() < id_len + NONCE_LEN + TAG_LEN {
199        return Err(CryptError::Truncated);
200    }
201    let (id, rest) = rest.split_at(id_len);
202    let id = std::str::from_utf8(id).map_err(|_| CryptError::Format("bad key id"))?;
203    validate_id(id).map_err(|_| CryptError::Format("bad key id"))?;
204    let (nonce, sealed) = rest.split_at(NONCE_LEN);
205    Ok(Parts { id, nonce, sealed })
206}
207
208fn validate_id(id: &str) -> Result<(), &'static str> {
209    if id.is_empty() {
210        return Err("empty key id");
211    }
212    if id.len() > MAX_ID_LEN {
213        return Err("key id too long");
214    }
215    if !id
216        .bytes()
217        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
218    {
219        return Err("key id must match [a-z0-9-]");
220    }
221    Ok(())
222}
223
224fn line_err(n: usize, what: impl Into<String>) -> CryptError {
225    CryptError::Key(format!("line {}: {}", n + 1, what.into()))
226}
227
228#[cfg(unix)]
229fn check_perm(path: &Path) -> Result<(), CryptError> {
230    let mode = fs::metadata(path)?.permissions().mode() & 0o777;
231    if mode & 0o077 != 0 {
232        return Err(CryptError::Key(format!(
233            "{path:?} mode {mode:04o} allows access to group or others, need 0600 or stricter"
234        )));
235    }
236    Ok(())
237}
238
239#[cfg(not(unix))]
240fn check_perm(_path: &Path) -> Result<(), CryptError> {
241    Ok(())
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247    use std::path::PathBuf;
248    use std::sync::atomic::{AtomicU32, Ordering};
249    use std::time::{SystemTime, UNIX_EPOCH};
250
251    static SEQ: AtomicU32 = AtomicU32::new(0);
252
253    struct TmpDir(PathBuf);
254
255    impl TmpDir {
256        fn new(tag: &str) -> Self {
257            let nanos = SystemTime::now()
258                .duration_since(UNIX_EPOCH)
259                .unwrap()
260                .as_nanos();
261            let path = std::env::temp_dir().join(format!(
262                "krab-crypt-{tag}-{}-{}-{nanos}",
263                std::process::id(),
264                SEQ.fetch_add(1, Ordering::Relaxed)
265            ));
266            fs::create_dir(&path).unwrap();
267            Self(path)
268        }
269
270        fn path(&self) -> &Path {
271            &self.0
272        }
273    }
274
275    impl Drop for TmpDir {
276        fn drop(&mut self) {
277            let _ = fs::remove_dir_all(&self.0);
278        }
279    }
280
281    fn key_line(id: &str, seed: u8) -> String {
282        format!("{id}:{}\n", base64::encode(&[seed; KEY_LEN]))
283    }
284
285    fn write_ring(dir: &Path, name: &str, content: &str) -> PathBuf {
286        let p = dir.join(name);
287        fs::write(&p, content).unwrap();
288        #[cfg(unix)]
289        fs::set_permissions(&p, Permissions::from_mode(0o600)).unwrap();
290        p
291    }
292
293    fn load_ring(dir: &Path, name: &str, content: &str) -> Keyring {
294        Keyring::from_file(&write_ring(dir, name, content)).unwrap()
295    }
296
297    #[test]
298    fn roundtrip() {
299        let dir = TmpDir::new("rt");
300        let ring = load_ring(dir.path(), "keys", &key_line("k1", 7));
301        let aad = b"secrets/default/app";
302        let ct = ring.encrypt(b"hunter2", aad);
303        assert_ne!(ct.as_slice(), b"hunter2");
304        assert!(is_encrypted(&ct));
305        assert_eq!(ring.decrypt(&ct, aad).unwrap(), b"hunter2");
306        assert_eq!(
307            ring.decrypt(&ring.encrypt(b"", aad), aad).unwrap(),
308            Vec::<u8>::new()
309        );
310    }
311
312    #[test]
313    fn tampered_byte() {
314        let dir = TmpDir::new("tamper");
315        let ring = load_ring(dir.path(), "keys", &key_line("k1", 7));
316        let ct = ring.encrypt(b"payload data", b"aad");
317        let mut bad_ct = ct.clone();
318        let mid = bad_ct.len() - 20;
319        bad_ct[mid] ^= 1;
320        assert!(matches!(
321            ring.decrypt(&bad_ct, b"aad"),
322            Err(CryptError::Integrity)
323        ));
324        let mut bad_tag = ct.clone();
325        let last = bad_tag.len() - 1;
326        bad_tag[last] ^= 0x80;
327        assert!(matches!(
328            ring.decrypt(&bad_tag, b"aad"),
329            Err(CryptError::Integrity)
330        ));
331    }
332
333    #[test]
334    fn wrong_aad() {
335        let dir = TmpDir::new("aad");
336        let ring = load_ring(dir.path(), "keys", &key_line("k1", 7));
337        let ct = ring.encrypt(b"payload", b"secrets/ns/name");
338        assert!(matches!(
339            ring.decrypt(&ct, b"secrets/ns/other"),
340            Err(CryptError::Integrity)
341        ));
342        assert!(matches!(ring.decrypt(&ct, b""), Err(CryptError::Integrity)));
343    }
344
345    #[test]
346    fn rotation() {
347        let dir = TmpDir::new("rot");
348        let ring = load_ring(
349            dir.path(),
350            "keys",
351            &format!("{}{}", key_line("v2", 9), key_line("v1", 3)),
352        );
353        let only_new = load_ring(dir.path(), "new", &key_line("v2", 9));
354        let only_old = load_ring(dir.path(), "old", &key_line("v1", 3));
355        let old_ct = only_old.encrypt(b"old data", b"aad");
356        assert_eq!(&old_ct[2..4], b"v1");
357        assert_eq!(ring.decrypt(&old_ct, b"aad").unwrap(), b"old data");
358        let ct = ring.encrypt(b"old data", b"aad");
359        assert_eq!(&ct[2..4], b"v2");
360        assert_eq!(only_new.decrypt(&ct, b"aad").unwrap(), b"old data");
361        assert!(matches!(
362            only_new.decrypt(&old_ct, b"aad"),
363            Err(CryptError::UnknownKey(id)) if id == "v1"
364        ));
365    }
366
367    #[test]
368    fn unknown_key_id() {
369        let dir = TmpDir::new("unknown");
370        let ring_a = load_ring(dir.path(), "a", &key_line("aaa", 1));
371        let ring_b = load_ring(dir.path(), "b", &key_line("bbb", 2));
372        let ct = ring_b.encrypt(b"x", b"aad");
373        assert!(matches!(
374            ring_a.decrypt(&ct, b"aad"),
375            Err(CryptError::UnknownKey(id)) if id == "bbb"
376        ));
377    }
378
379    #[test]
380    fn truncated_and_bad_format() {
381        let dir = TmpDir::new("trunc");
382        let ring = load_ring(dir.path(), "keys", &key_line("k1", 7));
383        let ct = ring.encrypt(b"payload", b"aad");
384        assert_eq!(ct.len(), 2 + 2 + NONCE_LEN + 7 + TAG_LEN);
385        for len in [0usize, 1, 2, 5, ct.len() - TAG_LEN - 8] {
386            assert!(
387                matches!(ring.decrypt(&ct[..len], b"aad"), Err(CryptError::Truncated)),
388                "len {len}"
389            );
390        }
391        assert!(matches!(
392            ring.decrypt(&ct[..ct.len() - 1], b"aad"),
393            Err(CryptError::Integrity)
394        ));
395        let mut bad_version = ct.clone();
396        bad_version[0] = 2;
397        assert!(matches!(
398            ring.decrypt(&bad_version, b"aad"),
399            Err(CryptError::Format(_))
400        ));
401        let mut bad_id = ct.clone();
402        bad_id[2] = b'A';
403        assert!(matches!(
404            ring.decrypt(&bad_id, b"aad"),
405            Err(CryptError::Format(_))
406        ));
407    }
408
409    #[test]
410    #[cfg(unix)]
411    fn keyring_file_permissions() {
412        let dir = TmpDir::new("perm");
413        let p = dir.path().join("keys");
414        fs::write(&p, key_line("k1", 1)).unwrap();
415        for (mode, ok) in [
416            (0o600, true),
417            (0o400, true),
418            (0o640, false),
419            (0o604, false),
420            (0o644, false),
421            (0o666, false),
422        ] {
423            fs::set_permissions(&p, Permissions::from_mode(0o600)).unwrap();
424            fs::write(&p, key_line("k1", 1)).unwrap();
425            fs::set_permissions(&p, Permissions::from_mode(mode)).unwrap();
426            assert_eq!(Keyring::from_file(&p).is_ok(), ok, "mode {mode:04o}");
427        }
428    }
429
430    #[test]
431    fn generate_file_no_overwrite() {
432        let dir = TmpDir::new("gen");
433        let p = dir.path().join("new-key");
434        Keyring::generate_file(&p, "app-key").unwrap();
435        let ring = Keyring::from_file(&p).unwrap();
436        let ct = ring.encrypt(b"abc", b"aad");
437        assert_eq!(ring.decrypt(&ct, b"aad").unwrap(), b"abc");
438        let before = fs::read(&p).unwrap();
439        assert!(Keyring::generate_file(&p, "other").is_err());
440        assert_eq!(fs::read(&p).unwrap(), before);
441        #[cfg(unix)]
442        assert_eq!(
443            fs::metadata(&p).unwrap().permissions().mode() & 0o777,
444            0o600
445        );
446        assert!(matches!(
447            Keyring::generate_file(&dir.path().join("bad"), "BAD ID"),
448            Err(CryptError::Key(_))
449        ));
450    }
451
452    #[test]
453    fn keyring_file_errors() {
454        let dir = TmpDir::new("errs");
455        for content in [
456            "",
457            "k1",
458            "K1:QUJDRA==",
459            "abcdefghijklmnopq:QUJDRA==",
460            "k1:QUJDRA==",
461            "k1:QUJDRA==\nk1:Zm9vYmFy",
462            "k1:!!bad!!",
463        ] {
464            let p = write_ring(dir.path(), "keys", content);
465            assert!(
466                matches!(Keyring::from_file(&p), Err(CryptError::Key(_))),
467                "content {content:?}"
468            );
469        }
470    }
471
472    #[test]
473    fn is_encrypted_rejects_garbage() {
474        assert!(!is_encrypted(b""));
475        assert!(!is_encrypted(b"plain secret"));
476        assert!(!is_encrypted(&[1]));
477        assert!(!is_encrypted(&[1, 2]));
478        let mut fake = vec![1u8, 3];
479        fake.extend(b"ABC");
480        fake.extend([0u8; 28]);
481        assert!(!is_encrypted(&fake));
482        let dir = TmpDir::new("isenc");
483        let ring = load_ring(dir.path(), "keys", &key_line("k1", 7));
484        let ct = ring.encrypt(b"payload", b"aad");
485        assert!(is_encrypted(&ct));
486        let mut truncated = ct.clone();
487        truncated.truncate(truncated.len() - TAG_LEN);
488        assert!(!is_encrypted(&truncated));
489    }
490}