1use std::fmt;
4use std::fs;
5use std::io::Write;
6use std::path::Path;
7use std::sync::atomic::{AtomicU64, Ordering};
8
9use nibkeep_base::cbor::{self, FromCbor, ToCbor, Value};
10use nibkeep_crypto::rand_core::CryptoRng;
11use nibkeep_crypto::{Envelope, Key, PassphraseParams};
12use zeroize::Zeroizing;
13
14use crate::{KeysError, ReplicaKeys, SecretsKeys};
15
16const SUITE: u8 = 1;
18
19const REPLICA: &str = "nibkeep key file: replica";
21
22const SECRETS: &str = "nibkeep key file: secrets";
24
25static WRITES: AtomicU64 = AtomicU64::new(0);
27
28#[derive(Clone, PartialEq, Eq)]
30pub enum Protection {
31 Passphrase {
33 params: PassphraseParams,
35 salt: [u8; 16],
37 },
38 Keystore {
41 service: String,
43 account: String,
45 },
46}
47
48impl fmt::Debug for Protection {
49 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50 match self {
51 Self::Passphrase { params, .. } => f
52 .debug_struct("Passphrase")
53 .field("params", params)
54 .finish_non_exhaustive(),
55 Self::Keystore { service, account } => f
56 .debug_struct("Keystore")
57 .field("service", service)
58 .field("account", account)
59 .finish(),
60 }
61 }
62}
63
64#[derive(Clone, Copy)]
66pub enum NewProtection<'a> {
67 Passphrase(&'a str, PassphraseParams),
69 Keystore {
72 service: &'a str,
74 },
75}
76
77impl fmt::Debug for NewProtection<'_> {
78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 match self {
80 Self::Passphrase(_, params) => f.debug_tuple("Passphrase").field(params).finish(),
81 Self::Keystore { service } => f
82 .debug_struct("Keystore")
83 .field("service", service)
84 .finish(),
85 }
86 }
87}
88
89#[derive(Clone, Copy)]
91pub enum Unlocker<'a> {
92 Passphrase(&'a str),
94 Keystore,
97}
98
99impl fmt::Debug for Unlocker<'_> {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 f.write_str(match self {
102 Self::Passphrase(_) => "Passphrase(..)",
103 Self::Keystore => "Keystore",
104 })
105 }
106}
107
108#[derive(Clone)]
112pub struct CompartmentKey(Key);
113
114impl fmt::Debug for CompartmentKey {
115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116 f.write_str("CompartmentKey(..)")
117 }
118}
119
120#[derive(Clone, Debug, PartialEq, Eq)]
121struct Compartment {
122 protection: Protection,
123 envelope: Envelope,
124}
125
126#[derive(Debug)]
131pub struct SealedSecrets(Option<Compartment>);
132
133impl SealedSecrets {
134 pub fn seal(
142 keys: &SecretsKeys,
143 protection: &NewProtection<'_>,
144 rng: &mut impl CryptoRng,
145 ) -> Result<(Self, CompartmentKey), KeysError> {
146 let (compartment, key) = Compartment::seal(&keys.encode(), SECRETS, protection, rng)?;
147 Ok((Self(Some(compartment)), key))
148 }
149
150 pub fn update(
156 &mut self,
157 keys: &SecretsKeys,
158 key: &CompartmentKey,
159 rng: &mut impl CryptoRng,
160 ) -> Result<(), KeysError> {
161 self.0
162 .as_mut()
163 .ok_or(KeysError::NoSecrets)?
164 .reseal(&keys.encode(), SECRETS, key, rng)
165 }
166
167 #[must_use]
169 pub fn protection(&self) -> Option<&Protection> {
170 self.0.as_ref().map(|compartment| &compartment.protection)
171 }
172}
173
174impl Drop for SealedSecrets {
175 fn drop(&mut self) {
176 if let Some(Compartment {
177 protection: Protection::Keystore { service, account },
178 ..
179 }) = self.0.take()
180 {
181 let _ = keyring_core::Entry::new(&service, &account)
182 .and_then(|entry| entry.delete_credential());
183 }
184 }
185}
186
187#[derive(Clone, Debug)]
194pub struct KeyFile {
195 replica: Compartment,
196 secrets: Option<Compartment>,
197 obsolete: Vec<(String, String)>,
200}
201
202impl PartialEq for KeyFile {
203 fn eq(&self, other: &Self) -> bool {
204 self.replica == other.replica && self.secrets == other.secrets
205 }
206}
207
208impl Eq for KeyFile {}
209
210impl KeyFile {
211 pub fn create(
218 replica: &ReplicaKeys,
219 protection: &NewProtection<'_>,
220 rng: &mut impl CryptoRng,
221 ) -> Result<(Self, CompartmentKey), KeysError> {
222 let (compartment, key) = Compartment::seal(&replica.encode(), REPLICA, protection, rng)?;
223 let file = Self {
224 replica: compartment,
225 secrets: None,
226 obsolete: Vec::new(),
227 };
228 Ok((file, key))
229 }
230
231 #[must_use]
233 pub fn replica_protection(&self) -> &Protection {
234 &self.replica.protection
235 }
236
237 #[must_use]
239 pub fn secrets_protection(&self) -> Option<&Protection> {
240 self.secrets.as_ref().map(|secrets| &secrets.protection)
241 }
242
243 pub fn unlock_replica(&self, unlocker: &Unlocker<'_>) -> Result<CompartmentKey, KeysError> {
249 self.replica.unlock(REPLICA, unlocker)
250 }
251
252 pub fn replica(&self, key: &CompartmentKey) -> Result<ReplicaKeys, KeysError> {
258 ReplicaKeys::decode(&self.replica.open(REPLICA, key)?)
259 }
260
261 pub fn set_replica(
267 &mut self,
268 keys: &ReplicaKeys,
269 key: &CompartmentKey,
270 rng: &mut impl CryptoRng,
271 ) -> Result<(), KeysError> {
272 self.replica.reseal(&keys.encode(), REPLICA, key, rng)
273 }
274
275 pub fn protect_replica(
284 &mut self,
285 key: &CompartmentKey,
286 protection: &NewProtection<'_>,
287 rng: &mut impl CryptoRng,
288 ) -> Result<CompartmentKey, KeysError> {
289 let contents = self.replica.open(REPLICA, key)?;
290 let (compartment, new_key) = Compartment::seal(&contents, REPLICA, protection, rng)?;
291 let old = std::mem::replace(&mut self.replica, compartment);
292 self.retire(old);
293 Ok(new_key)
294 }
295
296 pub fn set_secrets(
304 &mut self,
305 keys: &SecretsKeys,
306 protection: &NewProtection<'_>,
307 rng: &mut impl CryptoRng,
308 ) -> Result<CompartmentKey, KeysError> {
309 let (compartment, key) = Compartment::seal(&keys.encode(), SECRETS, protection, rng)?;
310 if let Some(old) = self.secrets.replace(compartment) {
311 self.retire(old);
312 }
313 Ok(key)
314 }
315
316 pub fn unlock_secrets(&self, unlocker: &Unlocker<'_>) -> Result<CompartmentKey, KeysError> {
324 self.secrets
325 .as_ref()
326 .ok_or(KeysError::NoSecrets)?
327 .unlock(SECRETS, unlocker)
328 }
329
330 pub fn secrets(&self, key: &CompartmentKey) -> Result<SecretsKeys, KeysError> {
336 let secrets = self.secrets.as_ref().ok_or(KeysError::NoSecrets)?;
337 SecretsKeys::decode(&secrets.open(SECRETS, key)?)
338 }
339
340 pub fn secrets_key_lost(&self) -> Result<bool, KeysError> {
349 let Some(Protection::Keystore { service, account }) = self.secrets_protection() else {
350 return Ok(false);
351 };
352 match keyring_core::Entry::new(service, account)?.get_attributes() {
353 Ok(_) => Ok(false),
354 Err(keyring_core::Error::NoEntry) => Ok(true),
355 Err(error) => Err(error.into()),
356 }
357 }
358
359 pub fn update_secrets(
365 &mut self,
366 keys: &SecretsKeys,
367 key: &CompartmentKey,
368 rng: &mut impl CryptoRng,
369 ) -> Result<(), KeysError> {
370 self.secrets
371 .as_mut()
372 .ok_or(KeysError::NoSecrets)?
373 .reseal(&keys.encode(), SECRETS, key, rng)
374 }
375
376 pub fn read(path: &Path) -> Result<Self, KeysError> {
382 let bytes = fs::read(path)?;
383 cbor::from_slice(&bytes).map_err(|error| KeysError::Damaged(error.to_string()))
384 }
385
386 pub fn write(&mut self, path: &Path) -> Result<(), KeysError> {
396 let name = path
397 .file_name()
398 .map_or_else(|| "keys".into(), |name| name.to_string_lossy());
399 let temporary = path.with_file_name(format!(
400 ".{name}.{}.{}.tmp",
401 std::process::id(),
402 WRITES.fetch_add(1, Ordering::Relaxed)
403 ));
404 let written =
405 write_new(&temporary, &cbor::to_vec(self)).and_then(|()| fs::rename(&temporary, path));
406 if let Err(error) = written {
407 let _ = fs::remove_file(&temporary);
408 return Err(error.into());
409 }
410 #[cfg(unix)]
413 {
414 let directory = path
415 .parent()
416 .filter(|directory| !directory.as_os_str().is_empty())
417 .unwrap_or_else(|| Path::new("."));
418 let _ = fs::File::open(directory).and_then(|directory| directory.sync_all());
419 }
420 self.obsolete.retain(|(service, account)| {
421 let deleted = keyring_core::Entry::new(service, account)
422 .and_then(|entry| entry.delete_credential());
423 matches!(deleted, Err(error) if !matches!(error, keyring_core::Error::NoEntry))
424 });
425 Ok(())
426 }
427
428 pub fn discard(self) {
432 let entries = [Some(self.replica), self.secrets]
433 .into_iter()
434 .flatten()
435 .filter_map(|compartment| match compartment.protection {
436 Protection::Keystore { service, account } => Some((service, account)),
437 Protection::Passphrase { .. } => None,
438 })
439 .chain(self.obsolete);
440 for (service, account) in entries {
441 let _ = keyring_core::Entry::new(&service, &account)
442 .and_then(|entry| entry.delete_credential());
443 }
444 }
445
446 pub fn put_secrets(&mut self, mut sealed: SealedSecrets) {
449 if let Some(new) = sealed.0.take()
450 && let Some(old) = self.secrets.replace(new)
451 {
452 self.retire(old);
453 }
454 }
455
456 pub fn remove_secrets(&mut self) {
460 if let Some(old) = self.secrets.take() {
461 self.retire(old);
462 }
463 }
464
465 pub fn discard_secrets(&mut self) {
468 if let Some(Compartment {
469 protection: Protection::Keystore { service, account },
470 ..
471 }) = self.secrets.take()
472 {
473 let _ = keyring_core::Entry::new(&service, &account)
474 .and_then(|entry| entry.delete_credential());
475 }
476 }
477
478 pub fn restore(&mut self, before: Self) {
484 let uses = |(service, account): &(String, String)| {
485 [Some(&before.replica), before.secrets.as_ref()]
486 .into_iter()
487 .flatten()
488 .any(|compartment| {
489 matches!(&compartment.protection, Protection::Keystore { service: s, account: a }
490 if s == service && a == account)
491 })
492 };
493 let mut pending: Vec<(String, String)> = std::mem::take(&mut self.obsolete)
494 .into_iter()
495 .filter(|entry| !uses(entry))
496 .collect();
497 let changed = |now: Option<&Compartment>, then: Option<&Compartment>| match now {
498 Some(Compartment {
499 protection: Protection::Keystore { service, account },
500 ..
501 }) if now.map(|now| &now.protection) != then.map(|then| &then.protection) => {
502 Some((service.clone(), account.clone()))
503 }
504 _ => None,
505 };
506 let made = [
507 changed(Some(&self.replica), Some(&before.replica)),
508 changed(self.secrets.as_ref(), before.secrets.as_ref()),
509 ];
510 for (service, account) in made.into_iter().flatten() {
511 let _ = keyring_core::Entry::new(&service, &account)
512 .and_then(|entry| entry.delete_credential());
513 }
514 *self = before;
515 pending.retain(|entry| !self.obsolete.contains(entry));
516 self.obsolete.append(&mut pending);
517 }
518
519 pub fn take_obsolete(&mut self, older: &mut Self) {
522 self.obsolete.append(&mut older.obsolete);
523 }
524
525 fn retire(&mut self, old: Compartment) {
528 if let Protection::Keystore { service, account } = old.protection {
529 self.obsolete.push((service, account));
530 }
531 }
532}
533
534fn write_new(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
536 let mut options = fs::OpenOptions::new();
537 options.write(true).create_new(true);
538 #[cfg(unix)]
539 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
540 let mut file = options.open(path)?;
541 file.write_all(bytes)?;
542 file.sync_all()
543}
544
545impl Compartment {
546 fn seal(
548 contents: &[u8],
549 name: &str,
550 protection: &NewProtection<'_>,
551 rng: &mut impl CryptoRng,
552 ) -> Result<(Self, CompartmentKey), KeysError> {
553 let (protection, key) = match *protection {
554 NewProtection::Passphrase(passphrase, params) => {
555 let mut salt = [0; 16];
556 rng.fill_bytes(&mut salt);
557 let key = Key::from_passphrase(passphrase, &salt, ¶ms)?;
558 (Protection::Passphrase { params, salt }, key)
559 }
560 NewProtection::Keystore { service } => {
561 let mut suffix = [0; 8];
563 rng.fill_bytes(&mut suffix);
564 let account = format!("nibkeep-{:016x}", u64::from_be_bytes(suffix));
565 let key = Key::generate(rng);
566 keyring_core::Entry::new(service, &account)?.set_secret(key.expose_bytes())?;
567 let protection = Protection::Keystore {
568 service: service.to_owned(),
569 account,
570 };
571 (protection, key)
572 }
573 };
574 let envelope = Envelope::seal(&key, contents, &associated_data(name, &protection), rng);
575 Ok((
576 Self {
577 protection,
578 envelope,
579 },
580 CompartmentKey(key),
581 ))
582 }
583
584 fn unlock(&self, name: &str, unlocker: &Unlocker<'_>) -> Result<CompartmentKey, KeysError> {
587 let key = match (&self.protection, unlocker) {
588 (Protection::Passphrase { params, salt }, Unlocker::Passphrase(passphrase)) => {
589 Key::from_passphrase(passphrase, salt, params)?
590 }
591 (Protection::Keystore { service, account }, Unlocker::Keystore) => {
592 let secret =
593 Zeroizing::new(keyring_core::Entry::new(service, account)?.get_secret()?);
594 Key::from_slice(&secret).ok_or(KeysError::WrongKey)?
595 }
596 _ => return Err(KeysError::WrongUnlocker),
597 };
598 let key = CompartmentKey(key);
599 self.open(name, &key)?;
600 Ok(key)
601 }
602
603 fn open(&self, name: &str, key: &CompartmentKey) -> Result<Zeroizing<Vec<u8>>, KeysError> {
605 self.envelope
606 .open(&key.0, &associated_data(name, &self.protection))
607 .map_err(|_| match self.protection {
608 Protection::Passphrase { .. } => KeysError::WrongPassphrase,
609 Protection::Keystore { .. } => KeysError::WrongKey,
610 })
611 }
612
613 fn reseal(
615 &mut self,
616 contents: &[u8],
617 name: &str,
618 key: &CompartmentKey,
619 rng: &mut impl CryptoRng,
620 ) -> Result<(), KeysError> {
621 self.open(name, key)?;
622 self.envelope = Envelope::seal(
623 &key.0,
624 contents,
625 &associated_data(name, &self.protection),
626 rng,
627 );
628 Ok(())
629 }
630}
631
632fn associated_data(name: &str, protection: &Protection) -> Vec<u8> {
635 cbor::encode(&Value::Array(vec![name.to_cbor(), protection.to_cbor()]))
636}
637
638impl ToCbor for KeyFile {
639 fn to_cbor(&self) -> Value {
640 let mut items = vec![SUITE.to_cbor(), self.replica.to_cbor()];
641 if let Some(secrets) = &self.secrets {
642 items.push(secrets.to_cbor());
643 }
644 Value::Array(items)
645 }
646}
647
648impl FromCbor for KeyFile {
649 fn from_cbor(value: &Value) -> Result<Self, cbor::Error> {
650 const EXPECTED: &str = "a key file: [1, replica] or [1, replica, secrets]";
651 let Value::Array(items) = value else {
652 return Err(cbor::Error::Expected(EXPECTED));
653 };
654 let (suite, replica, secrets) = match items.as_slice() {
655 [suite, replica] => (suite, replica, None),
656 [suite, replica, secrets] => (suite, replica, Some(secrets)),
657 _ => return Err(cbor::Error::Expected(EXPECTED)),
658 };
659 if u8::from_cbor(suite) != Ok(SUITE) {
660 return Err(cbor::Error::Expected(EXPECTED));
661 }
662 Ok(Self {
663 replica: Compartment::from_cbor(replica)?,
664 secrets: secrets.map(Compartment::from_cbor).transpose()?,
665 obsolete: Vec::new(),
666 })
667 }
668}
669
670impl ToCbor for Protection {
671 fn to_cbor(&self) -> Value {
672 match self {
673 Self::Passphrase { params, salt } => Value::Array(vec![
674 0_u8.to_cbor(),
675 params.to_cbor(),
676 Value::Bytes(salt.to_vec()),
677 ]),
678 Self::Keystore { service, account } => {
679 Value::Array(vec![1_u8.to_cbor(), service.to_cbor(), account.to_cbor()])
680 }
681 }
682 }
683}
684
685impl FromCbor for Protection {
686 fn from_cbor(value: &Value) -> Result<Self, cbor::Error> {
687 const EXPECTED: &str = "a protection: [0, parameters, salt] or [1, service, account]";
688 let error = || cbor::Error::Expected(EXPECTED);
689 let Value::Array(items) = value else {
690 return Err(error());
691 };
692 match items.as_slice() {
693 [kind, params, Value::Bytes(salt)] if u8::from_cbor(kind) == Ok(0) => {
694 Ok(Self::Passphrase {
695 params: PassphraseParams::from_cbor(params)?,
696 salt: salt.as_slice().try_into().map_err(|_| error())?,
697 })
698 }
699 [kind, service, account] if u8::from_cbor(kind) == Ok(1) => Ok(Self::Keystore {
700 service: String::from_cbor(service)?,
701 account: String::from_cbor(account)?,
702 }),
703 _ => Err(error()),
704 }
705 }
706}
707
708impl ToCbor for Compartment {
709 fn to_cbor(&self) -> Value {
710 Value::Array(vec![self.protection.to_cbor(), self.envelope.to_cbor()])
711 }
712}
713
714impl FromCbor for Compartment {
715 fn from_cbor(value: &Value) -> Result<Self, cbor::Error> {
716 const EXPECTED: &str = "a compartment: [protection, envelope]";
717 let Value::Array(items) = value else {
718 return Err(cbor::Error::Expected(EXPECTED));
719 };
720 let [protection, envelope] = items.as_slice() else {
721 return Err(cbor::Error::Expected(EXPECTED));
722 };
723 Ok(Self {
724 protection: Protection::from_cbor(protection)?,
725 envelope: Envelope::from_cbor(envelope)?,
726 })
727 }
728}