use std::sync::{Arc, RwLock};
pub mod legacy;
use aes_gcm::aead::{Aead, KeyInit};
use aes_gcm::{Aes256Gcm, Nonce};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use hmac::{Hmac, Mac};
use sha2::Sha256;
use crate::db::Value;
use crate::{Error, Result};
const PREFIX: &str = "gl1:";
const DETERMINISTIC_PREFIX: &str = "gl1d:";
const NONCE_LEN: usize = 12;
static KEYS: RwLock<Option<Arc<Vec<[u8; 32]>>>> = RwLock::new(None);
pub fn install(key: &str, previous: &[String]) {
let keys = std::iter::once(key)
.chain(previous.iter().map(String::as_str))
.map(derive)
.collect();
*KEYS.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(keys));
}
pub(crate) fn configure(config: &crate::Config) -> Result<()> {
let key = match config.get_opt::<String>("encryption.key")? {
Some(key) => Some(key),
None => config.get_opt::<String>("secret_key_base")?,
};
if let Some(key) = key {
let previous: Vec<String> = config
.get_opt("encryption.previous_keys")?
.unwrap_or_default();
install(&key, &previous);
}
legacy::configure(config)
}
fn derive(secret: &str) -> [u8; 32] {
let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(secret.as_bytes())
.expect("HMAC takes a key of any length");
mac.update(b"glacier column encryption");
mac.finalize().into_bytes().into()
}
fn keys() -> Result<Arc<Vec<[u8; 32]>>> {
KEYS.read()
.unwrap_or_else(|e| e.into_inner())
.clone()
.ok_or_else(|| {
Error::internal(
"no key for encrypted columns: set `secret_key_base` or `encryption.key` in the config",
)
})
}
pub fn encrypt(plain: &str) -> Result<String> {
let keys = keys()?;
let cipher = Aes256Gcm::new((&keys[0]).into());
let mut nonce = [0u8; NONCE_LEN];
getrandom::fill(&mut nonce).expect("the system's random number generator failed");
let sealed = cipher
.encrypt(Nonce::from_slice(&nonce), plain.as_bytes())
.map_err(|_| Error::internal("encrypting a column failed"))?;
let mut bytes = nonce.to_vec();
bytes.extend(sealed);
Ok(format!("{PREFIX}{}", STANDARD.encode(bytes)))
}
pub fn encrypt_deterministic(plain: &str) -> Result<String> {
Ok(deterministic_with(&keys()?[0], plain))
}
pub(crate) fn deterministic_variants(plain: &str) -> Result<Vec<String>> {
Ok(keys()?
.iter()
.map(|key| deterministic_with(key, plain))
.collect())
}
fn deterministic_with(key: &[u8; 32], plain: &str) -> String {
let mut mac =
<Hmac<Sha256> as Mac>::new_from_slice(key).expect("HMAC takes a key of any length");
mac.update(b"glacier deterministic|");
mac.update(plain.as_bytes());
let nonce: [u8; NONCE_LEN] = mac.finalize().into_bytes()[..NONCE_LEN]
.try_into()
.expect("a SHA-256 MAC is longer than a nonce");
let sealed = Aes256Gcm::new(key.into())
.encrypt(Nonce::from_slice(&nonce), plain.as_bytes())
.expect("AES-GCM encrypts any text this size");
let mut bytes = nonce.to_vec();
bytes.extend(sealed);
format!("{DETERMINISTIC_PREFIX}{}", STANDARD.encode(bytes))
}
pub fn decrypt(stored: &str) -> Result<String> {
let Some(encoded) = stored
.strip_prefix(PREFIX)
.or_else(|| stored.strip_prefix(DETERMINISTIC_PREFIX))
else {
return legacy::decrypt(stored).unwrap_or_else(|| Ok(stored.to_owned()));
};
let bytes = STANDARD
.decode(encoded)
.map_err(|_| Error::internal("an encrypted column isn't base64"))?;
if bytes.len() < NONCE_LEN {
return Err(Error::internal("an encrypted column is too short"));
}
let (nonce, sealed) = bytes.split_at(NONCE_LEN);
for key in keys()?.iter() {
let cipher = Aes256Gcm::new(key.into());
if let Ok(plain) = cipher.decrypt(Nonce::from_slice(nonce), sealed) {
return String::from_utf8(plain)
.map_err(|_| Error::internal("an encrypted column isn't UTF-8"));
}
}
Err(Error::internal(
"no key decrypts an encrypted column: was `secret_key_base` or `encryption.key` changed without adding the old one to `encryption.previous_keys`?",
))
}
#[doc(hidden)]
pub fn stored<M: crate::model::Model>(column: &str, value: Value) -> Result<Value> {
if !M::ENCRYPTED.contains(&column) {
return Ok(value);
}
match value {
Value::Null => Ok(Value::Null),
other if M::DETERMINISTIC.contains(&column) => {
Ok(Value::Text(encrypt_deterministic(&other.to_text())?))
}
other => Ok(Value::Text(encrypt(&other.to_text())?)),
}
}
pub(crate) fn query_condition<M: crate::model::Model>(expr: crate::db::Expr) -> crate::db::Expr {
use crate::db::Expr;
if M::DETERMINISTIC.is_empty() {
return expr;
}
let variants = |value: &Value| -> Option<Vec<Value>> {
if value.is_null() {
return None;
}
let texts = deterministic_variants(&value.to_text()).ok()?;
Some(texts.into_iter().map(Value::Text).collect())
};
match expr {
Expr::Compare { column, op, value } if M::DETERMINISTIC.contains(&column) => {
match (op, variants(&value)) {
("=", Some(values)) => Expr::In { column, values },
("!=" | "<>", Some(values)) => Expr::Not(Box::new(Expr::In { column, values })),
_ => Expr::Compare { column, op, value },
}
}
Expr::In { column, values } if M::DETERMINISTIC.contains(&column) => Expr::In {
column,
values: values
.iter()
.flat_map(|v| variants(v).unwrap_or_else(|| vec![v.clone()]))
.collect(),
},
Expr::And(a, b) => Expr::And(
Box::new(query_condition::<M>(*a)),
Box::new(query_condition::<M>(*b)),
),
Expr::Or(a, b) => Expr::Or(
Box::new(query_condition::<M>(*a)),
Box::new(query_condition::<M>(*b)),
),
Expr::Not(inner) => Expr::Not(Box::new(query_condition::<M>(*inner))),
other => other,
}
}
#[doc(hidden)]
pub trait Decrypted: Sized {
fn decrypted(stored: Option<String>) -> Result<Self>;
}
impl Decrypted for String {
fn decrypted(stored: Option<String>) -> Result<Self> {
stored
.map(|s| decrypt(&s))
.unwrap_or_else(|| Ok(String::new()))
}
}
impl Decrypted for Option<String> {
fn decrypted(stored: Option<String>) -> Result<Self> {
stored.map(|s| decrypt(&s)).transpose()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encrypts_and_rotates_keys() {
install("the old secret", &[]);
let old = encrypt("JBSWY3DPEHPK3PXP").unwrap();
assert!(old.starts_with("gl1:"));
assert!(!old.contains("JBSWY3DPEHPK3PXP"));
assert_ne!(
old,
encrypt("JBSWY3DPEHPK3PXP").unwrap(),
"a nonce each time"
);
assert_eq!(decrypt(&old).unwrap(), "JBSWY3DPEHPK3PXP");
install("the new secret", &["the old secret".to_owned()]);
assert_eq!(decrypt(&old).unwrap(), "JBSWY3DPEHPK3PXP");
let new = encrypt("x").unwrap();
install("the new secret", &[]);
assert_eq!(decrypt(&new).unwrap(), "x");
assert!(
decrypt(&old)
.unwrap_err()
.to_string()
.contains("previous_keys")
);
assert_eq!(decrypt("plain").unwrap(), "plain");
let mut bytes = STANDARD.decode(&new[PREFIX.len()..]).unwrap();
bytes[NONCE_LEN] ^= 1;
let tampered = format!("{PREFIX}{}", STANDARD.encode(bytes));
assert!(decrypt(&tampered).is_err());
}
}