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));
}
}