1use crate::aead::{Sealed, open, seal};
13use crate::error::KeysError;
14use crate::kdf::{master_kek, service_key};
15use crate::key::Key32;
16use crate::password::{PasswordSealed, password_open, password_seal};
17use crate::profile::Profile;
18use crate::shards;
19use crate::words::to_words;
20use secrecy::{ExposeSecret, SecretString};
21use serde::{Deserialize, Serialize};
22use std::path::{Path, PathBuf};
23use zeroize::Zeroizing;
24
25pub trait KeyFiles {
28 type Error: From<KeysError>;
30
31 fn profile(&self) -> Profile {
34 Profile::WEIRDNET
35 }
36 fn home(&self) -> PathBuf;
38 fn envelope(&self) -> PathBuf;
39 fn service_keys_dir(&self) -> PathBuf;
40 fn prepare(&self) -> Result<(), Self::Error>;
42 fn ensure_dir(&self, dir: &Path) -> Result<(), Self::Error>;
43 fn write_private(&self, path: &Path, bytes: &[u8]) -> Result<(), Self::Error>;
45 fn read(&self, path: &Path) -> Result<Option<Vec<u8>>, Self::Error> {
47 match std::fs::read(path) {
48 Ok(b) => Ok(Some(b)),
49 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
50 Err(e) => Err(KeysError::Io(e).into()),
51 }
52 }
53 fn list(&self, dir: &Path) -> Result<Vec<PathBuf>, Self::Error> {
55 match std::fs::read_dir(dir) {
56 Ok(rd) => Ok(rd.flatten().map(|e| e.path()).filter(|p| p.is_file()).collect()),
57 Err(_) => Ok(vec![]),
58 }
59 }
60 fn remove(&self, path: &Path) -> Result<(), Self::Error> {
62 match std::fs::remove_file(path) {
63 Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(KeysError::Io(e).into()),
64 _ => Ok(()),
65 }
66 }
67}
68
69pub trait EncryptedDatabase: KeyFiles {
72 fn database_exists(&self) -> bool;
73 fn encrypt_plaintext(&self, dek: &Key32) -> Result<(), Self::Error>;
75 fn open_keyed(&self, dek: &Key32) -> Result<(), Self::Error>;
77 fn rekey_database(&self, old: &Key32, new: &Key32) -> Result<(), Self::Error>;
79 fn remove_database(&self);
81}
82
83fn now_ms() -> i64 {
84 std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0)
85}
86
87#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
88pub struct Envelope {
89 pub format: u32,
90 #[serde(default, skip_serializing_if = "Option::is_none")]
92 pub profile: Option<String>,
93 pub db_id: String,
94 pub created_at: i64,
95 pub service_version: u32,
96 pub service_wrap: Sealed,
98 pub master_wrap: Sealed,
100}
101
102#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
103pub struct ServiceKeyFile {
104 pub version: u32,
105 pub created_at: i64,
106 pub retired: bool,
107 pub wrapped: Option<PasswordSealed>,
109}
110
111fn utf8<E: From<KeysError>>(b: &[u8]) -> Result<&str, E> {
112 std::str::from_utf8(b).map_err(|_| KeysError::invalid("key file", "not UTF-8").into())
113}
114
115fn toml_of<T: Serialize, E: From<KeysError>>(v: &T) -> Result<String, E> {
116 toml::to_string_pretty(v).map_err(|e| KeysError::TomlSer(e).into())
117}
118
119fn from_toml<T: serde::de::DeserializeOwned, E: From<KeysError>>(b: &[u8]) -> Result<T, E> {
120 toml::from_str(utf8::<E>(b)?).map_err(|e| KeysError::TomlDe(e).into())
121}
122
123impl Envelope {
124 pub fn load<P: KeyFiles + ?Sized>(files: &P) -> Result<Option<Self>, P::Error> {
126 let Some(b) = files.read(&files.envelope())? else { return Ok(None) };
127 let env: Envelope = from_toml(&b)?;
128 let p = files.profile();
129 if env.format != p.envelope_format || env.profile.as_deref() != p.name {
130 return Err(KeysError::invalid(
131 "keys",
132 format!(
133 "the envelope is format {} ({}), but this application reads format {} ({}); nothing was changed",
134 env.format,
135 env.profile.as_deref().unwrap_or("no profile"),
136 p.envelope_format,
137 p.name.unwrap_or("no profile")
138 ),
139 )
140 .into());
141 }
142 Ok(Some(env))
143 }
144
145 pub fn require<P: KeyFiles + ?Sized>(files: &P) -> Result<Self, P::Error> {
146 Self::load(files)?.ok_or_else(|| KeysError::NotInitialized(files.home()).into())
147 }
148
149 pub fn save<P: KeyFiles + ?Sized>(&self, files: &P) -> Result<(), P::Error> {
150 files.write_private(&files.envelope(), toml_of::<_, P::Error>(self)?.as_bytes())
151 }
152}
153
154fn service_file<P: KeyFiles + ?Sized>(files: &P, v: u32) -> PathBuf {
155 files.service_keys_dir().join(format!("v{v}.toml"))
156}
157
158pub fn load_service_file<P: KeyFiles + ?Sized>(files: &P, v: u32) -> Result<ServiceKeyFile, P::Error> {
159 let p = service_file(files, v);
160 let b = files.read(&p)?.ok_or_else(|| KeysError::Unlock(format!("service key v{v} is missing ({})", p.display())))?;
161 from_toml(&b)
162}
163
164pub fn service_files<P: KeyFiles + ?Sized>(files: &P) -> Result<Vec<ServiceKeyFile>, P::Error> {
165 let mut v = Vec::new();
166 for p in files.list(&files.service_keys_dir())? {
167 if p.extension().is_some_and(|x| x == "toml")
168 && let Some(b) = files.read(&p)?
169 {
170 v.push(from_toml::<ServiceKeyFile, P::Error>(&b)?);
171 }
172 }
173 v.sort_by_key(|f| f.version);
174 Ok(v)
175}
176
177fn write_service_file<P: KeyFiles + ?Sized>(files: &P, db_id: &str, v: u32, key: &Key32, password: &SecretString) -> Result<(), P::Error> {
178 let aad = files.profile().service_key_aad(db_id, v);
179 let f = ServiceKeyFile { version: v, created_at: now_ms(), retired: false, wrapped: Some(password_seal(password, &key.0, &aad)?) };
180 files.write_private(&service_file(files, v), toml_of::<_, P::Error>(&f)?.as_bytes())
181}
182
183fn retire_service_file<P: KeyFiles + ?Sized>(files: &P, v: u32) -> Result<(), P::Error> {
184 if let Ok(mut f) = load_service_file(files, v) {
185 f.retired = true;
186 f.wrapped = None;
187 files.write_private(&service_file(files, v), toml_of::<_, P::Error>(&f)?.as_bytes())?;
188 }
189 Ok(())
190}
191
192pub struct InitOutput {
194 pub db_id: String,
195 pub words: Zeroizing<String>,
196 pub shards: Vec<Zeroizing<String>>,
197 pub migrated_plain_db: bool,
198}
199
200pub fn init<P: EncryptedDatabase + ?Sized>(files: &P, password: &SecretString) -> Result<InitOutput, P::Error> {
202 if files.read(&files.envelope())?.is_some() {
203 return Err(KeysError::invalid("keys", format!("already initialized ({})", files.envelope().display())).into());
204 }
205 if password.expose_secret().is_empty() {
208 return Err(KeysError::invalid("password", "must not be empty").into());
209 }
210 let profile = files.profile();
211 files.prepare()?;
212 let master = Key32::random()?;
213 let dek = Key32::random()?;
214 let db_id = uuid::Uuid::new_v4().to_string();
215 let svc = service_key(&profile, &master, &db_id, 1)?;
216 let kek = master_kek(&profile, &master, &db_id)?;
217
218 let mut migrated = false;
220 if files.database_exists() {
221 files.encrypt_plaintext(&dek)?;
222 migrated = true;
223 }
224 files.open_keyed(&dek)?;
225
226 let finish = || -> Result<(), P::Error> {
227 write_service_file(files, &db_id, 1, &svc, password)?;
228 let env = Envelope {
229 format: profile.envelope_format,
230 profile: profile.name.map(str::to_string),
231 db_id: db_id.clone(),
232 created_at: now_ms(),
233 service_version: 1,
234 service_wrap: seal(&svc, &dek.0, &profile.dek_aad())?,
235 master_wrap: seal(&kek, &dek.0, &profile.dek_aad())?,
236 };
237 env.save(files)
238 };
239 if let Err(e) = finish() {
240 if !migrated {
242 files.remove_database();
243 }
244 let _ = files.remove(&service_file(files, 1));
245 return Err(e);
246 }
247 Ok(InitOutput {
248 db_id,
249 words: to_words(&master)?,
250 shards: shards::split(&profile, &master, shards::THRESHOLD, shards::COUNT)?,
251 migrated_plain_db: migrated,
252 })
253}
254
255pub fn unlock_with_password<P: KeyFiles + ?Sized>(files: &P, password: &SecretString) -> Result<Key32, P::Error> {
257 let profile = files.profile();
258 let env = Envelope::require(files)?;
259 let f = load_service_file(files, env.service_version)?;
260 let w = f.wrapped.ok_or_else(|| KeysError::Unlock("current service key is retired".into()))?;
261 let svc = Key32::from_slice(&password_open(password, &w, &profile.service_key_aad(&env.db_id, env.service_version))?)?;
262 Ok(Key32::from_slice(&open(&svc, &env.service_wrap, &profile.dek_aad())?)?)
263}
264
265fn dek_from_master(profile: &Profile, env: &Envelope, master: &Key32) -> crate::Result<Key32> {
266 let kek = master_kek(profile, master, &env.db_id)?;
267 Key32::from_slice(
268 &open(&kek, &env.master_wrap, &profile.dek_aad()).map_err(|_| KeysError::Unlock("master key does not match this database".into()))?,
269 )
270}
271
272pub fn unlock_with_master<P: KeyFiles + ?Sized>(files: &P, master: &Key32) -> Result<Key32, P::Error> {
274 let env = Envelope::require(files)?;
275 Ok(dek_from_master(&files.profile(), &env, master)?)
276}
277
278pub fn rotate<P: KeyFiles + ?Sized>(files: &P, master: &Key32, password: &SecretString) -> Result<u32, P::Error> {
282 let profile = files.profile();
283 let mut env = Envelope::require(files)?;
284 let dek = dek_from_master(&profile, &env, master)?;
285 let old = env.service_version;
286 let new = old.checked_add(1).ok_or_else(|| KeysError::invalid("keys", "no service key versions left"))?;
287 let svc = service_key(&profile, master, &env.db_id, new)?;
288 write_service_file(files, &env.db_id, new, &svc, password)?;
289 env.service_version = new;
290 env.service_wrap = seal(&svc, &dek.0, &profile.dek_aad())?;
291 env.save(files)?;
292 retire_service_file(files, old)?;
293 Ok(new)
294}
295
296pub fn rekey<P: EncryptedDatabase + ?Sized>(files: &P, master: &Key32) -> Result<(), P::Error> {
300 let profile = files.profile();
301 let mut env = Envelope::require(files)?;
302 let old = dek_from_master(&profile, &env, master)?;
303 let new = Key32::random()?;
304 let svc = service_key(&profile, master, &env.db_id, env.service_version)?;
305 let kek = master_kek(&profile, master, &env.db_id)?;
306 env.service_wrap = seal(&svc, &new.0, &profile.dek_aad())?;
307 env.master_wrap = seal(&kek, &new.0, &profile.dek_aad())?;
308 files.rekey_database(&old, &new)?;
309 let commit = || -> Result<(), P::Error> {
310 files.open_keyed(&new)?;
311 env.save(files)
312 };
313 if let Err(e) = commit() {
314 if files.rekey_database(&new, &old).is_err() {
315 return Err(KeysError::crypto(
316 "rekey failed after the database was re-encrypted, and undoing it failed too; the database is keyed with a key that is no longer stored — restore it from a backup",
317 )
318 .into());
319 }
320 return Err(e);
321 }
322 Ok(())
323}
324
325pub fn recover<P: KeyFiles + ?Sized>(files: &P, master: &Key32, new_password: &SecretString) -> Result<(), P::Error> {
327 let profile = files.profile();
328 let env = Envelope::require(files)?;
329 dek_from_master(&profile, &env, master)?;
330 let svc = service_key(&profile, master, &env.db_id, env.service_version)?;
331 write_service_file(files, &env.db_id, env.service_version, &svc, new_password)
332}
333
334pub fn verify_master<P: KeyFiles + ?Sized>(files: &P, master: &Key32) -> Result<(), P::Error> {
336 unlock_with_master(files, master).map(|_| ())
337}
338
339pub fn recover_master<P: KeyFiles + ?Sized>(files: &P, texts: &[String]) -> Result<Key32, P::Error> {
341 let m = shards::combine(&files.profile(), texts)?;
342 verify_master(files, &m)?;
343 Ok(m)
344}
345
346#[derive(Debug, Clone, Copy, PartialEq, Eq)]
347pub enum ExportItem {
348 Master,
349 Words,
350 Service,
351 Shards,
352}
353
354impl ExportItem {
355 pub const ALL: [ExportItem; 4] = [ExportItem::Master, ExportItem::Words, ExportItem::Service, ExportItem::Shards];
356
357 pub fn from_name(s: &str) -> Option<Self> {
359 match s.trim().to_ascii_lowercase().as_str() {
360 "master" => Some(Self::Master),
361 "words" => Some(Self::Words),
362 "service" | "service-keys" => Some(Self::Service),
363 "shards" => Some(Self::Shards),
364 _ => None,
365 }
366 }
367}
368
369#[cfg(feature = "age")]
373pub fn export<P: KeyFiles + ?Sized>(
374 files: &P,
375 master: &Key32,
376 password: &SecretString,
377 out: &Path,
378 items: &[ExportItem],
379) -> Result<Vec<PathBuf>, P::Error> {
380 use crate::agefile;
381 verify_master(files, master)?;
382 files.ensure_dir(out)?;
383 let profile = files.profile();
384 let mut written = Vec::new();
385 let mut run = || -> Result<(), P::Error> {
386 let mut put = |name: &str, data: &[u8]| -> Result<(), P::Error> {
387 let p = out.join(name);
388 let existed = files.read(&p)?.is_some();
389 files.write_private(&p, &agefile::encrypt(password, data)?)?;
390 written.push((p, existed));
391 Ok(())
392 };
393 for it in items {
394 match it {
395 ExportItem::Master => put("master.key.age", master.hex().as_bytes())?,
396 ExportItem::Words => put("words.txt.age", to_words(master)?.as_bytes())?,
397 ExportItem::Service => {
398 let env = Envelope::require(files)?;
399 let j = serde_json::json!({ "envelope": env, "service_keys": service_files(files)? });
400 put("service-keys.json.age", serde_json::to_string_pretty(&j).map_err(KeysError::from)?.as_bytes())?
401 }
402 ExportItem::Shards => {
403 for (i, s) in shards::split(&profile, master, shards::THRESHOLD, shards::COUNT)?.iter().enumerate() {
404 put(&format!("shard-{}.age", i + 1), s.as_bytes())?;
405 }
406 }
407 }
408 }
409 Ok(())
410 };
411 if let Err(e) = run() {
412 for (p, existed) in &written {
413 if !existed {
414 let _ = files.remove(p);
415 }
416 }
417 return Err(e);
418 }
419 Ok(written.into_iter().map(|(p, _)| p).collect())
420}
421
422#[cfg(feature = "age")]
425pub fn read_maybe_age<E: From<KeysError>>(path: &Path, password: impl FnOnce() -> Result<SecretString, E>) -> Result<Zeroizing<String>, E> {
426 use crate::agefile;
427 let b = Zeroizing::new(std::fs::read(path).map_err(KeysError::from)?);
428 let plain = if agefile::is_age(&b) { agefile::decrypt(&password()?, &b)? } else { Zeroizing::new(b.to_vec()) };
429 Ok(Zeroizing::new(String::from_utf8_lossy(&plain).trim().to_string()))
430}
431
432#[cfg(test)]
433mod tests;