Repository navigation
Expand file tree
/
Copy pathmint.rs
More file actions
2670 lines (2504 loc) · 98 KB
/
Copy pathmint.rs
File metadata and controls
2670 lines (2504 loc) · 98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The sign-in reference that a box with a GitHub grant carries, and the
//! box's registration with the Box Egress Proxy (BEP-003, BEP-005).
//!
//! On a host that is not enrolled, `min` mints one member for each GitHub
//! grant when it creates the box. The member is a sign-in reference: a
//! handle in the store-handle wire format ([`bep::handle`]), signed under
//! the client's key. The handle names the held sign-in item by the module
//! and the item's instance identifier. It carries the module's authorities
//! as its upstream set and no injection form, and it expires when the
//! proxy's root CA does. It carries no token. The proxy resolves the
//! reference against the sign-in item at each request.
//!
//! A store reference is a handle of the same wire format, signed under the
//! same key: the store, the item's identifier, the rule's registered
//! authorities and injection form, and the root CA's validity end as its
//! expiry ([`mint_store_handle`], BEP-063).
//!
//! The client's key is registered with the proxy over the proxy's control
//! socket before any handle signed under it leaves this process (BEP-063).
//! The proxy keeps the registration across its restarts. The target is one
//! local key that a [`ClientKeyStore`] keeps. When the store refuses this
//! program that key, [`local_client_key`] replaces it. The proxy registers
//! the replacement first. After the store keeps the replacement, the proxy
//! revokes every other client key, so no handle signed under the refused
//! key verifies again. A revoke that fails is retried at the next creation.
//!
//! Box creation reads that key from the host keychain
//! ([`HostClientKeyStore`]), so every creation signs under one key and the
//! proxy keeps one registration for this client.
//! Box creation seals each store handle as a `store` member, one sealed
//! value for each store reference that a rule accepts
//! ([`mint_store_members`], BEP-032).
//!
//! A mint refuses a root CA whose validity ended: every handle minted under
//! it would be expired already.
//!
//! The member is sealed from the proxy's published identity
//! ([`bep::publish`]): sealing is public-key work, so a mint never opens the
//! proxy's key store. The Box Host a value binds is the fingerprint of the
//! proxy's sealing key, which is the name `bep serve` redeems under.
//!
//! The same control socket then registers the box with its declared egress
//! and its address stance, so the proxy admits the box's requests to those
//! authorities. Last, it records one `mint` record per member in the
//! proxy's audit log, the log the proxy's decisions go to (BEP-067).
use std::fmt;
use std::io::{self, BufRead as _, BufReader, Write as _};
use std::os::unix::net::UnixStream;
use std::path::{Path, PathBuf};
use std::time::Duration;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use bep::boxes::Stance;
use bep::control::{Reply, Request};
use bep::handle::{self, Claims, StoreRule};
use bep::module::{GITHUB, Module};
use bep::publish::{Identity, PublishError};
use bep::seal::{Breadth, Context, Member, MemberKind, MemberList, Mode};
use bep::signin::{Keychain, SignInError};
use p256::ecdsa::SigningKey;
use zeroize::{Zeroize as _, Zeroizing};
/// How long a control socket request waits for the proxy.
const CONTROL_TIMEOUT: Duration = Duration::from_secs(10);
/// How long the forget of a failed creation waits for the proxy. It is
/// short, so a stuck proxy does not hold up the end of the creation.
const FORGET_TIMEOUT: Duration = Duration::from_secs(2);
/// What a refused client key registration names, in [`MintError::Refused`].
const CLIENT_KEY: &str = "this client's signing key";
/// `~/.minimal/bep/identity.json`, where the proxy publishes its keys.
#[must_use]
pub fn identity_path() -> Option<PathBuf> {
std::env::home_dir().map(|home| home.join(".minimal/bep/identity.json"))
}
/// `~/.minimal/bep/control.sock`, the proxy's control socket.
#[must_use]
pub fn control_path() -> Option<PathBuf> {
std::env::home_dir().map(|home| home.join(".minimal/bep/control.sock"))
}
/// Why a box's members were not minted, or the box was not registered.
#[derive(Debug)]
pub enum MintError {
/// The host keychain did not give the sign-in item's metadata.
SignIn(SignInError),
/// No GitHub sign-in is held.
NoSignIn,
/// The proxy's published identity was not read, or is not usable.
Identity {
/// The identity file.
path: PathBuf,
/// Why.
error: PublishError,
},
/// Nothing answers on the control socket.
NotRunning {
/// The control socket.
path: PathBuf,
/// Why.
error: io::Error,
},
/// The control socket connection failed during a request.
Control(io::Error),
/// The proxy refused a request.
Refused {
/// What was asked.
what: &'static str,
/// The proxy's reason.
error: String,
},
/// The box id is not 32 hex digits or a UUID.
BoxId(String),
/// The host has no random source for the client key or the handle id.
Random,
/// The root CA's validity ended at or before the mint.
RootExpired,
/// The client key store failed for a reason other than a refusal.
KeyStore(String),
/// The proxy holds its bound of client keys, and running boxes use each
/// one, so it refused this client's key.
KeysInUse {
/// The proxy's bound.
max: usize,
},
/// The rule is read from a `min --config-dir` override, and the files
/// that `bep serve` reads hold no rule for the item, so it would not
/// redeem the handle.
RuleNotRead {
/// The rule's item identifier.
id: String,
/// The client configuration that `bep serve` reads.
bep_config: PathBuf,
/// The `--config-dir` override.
config_dir: PathBuf,
},
/// A configuration file that `bep serve` reads store rules from does
/// not read, so `bep serve` holds no store rules at all.
BepConfigUnread {
/// The rule's item identifier.
id: String,
/// The file that does not read.
file: PathBuf,
/// Why it does not read.
error: String,
},
/// `bep serve` refuses its own rule for the item when it reads it.
BepRuleRefused {
/// The rule's item identifier.
id: String,
/// The refusal, which names its file.
refusal: String,
},
/// The rules that `bep serve` reads give the item a `deny` action.
BepRuleDenied {
/// The rule's item identifier.
id: String,
/// The files that `bep serve` reads store rules from.
files: String,
},
/// `bep serve` holds a rule for the item in another form.
BepRuleDiffers {
/// The rule's item identifier.
id: String,
/// The files that `bep serve` reads store rules from.
files: String,
/// The rule fields that differ, as the configuration names them.
fields: Vec<&'static str>,
},
}
impl fmt::Display for MintError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.write_for(f, false)
}
}
/// A [`MintError`] for a box whose only proxy-served secrets are
/// `source = "store"` references. Its text names those secrets, not a
/// GitHub grant. Every other variant prints as [`MintError`] prints it.
#[derive(Debug)]
pub struct StoreOnlyMintError(pub MintError);
impl fmt::Display for StoreOnlyMintError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.write_for(f, true)
}
}
impl std::error::Error for StoreOnlyMintError {}
impl MintError {
/// The error's text. `stored` says the box declares store references
/// only, so the text names no GitHub grant.
fn write_for(&self, f: &mut fmt::Formatter<'_>, stored: bool) -> fmt::Result {
let declares = if stored {
"a secret from the host's secret store"
} else {
"a GitHub grant"
};
match self {
Self::SignIn(error) => write!(
f,
"Cannot start the box: the GitHub sign-in was not read from the host keychain: {error}"
),
// The same text as the refusal at creation (BEP-003).
Self::NoSignIn => write!(
f,
"{}",
boxes::core::bep::BepRefusal::SignInRequired { grants: Vec::new() }
),
Self::Identity {
path,
error: PublishError::Io { source, .. },
} if source.kind() == io::ErrorKind::NotFound => write!(
f,
"Cannot start the box: it declares {declares}, and the Box Egress Proxy \
has not published its keys at {}.",
path.display()
),
Self::Identity { error, .. } => {
write!(f, "Cannot start the box: it declares {declares}. {error}")
}
Self::NotRunning { path, error } => write!(
f,
"Cannot start the box: it declares {declares}, and the Box Egress Proxy \
does not answer on {}: {error}.",
path.display()
),
Self::Control(error) => write!(
f,
"Cannot start the box: the connection to the Box Egress Proxy failed: {error}."
),
// The exact text the task fixes for a refused key registration.
// The proxy's reason goes to the log.
Self::Refused { what, .. } if *what == CLIENT_KEY => write!(
f,
"The proxy did not accept this client's signing key, so the box was not created."
),
Self::Refused { what, error } => write!(
f,
"Cannot start the box: the Box Egress Proxy refused to register {what}: {error}."
),
Self::BoxId(id) => write!(
f,
"Cannot start the box: its id {id} is not one the Box Egress Proxy accepts."
),
Self::Random if stored => write!(
f,
"Cannot start the box: this machine gave no random bytes for the store handle's key."
),
Self::Random => write!(
f,
"Cannot start the box: this machine gave no random bytes for the GitHub grant's key."
),
Self::RootExpired => write!(
f,
"Cannot start the box: the Box Egress Proxy's root certificate is expired. \
Run `bep --replace-key root` to make a new one."
),
Self::KeyStore(detail) => write!(
f,
"Cannot start the box: the host keychain did not give this client's signing key: {detail}."
),
// The exact text the task fixes for a registration that the
// bound refuses (BEP-063).
Self::KeysInUse { max } => write!(
f,
"min did not create the box: the Box Egress Proxy already holds {max} client keys, \
and running boxes use each one. A key is freed when the last box created under it ends."
),
// The exact text the task fixes for a rule that `bep serve`
// does not read (BEP-032).
Self::RuleNotRead {
id,
bep_config,
config_dir,
} => write!(
f,
"min did not mint a store handle for {id}: bep serve reads store rules from {}, \
not from --config-dir {}.",
bep_config.display(),
config_dir.display()
),
Self::BepConfigUnread { id, file, error } => write!(
f,
"min did not mint a store handle for {id}: bep serve cannot read {}, \
so it holds no store rules. {error}",
file.display()
),
Self::BepRuleRefused { id, refusal } => write!(
f,
"min did not mint a store handle for {id}: bep serve refuses its rule for {id}. \
{refusal}"
),
Self::BepRuleDenied { id, files } => write!(
f,
"min did not mint a store handle for {id}: the store rules that bep serve reads \
from {files} set action = \"deny\" for {id}."
),
Self::BepRuleDiffers { id, files, fields } => write!(
f,
"min did not mint a store handle for {id}: the rule for {id} that bep serve reads \
from {files} has a different {}. Give both rules the same {}.",
fields.join(" and "),
fields.join(" and ")
),
}
}
}
impl std::error::Error for MintError {}
/// The client's handle-signing key. [`local_client_key`] gives the one key a
/// [`ClientKeyStore`] keeps, and box creation reads it from
/// [`HostClientKeyStore`].
pub struct ClientKey(SigningKey);
impl fmt::Debug for ClientKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("ClientKey").field(&self.kid()).finish()
}
}
impl ClientKey {
/// A new key from the operating system's random source.
///
/// # Errors
///
/// [`MintError::Random`] when the host gives no random bytes.
pub fn generate() -> Result<Self, MintError> {
// A random 32-byte string is a valid scalar except with negligible
// odds. Draw again in that case.
for _ in 0..8 {
let mut bytes = Zeroizing::new([0u8; 32]);
getrandom::fill(bytes.as_mut()).map_err(|_| MintError::Random)?;
if let Ok(key) = SigningKey::from_bytes(&(*bytes).into()) {
return Ok(Self(key));
}
}
Err(MintError::Random)
}
/// The key from its 32-byte secret scalar, as a [`ClientKeyStore`] keeps
/// it. `None` when the bytes are not a valid scalar.
#[must_use]
pub fn from_secret(bytes: &[u8; 32]) -> Option<Self> {
SigningKey::from_bytes(&(*bytes).into()).ok().map(Self)
}
/// The 32-byte secret scalar, for a [`ClientKeyStore`] to keep.
#[must_use]
pub fn secret(&self) -> Zeroizing<[u8; 32]> {
Zeroizing::new(self.0.to_bytes().into())
}
/// The SEC1 encoding of the public half, unpadded base64url, as the
/// control socket takes it.
#[must_use]
pub fn public(&self) -> String {
URL_SAFE_NO_PAD.encode(self.0.verifying_key().to_sec1_bytes())
}
/// The key's thumbprint, which a handle's `kid` carries.
#[must_use]
pub fn kid(&self) -> String {
handle::kid(self.0.verifying_key())
}
}
/// Why a [`ClientKeyStore`] did not give the client's key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ClientKeyError {
/// The store holds the key and refused this program its use.
Refused(String),
/// The store failed for another reason, as a locked keychain does.
Store(String),
}
/// The store that keeps the client's one handle-signing key across
/// creations, the host keychain on a laptop.
pub trait ClientKeyStore {
/// The key the store keeps, or `None` when it keeps none.
///
/// # Errors
///
/// [`ClientKeyError::Refused`] when the store holds a key and refuses
/// it to this program.
fn find(&self) -> Result<Option<ClientKey>, ClientKeyError>;
/// Keeps `key` in place of any key the store holds.
///
/// # Errors
///
/// [`ClientKeyError::Store`] when the store does not keep it.
fn replace(&self, key: &ClientKey) -> Result<(), ClientKeyError>;
}
/// The client's local key from `store`. A store that keeps no key gets a
/// new one. A store that refuses this program its key gets a replacement
/// (BEP-063): the key signs handles only, and every mint registers the key
/// it signs under, so the replacement needs no step from the operator. The
/// proxy at [`control_path`] registers the replacement before the store
/// keeps it, and revokes the key it replaces after the store keeps it.
///
/// # Errors
///
/// [`MintError::Random`] when the host gives no random bytes, and
/// [`MintError::KeyStore`] when the store fails for another reason. A
/// replacement also fails with the control socket's errors.
pub fn local_client_key(store: &dyn ClientKeyStore) -> Result<ClientKey, MintError> {
let control = control_path().unwrap_or_else(|| PathBuf::from("~/.minimal/bep/control.sock"));
local_client_key_at(store, &control)
}
/// [`local_client_key`], with the proxy's control socket at `control`.
///
/// The client cannot read the key that the store refused, so it cannot name
/// that key to the proxy. The replacement goes to the proxy with
/// `replace_client_key`, which revokes every other registered key. The
/// steps go in this order:
///
/// 1. `register_client_key` registers the replacement and revokes nothing.
/// A proxy that is down or refuses leaves the refused key in the store,
/// and the next creation tries again.
/// 2. The store keeps the replacement. A store that fails leaves every old
/// key registered, so running boxes keep their store handles.
/// 3. `replace_client_key` revokes every other key that no running box
/// uses. A key that a running box uses keeps verifying until the last
/// such box is forgotten, and then the proxy revokes it. Before this
/// step, a pending-revoke file next to the control socket records the
/// replacement's identifier, and the client removes the file when the
/// revoke succeeds.
/// A failure here leaves the replacement registered and in the store,
/// and is logged at warn. The next creation finds the replacement in the
/// store and the pending file under its identifier, and revokes again.
///
/// A lock file next to the control socket serialises the replacement and
/// the retry across `min` processes. A creation that waited on the lock
/// reads the store again, and uses a key that another creation kept.
///
/// # Errors
///
/// As [`local_client_key`].
pub fn local_client_key_at(
store: &dyn ClientKeyStore,
control: &Path,
) -> Result<ClientKey, MintError> {
let store_error = |error| match error {
ClientKeyError::Refused(detail) | ClientKeyError::Store(detail) => {
MintError::KeyStore(detail)
}
};
let pending = pending_revoke_path(control);
let replacing = match store.find() {
Ok(Some(key)) => {
if !pending.exists() {
return Ok(key);
}
// A pending revoke is retried under the lock, against the key
// that the store holds then.
let _lock = ReplaceLock::acquire(control);
return match store.find() {
Ok(Some(key)) => {
retry_pending_revoke(&key, control, &pending);
Ok(key)
}
Ok(None) => Ok(key),
Err(error) => Err(store_error(error)),
};
}
Ok(None) => false,
Err(ClientKeyError::Refused(detail)) => {
tracing::warn!(%detail, "the keychain refused the client's signing key; replacing it");
true
}
Err(error) => return Err(store_error(error)),
};
// Two creations that both get a refusal replace the key one after the
// other. The second one finds the first one's replacement in the store
// and uses it, so the revoke never removes the key that the store keeps.
let _lock = replacing.then(|| ReplaceLock::acquire(control));
if replacing && let Ok(Some(key)) = store.find() {
retry_pending_revoke(&key, control, &pending);
return Ok(key);
}
let key = ClientKey::generate()?;
if replacing {
ControlClient::connect(control)?.register_client_key(&key, None)?;
}
if replacing && let Err(error) = std::fs::write(&pending, key.kid()) {
// Without the file, a failed revoke below is not retried.
tracing::warn!(path = %pending.display(), %error, "did not record the pending client key revoke");
}
store.replace(&key).map_err(store_error)?;
if replacing {
revoke_others(&key, control, &pending);
}
tracing::info!(kid = %key.kid(), "made a new client signing key");
Ok(key)
}
/// An exclusive lock on the file next to the control socket at `control`.
/// It serialises the replacement of the client's key, and the retry of a
/// pending revoke, across `min` processes. The lock ends when it is dropped.
struct ReplaceLock {
_file: Option<std::fs::File>,
}
impl ReplaceLock {
/// Waits for the lock. A lock file that does not open, or a lock that
/// fails, is logged at warn, and the caller goes on without the lock.
fn acquire(control: &Path) -> Self {
let mut name = control.as_os_str().to_owned();
name.push(".replace-lock");
let path = PathBuf::from(name);
let file = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(&path)
.and_then(|file| file.lock().map(|()| file));
match file {
Ok(file) => Self { _file: Some(file) },
Err(error) => {
tracing::warn!(path = %path.display(), %error, "did not lock the client key replacement");
Self { _file: None }
}
}
}
}
/// The file next to the control socket at `control` that names a kept
/// replacement key whose revoke of the other keys did not finish.
fn pending_revoke_path(control: &Path) -> PathBuf {
let mut name = control.as_os_str().to_owned();
name.push(".revoke-pending");
PathBuf::from(name)
}
/// Revokes every client key but `key` at the proxy at `control`, when the
/// file at `pending` names `key`. A file that names another key is stale:
/// that key is not in the store, so the file is removed.
fn retry_pending_revoke(key: &ClientKey, control: &Path, pending: &Path) {
let Ok(named) = std::fs::read_to_string(pending) else {
return;
};
if named.trim() == key.kid() {
tracing::info!(kid = %key.kid(), "retrying the revoke of the replaced client signing keys");
revoke_others(key, control, pending);
} else {
let _ = std::fs::remove_file(pending);
}
}
/// Revokes every client key but `key` at the proxy at `control`, and
/// removes the file at `pending` when the proxy records the revoke.
fn revoke_others(key: &ClientKey, control: &Path, pending: &Path) {
match ControlClient::connect(control).and_then(|mut client| client.replace_client_key(key)) {
Ok(()) => {
let _ = std::fs::remove_file(pending);
}
Err(error) => tracing::warn!(
kid = %key.kid(),
%error,
"did not revoke the replaced client signing keys at the proxy; the next creation tries again"
),
}
}
/// The keychain item that keeps the client's key: its service.
const CLIENT_KEY_SERVICE: &str = "dev.minimal.client-key";
/// The keychain item that keeps the client's key: its account.
const CLIENT_KEY_ACCOUNT: &str = "minimal";
/// The keychain item that keeps the client's key: its label.
const CLIENT_KEY_LABEL: &str = "Minimal client signing key";
/// The host keychain as a [`ClientKeyStore`]: the login keychain through
/// `/usr/bin/security` on macOS, the Secret Service through `secret-tool`
/// on Linux. The item holds the key's secret scalar, unpadded base64url.
/// The secret goes to the tool on its stdin, never on a command line.
#[derive(Debug, Default, Clone, Copy)]
pub struct HostClientKeyStore;
impl HostClientKeyStore {
/// The key from the item's text. An item that holds no valid key is
/// refused, so [`local_client_key`] replaces it.
fn decode(text: &mut Vec<u8>) -> Result<ClientKey, ClientKeyError> {
let decoded = std::str::from_utf8(text)
.ok()
.and_then(|text| URL_SAFE_NO_PAD.decode(text.trim()).ok())
.map(Zeroizing::new);
text.zeroize();
decoded
.and_then(|bytes| {
<[u8; 32]>::try_from(bytes.as_slice())
.ok()
.map(Zeroizing::new)
})
.and_then(|bytes| ClientKey::from_secret(&bytes))
.ok_or_else(|| ClientKeyError::Refused("the kept item holds no valid key".into()))
}
}
impl ClientKeyStore for HostClientKeyStore {
fn find(&self) -> Result<Option<ClientKey>, ClientKeyError> {
match host_key::find()? {
Some(mut text) => Self::decode(&mut text).map(Some),
None => Ok(None),
}
}
fn replace(&self, key: &ClientKey) -> Result<(), ClientKeyError> {
let secret = Zeroizing::new(URL_SAFE_NO_PAD.encode(key.secret().as_slice()));
host_key::store(&secret)?;
// Read the key back: a keychain tool can exit 0 and store nothing.
match self.find() {
Ok(Some(kept)) if kept.kid() == key.kid() => Ok(()),
_ => Err(ClientKeyError::Store(
"the keychain does not hold the new key after the write".into(),
)),
}
}
}
/// How long a keychain tool can run. The tool can wait on an unlock or
/// access prompt that nobody answers, as in an SSH session, and box
/// creation must not wait for it forever.
const KEY_TOOL_TIMEOUT: Duration = Duration::from_secs(60);
/// Runs a keychain tool with `stdin` on its standard input, and gives its
/// output. A tool that runs past `timeout` is killed. The child is reaped
/// on every path.
fn run_key_tool(
tool: &str,
cmd: std::process::Command,
stdin: Option<&str>,
) -> Result<std::process::Output, ClientKeyError> {
run_key_tool_within(tool, cmd, stdin, KEY_TOOL_TIMEOUT)
}
fn run_key_tool_within(
tool: &str,
mut cmd: std::process::Command,
stdin: Option<&str>,
timeout: Duration,
) -> Result<std::process::Output, ClientKeyError> {
use std::io::Read as _;
use std::process::Stdio;
cmd.stdin(if stdin.is_some() {
Stdio::piped()
} else {
Stdio::null()
})
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = cmd.spawn().map_err(|error| {
if error.kind() == io::ErrorKind::NotFound {
ClientKeyError::Store(format!("`{tool}` is not installed"))
} else {
ClientKeyError::Store(format!("`{tool}` did not start: {error}"))
}
})?;
let stop = |child: &mut std::process::Child| {
let _ = child.kill();
let _ = child.wait();
};
if let (Some(input), Some(mut pipe)) = (stdin, child.stdin.take())
&& let Err(error) = pipe.write_all(input.as_bytes())
{
drop(pipe);
stop(&mut child);
return Err(ClientKeyError::Store(format!(
"`{tool}` did not take its input: {error}"
)));
}
// The pipes are read on their own threads, so a full pipe never stops
// the tool while this thread waits on the deadline.
let reader = |pipe: Option<Box<dyn io::Read + Send>>| {
std::thread::spawn(move || {
let mut bytes = Vec::new();
if let Some(mut pipe) = pipe {
let _ = pipe.read_to_end(&mut bytes);
}
bytes
})
};
let stdout = reader(
child
.stdout
.take()
.map(|pipe| Box::new(pipe) as Box<dyn io::Read + Send>),
);
let stderr = reader(
child
.stderr
.take()
.map(|pipe| Box::new(pipe) as Box<dyn io::Read + Send>),
);
let deadline = std::time::Instant::now() + timeout;
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Ok(None) if std::time::Instant::now() < deadline => {
std::thread::sleep(Duration::from_millis(20));
}
Ok(None) => {
stop(&mut child);
let _ = (stdout.join(), stderr.join());
return Err(ClientKeyError::Store(format!(
"`{tool}` did not finish in {} seconds. The keychain can be locked, \
or it can wait for an answer to a prompt",
timeout.as_secs()
)));
}
Err(error) => {
stop(&mut child);
let _ = (stdout.join(), stderr.join());
return Err(ClientKeyError::Store(error.to_string()));
}
}
};
Ok(std::process::Output {
status,
stdout: stdout.join().unwrap_or_default(),
stderr: stderr.join().unwrap_or_default(),
})
}
/// The text a keychain tool printed on its standard error.
fn key_tool_error(stderr: &[u8]) -> String {
String::from_utf8_lossy(stderr).trim().to_owned()
}
#[cfg(target_os = "macos")]
mod host_key {
use std::process::Command;
use zeroize::{Zeroize as _, Zeroizing};
use super::{
CLIENT_KEY_ACCOUNT, CLIENT_KEY_LABEL, CLIENT_KEY_SERVICE, ClientKeyError, key_tool_error,
run_key_tool,
};
const SECURITY: &str = "/usr/bin/security";
/// `security` exits with the low byte of the keychain status. No item
/// matched: `errSecItemNotFound`.
const NOT_FOUND: i32 = 44;
/// The keychain holds the item and refused it to this program:
/// `errSecAuthFailed`, `errSecNoAccessForItem` and `userCanceled`.
const REFUSED: [i32; 3] = [51, 101, 128];
pub(super) fn find() -> Result<Option<Vec<u8>>, ClientKeyError> {
let mut cmd = Command::new(SECURITY);
cmd.args([
"find-generic-password",
"-s",
CLIENT_KEY_SERVICE,
"-a",
CLIENT_KEY_ACCOUNT,
"-w",
]);
let mut out = run_key_tool(SECURITY, cmd, None)?;
match out.status.code() {
_ if out.status.success() => Ok(Some(out.stdout)),
Some(NOT_FOUND) => {
out.stdout.zeroize();
Ok(None)
}
Some(code) if REFUSED.contains(&code) => {
out.stdout.zeroize();
Err(ClientKeyError::Refused(key_tool_error(&out.stderr)))
}
_ => {
out.stdout.zeroize();
Err(ClientKeyError::Store(key_tool_error(&out.stderr)))
}
}
}
pub(super) fn store(secret: &str) -> Result<(), ClientKeyError> {
// A replacement follows only a missing or a refused item. An item
// whose access list refuses this program can refuse an update in
// place too, so the old item goes first and a new one is added.
delete()?;
// Every part is quoted, and none carries a quote or a backslash:
// the names are fixed, and the secret is base64url.
let line = Zeroizing::new(format!(
"add-generic-password -s \"{CLIENT_KEY_SERVICE}\" -a \"{CLIENT_KEY_ACCOUNT}\" \
-l \"{CLIENT_KEY_LABEL}\" -w \"{secret}\"\n"
));
let mut cmd = Command::new(SECURITY);
cmd.arg("-i");
let out = run_key_tool(SECURITY, cmd, Some(&line))?;
if out.status.success() {
Ok(())
} else {
Err(ClientKeyError::Store(key_tool_error(&out.stderr)))
}
}
/// Deletes the kept item. No item to delete is no error.
fn delete() -> Result<(), ClientKeyError> {
let mut cmd = Command::new(SECURITY);
cmd.args([
"delete-generic-password",
"-s",
CLIENT_KEY_SERVICE,
"-a",
CLIENT_KEY_ACCOUNT,
]);
let out = run_key_tool(SECURITY, cmd, None)?;
if out.status.success() || out.status.code() == Some(NOT_FOUND) {
Ok(())
} else {
Err(ClientKeyError::Store(key_tool_error(&out.stderr)))
}
}
}
#[cfg(not(target_os = "macos"))]
mod host_key {
use std::path::{Path, PathBuf};
use std::process::Command;
use zeroize::Zeroize as _;
use super::{
CLIENT_KEY_ACCOUNT, CLIENT_KEY_LABEL, CLIENT_KEY_SERVICE, ClientKeyError, key_tool_error,
run_key_tool,
};
const SECRET_TOOL: &str = "secret-tool";
/// The system directories `secret-tool` is taken from. The tool sees
/// the client's key, so it is never found through `PATH`, where a
/// project directory can put a program of the same name first.
const SYSTEM_DIRS: [&str; 3] = ["/usr/bin", "/bin", "/run/current-system/sw/bin"];
/// The first `secret-tool` in [`SYSTEM_DIRS`].
fn secret_tool() -> Result<Command, ClientKeyError> {
trusted_tool(&SYSTEM_DIRS).map(Command::new).ok_or_else(|| {
ClientKeyError::Store(format!(
"`{SECRET_TOOL}` is not installed in {}",
SYSTEM_DIRS.join(", ")
))
})
}
pub(super) fn trusted_tool(dirs: &[&str]) -> Option<PathBuf> {
dirs.iter()
.map(|dir| Path::new(dir).join(SECRET_TOOL))
.find(|path| path.is_file())
}
pub(super) fn find() -> Result<Option<Vec<u8>>, ClientKeyError> {
let mut cmd = secret_tool()?;
cmd.args([
"lookup",
"service",
CLIENT_KEY_SERVICE,
"account",
CLIENT_KEY_ACCOUNT,
]);
let mut out = run_key_tool(SECRET_TOOL, cmd, None)?;
if out.status.success() && !out.stdout.is_empty() {
return Ok(Some(out.stdout));
}
out.stdout.zeroize();
// `secret-tool` exits 1 with nothing on stderr when no item matches.
if out.stderr.is_empty() {
Ok(None)
} else {
Err(ClientKeyError::Store(key_tool_error(&out.stderr)))
}
}
pub(super) fn store(secret: &str) -> Result<(), ClientKeyError> {
// The Secret Service replaces the item whose attributes all match.
let mut cmd = secret_tool()?;
cmd.args([
"store",
&format!("--label={CLIENT_KEY_LABEL}"),
"service",
CLIENT_KEY_SERVICE,
"account",
CLIENT_KEY_ACCOUNT,
]);
let out = run_key_tool(SECRET_TOOL, cmd, Some(secret))?;
if out.status.success() {
Ok(())
} else {
Err(ClientKeyError::Store(key_tool_error(&out.stderr)))
}
}
}
/// The end of the root CA's validity, the expiry of every handle minted
/// under it. A root whose validity ends at or before `now` mints nothing.
fn root_expiry(identity: &Identity, identity_path: &Path, now: u64) -> Result<u64, MintError> {
let not_after = identity
.root_not_after()
.map_err(|error| MintError::Identity {
path: identity_path.to_owned(),
error,
})?;
if not_after <= now {
tracing::error!(not_after, now, "refused a mint under an expired root CA");
return Err(MintError::RootExpired);
}
Ok(not_after)
}
/// One connection to the proxy's control socket.
pub struct ControlClient {
path: PathBuf,
stream: BufReader<UnixStream>,
}
impl ControlClient {
/// Connects to the control socket at `path`.
///
/// # Errors
///
/// [`MintError::NotRunning`] when nothing answers there.
pub fn connect(path: &Path) -> Result<Self, MintError> {
Self::connect_with_timeout(path, CONTROL_TIMEOUT)
}
/// Connects to the control socket at `path`, and waits at most
/// `timeout` for each read and write.
fn connect_with_timeout(path: &Path, timeout: Duration) -> Result<Self, MintError> {
let not_running = |error| MintError::NotRunning {
path: path.to_owned(),
error,
};
let stream = UnixStream::connect(path).map_err(not_running)?;
stream
.set_read_timeout(Some(timeout))
.map_err(not_running)?;
stream
.set_write_timeout(Some(timeout))
.map_err(not_running)?;
Ok(Self {
path: path.to_owned(),
stream: BufReader::new(stream),
})
}
fn ask(
&mut self,
request: &impl serde::Serialize,
what: &'static str,
) -> Result<Reply, MintError> {
let mut line = serde_json_lenient::to_string(request).map_err(|error| {
MintError::Control(io::Error::new(io::ErrorKind::InvalidData, error))
})?;
line.push('\n');
self.stream
.get_mut()
.write_all(line.as_bytes())
.map_err(MintError::Control)?;
let mut answer = String::new();
let read = self
.stream
.read_line(&mut answer)
.map_err(MintError::Control)?;
if read == 0 {
return Err(MintError::Control(io::ErrorKind::UnexpectedEof.into()));
}
let reply: Reply = serde_json_lenient::from_str(&answer).map_err(|error| {
MintError::Control(io::Error::new(io::ErrorKind::InvalidData, error))
})?;
if reply.ok {
Ok(reply)
} else {
Err(MintError::Refused {
what,
error: reply.error.unwrap_or_default(),
})
}
}
/// Registers `key` with the proxy, so it verifies handles signed under
/// it (BEP-063). With `box_id`, the proxy records that the box uses the
/// key, and keeps the key until the box is forgotten.
///
/// # Errors
///
/// [`MintError::Control`] when the connection fails,
/// [`MintError::KeysInUse`] when the proxy's bound is full of keys that
/// running boxes use, and [`MintError::Refused`] when the proxy refuses