-
Notifications
You must be signed in to change notification settings - Fork 38
/
signature.rs
576 lines (523 loc) · 19.5 KB
/
signature.rs
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
//! Contains the Signature type along with associated types and Roles
use base64::Engine;
pub use ed25519_dalek::{
Signature as EdSignature,
Signer,
SigningKey as Keypair, // re-export under old name for backwards compatibility
SigningKey,
VerifyingKey as PublicKey, // re-export under old name for backwards compatibility
VerifyingKey,
};
use serde::{Deserialize, Serialize};
use thiserror::Error;
#[cfg(not(target_arch = "wasm32"))]
use tokio::io::AsyncWriteExt;
use tracing::error;
use std::convert::TryFrom;
use std::fmt::{Display, Formatter, Result as FmtResult};
#[cfg(not(target_arch = "wasm32"))]
use std::path::Path;
use std::str::FromStr;
/// The latest key ring version supported by this library.
pub const KEY_RING_VERSION: &str = "1.0";
/// A signature describes a cryptographic signature of the parcel list.
///
/// In the current implementation, a signature signs the list of parcels that belong on
/// an invoice. The signature, in the current implementation, is an Ed25519 signature
/// and is signed by the private counterpart of the given public key.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct Signature {
// The cleartext name of the user who signed
pub by: String,
// The signature block, encoded as hex chars
pub signature: String,
// The public key, encoded as hex chars
pub key: String,
// The role of the signer
pub role: SignatureRole,
// The UNIX timestamp, expressed as an unsigned 64-bit integer
pub at: u64,
}
/// Wrap errors related to signing
///
/// These errors are designed to tell what failed and how, but not necessarily why.
/// This is to avoid leaking sensitive data back to a user agent.
/// Where possible, the error is linked to the signing key that failed. That key can
/// be cross-referenced with the invoice to determine which block failed or which key
/// is not correctly represented in the keyring.
#[derive(Error, Debug)]
pub enum SignatureError {
#[error("signatures `{0}` cannot be verified")]
Unverified(String),
#[error("failed to sign the invoice with the given key")]
SigningFailed,
#[error("key is corrupt for `{0}`")]
CorruptKey(String),
#[error("signature block is corrupt for key {0}")]
CorruptSignature(String),
#[error("unknown signing key {0}")]
UnknownSigningKey(String),
#[error("none of the signatures are made with a known key")]
NoKnownKey,
#[error("cannot sign the data again with a key that has already signed the data")]
DuplicateSignature,
#[error("no suitable key for signing data")]
NoSuitableKey,
}
/// The role of a signer in a signature block.
///
/// Signatories on a signature must have an associated role, as defined in the
/// specification.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum SignatureRole {
Creator,
Proxy,
Host,
Approver,
}
impl Display for SignatureRole {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(
f,
"{}",
match self {
Self::Creator => "creator",
Self::Proxy => "proxy",
Self::Host => "host",
Self::Approver => "approver",
}
)
}
}
impl FromStr for SignatureRole {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let normalized = s.trim().to_lowercase();
match normalized.as_str() {
"c" | "creator" => Ok(Self::Creator),
"h" | "host" => Ok(Self::Host),
"a" | "approver" => Ok(Self::Approver),
"p" | "proxy" => Ok(Self::Proxy),
_ => Err("Invalid SignatureRole, should be one of: Creator, Proxy, Host, Approver"),
}
}
}
// NOTE (thomastaylor312): These are basically glorified helper traits. We could theoretically
// define `KeyRing` as a set of traits and then implementors could only dynamically load what is
// necessary (as keychains could get large a big companies) and that could replace these helpers.
// This isn't an optimization we need now, but likely do in the future
/// Keyrings could be loaded from in any number of sources. This trait allows implementors to create
/// custom loader helpers for keyrings
#[async_trait::async_trait]
pub trait KeyRingLoader {
/// Load the keyring from source, returning the KeyRing
async fn load(&self) -> anyhow::Result<KeyRing>;
}
/// Keyrings could be saved to any number of sources. This trait allows implementors to create
/// custom saving helpers for keyrings
#[async_trait::async_trait]
pub trait KeyRingSaver {
/// Save the keyring to the given source
async fn save(&self, keyring: &KeyRing) -> anyhow::Result<()>;
}
#[cfg(not(target_arch = "wasm32"))]
#[async_trait::async_trait]
impl<T: AsRef<Path> + Sync> KeyRingLoader for T {
async fn load(&self) -> anyhow::Result<KeyRing> {
let raw_data = tokio::fs::read(self).await.map_err(|e| {
anyhow::anyhow!(
"failed to read TOML file {}: {}",
self.as_ref().display(),
e
)
})?;
let res: KeyRing = toml::from_slice(&raw_data)?;
Ok(res)
}
}
#[cfg(not(target_arch = "wasm32"))]
#[async_trait::async_trait]
impl<T: AsRef<Path> + Sync> KeyRingSaver for T {
async fn save(&self, keyring: &KeyRing) -> anyhow::Result<()> {
let mut opts = tokio::fs::OpenOptions::new();
opts.create(true).write(true).truncate(true);
// TODO(thomastaylor312): Figure out what the proper permissions are on windows (probably
// creator/owner with read/write permissions and everything else excluded) and figure out
// how to set those
#[cfg(target_family = "unix")]
opts.mode(0o600);
let mut file = opts.open(self).await?;
file.write_all(&toml::to_vec(keyring)?).await?;
file.flush().await?;
Ok(())
}
}
/// A KeyRing contains a list of public keys.
///
/// The purpose of this keyring is to validate signatures. The keyring NEVER
/// contains private keys.
///
/// The concepts are described in the signing-spec.md document for Bindle.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct KeyRing {
pub version: String,
pub key: Vec<KeyEntry>,
}
impl Default for KeyRing {
fn default() -> Self {
Self {
version: KEY_RING_VERSION.to_owned(),
key: vec![],
}
}
}
impl KeyRing {
pub fn new(keys: Vec<KeyEntry>) -> Self {
KeyRing {
version: KEY_RING_VERSION.to_owned(),
key: keys,
}
}
pub fn add_entry(&mut self, entry: KeyEntry) {
self.key.push(entry)
}
pub fn contains(&self, key: &VerifyingKey) -> bool {
// This could definitely be optimized.
for k in self.key.iter() {
// Note that we are skipping malformed keys because they don't matter
// when doing a contains(). If they key is malformed, it definitely
// is not the key we are looking for.
match k.public_key() {
Err(e) => tracing::warn!(%e, "Error parsing key"),
Ok(pk) if pk == *key => return true,
_ => {}
}
tracing::debug!("No match. Moving on.");
}
tracing::debug!("No more keys to check");
false
}
}
/// A KeyEntry describes an entry on a keyring.
///
/// An entry has a key, an identifying label, a list of roles, and an optional signature of this data.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct KeyEntry {
/// The human-friendly name of the key.
///
/// This has no particular security importance. It is just for convenience and
/// can be changed by the user who owns this keyring.
pub label: String,
/// The list of roles, where a role is one of the signature roles.
pub roles: Vec<SignatureRole>,
/// The public key, encoded as the platform dictates.
///
/// As of this writing, a key is a base64-encoded Ed25519 public key.
pub key: String,
/// A signed version of the label
///
/// The specification provides an optional field for signing the label with a known
/// private key as a way of protecting labels against tampering.
pub label_signature: Option<String>,
}
impl KeyEntry {
/// Create a new KeyEntry from a public key and related information.
///
/// In most cases, it is fine to construct a KeyEntry struct manually. This
/// constructor merely encapsulates the logic to store the public key in its
/// canonical encoded format (as a String).
pub fn new(label: &str, roles: Vec<SignatureRole>, public_key: VerifyingKey) -> Self {
let key = base64::engine::general_purpose::STANDARD.encode(public_key.to_bytes());
KeyEntry {
label: label.to_owned(),
roles,
key,
label_signature: None,
}
}
pub fn sign_label(&mut self, key: SigningKey) {
let sig = key.sign(self.label.as_bytes());
self.label_signature =
Some(base64::engine::general_purpose::STANDARD.encode(sig.to_bytes()));
}
pub fn verify_label(self, key: VerifyingKey) -> anyhow::Result<()> {
match self.label_signature {
None => {
tracing::log::info!("Label was not signed. Skipping.");
Ok(())
}
Some(txt) => {
let decoded_txt = base64::engine::general_purpose::STANDARD.decode(txt)?;
let sig = EdSignature::try_from(decoded_txt.as_slice())?;
key.verify_strict(self.label.as_bytes(), &sig)?;
Ok(())
}
}
}
pub(crate) fn public_key(&self) -> Result<VerifyingKey, SignatureError> {
let rawbytes = base64::engine::general_purpose::STANDARD
.decode(&self.key)
.map_err(|_e| {
// We swallow the source error because it could disclose information about
// the secret key.
SignatureError::CorruptKey("Base64 decoding of the public key failed".to_owned())
})?;
let pk = VerifyingKey::try_from(rawbytes.as_slice()).map_err(|e| {
error!(%e, "Error loading public key");
// Don't leak information about the key, because this could be sent to
// a remote. A generic error is all the user should see.
SignatureError::CorruptKey("Could not load keypair".to_owned())
})?;
Ok(pk)
}
}
/// Convert a secret key to a public key.
impl TryFrom<SecretKeyEntry> for KeyEntry {
type Error = SignatureError;
fn try_from(secret: SecretKeyEntry) -> std::result::Result<Self, SignatureError> {
let skey = secret.key()?;
let mut s = Self {
label: secret.label,
roles: secret.roles,
key: base64::engine::general_purpose::STANDARD.encode(skey.verifying_key().as_bytes()),
label_signature: None,
};
s.sign_label(skey);
Ok(s)
}
}
impl TryFrom<&SecretKeyEntry> for KeyEntry {
type Error = SignatureError;
fn try_from(secret: &SecretKeyEntry) -> std::result::Result<Self, SignatureError> {
let skey = secret.key()?;
let mut s = Self {
label: secret.label.clone(),
roles: secret.roles.clone(),
key: base64::engine::general_purpose::STANDARD.encode(skey.verifying_key().as_bytes()),
label_signature: None,
};
s.sign_label(skey);
Ok(s)
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SecretKeyEntry {
/// A label for this key.
///
/// This is intended for human consumption
pub label: String,
/// Base64-encoded Ed25519 key
pub keypair: String,
/// The roles this key should be used for.
/// The default should be SignatureRole::Creator
pub roles: Vec<SignatureRole>,
}
impl SecretKeyEntry {
pub fn new(label: &str, roles: Vec<SignatureRole>) -> Self {
let mut rng = rand::rngs::OsRng {};
let rawkey = SigningKey::generate(&mut rng);
let keypair = base64::engine::general_purpose::STANDARD.encode(rawkey.to_keypair_bytes());
Self {
label: label.to_owned(),
keypair,
roles,
}
}
pub(crate) fn key(&self) -> Result<SigningKey, SignatureError> {
let rawbytes = base64::engine::general_purpose::STANDARD
.decode(&self.keypair)
.map_err(|_e| {
// We swallow the source error because it could disclose information about
// the secret key.
SignatureError::CorruptKey("Base64 decoding of the keypair failed".to_owned())
})?;
let rawbytes = rawbytes.try_into().map_err(|_e| {
// We swallow the source error because it could disclose information about
// the secret key.
SignatureError::CorruptKey("Invalid keypair length".to_owned())
})?;
SigningKey::from_keypair_bytes(&rawbytes).map_err(|e| {
tracing::log::error!("Error loading key: {}", e);
// Don't leak information about the key, because this could be sent to
// a remote. A generic error is all the user should see.
SignatureError::CorruptKey("Could not load keypair".to_owned())
})
}
}
/// Storage for secret keys
///
/// Any possible number of key storage systems may be used for key storage, but
/// all of them must provide a way for the system to fetch a key matching the
/// desired role.
pub trait SecretKeyStorage {
/// Get a key appropriate for signing with the given role and optional match criteria with
/// LabelMatch enum.
///
/// If no key is found, this will return a None. In general, if multiple keys match, the
/// implementation chooses the "best fit" and returns that key.
fn get_first_matching(
&self,
role: &SignatureRole,
label_match: Option<&LabelMatch>,
) -> Option<&SecretKeyEntry>;
/// Similar to [`get_first_matching`](get_first_matching), but returns all matches rather than
/// just the best fit
fn get_all_matching(
&self,
role: &SignatureRole,
label_match: Option<&LabelMatch>,
) -> Vec<&SecretKeyEntry>;
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SecretKeyFile {
pub version: String,
pub key: Vec<SecretKeyEntry>,
}
impl Default for SecretKeyFile {
fn default() -> Self {
Self {
version: KEY_RING_VERSION.to_owned(),
key: vec![],
}
}
}
#[cfg(not(target_arch = "wasm32"))]
impl SecretKeyFile {
pub async fn load_file(path: impl AsRef<Path>) -> anyhow::Result<SecretKeyFile> {
let raw = tokio::fs::read(path).await?;
let t = toml::from_slice(&raw)?;
Ok(t)
}
/// Save the present keyfile to the named path.
pub async fn save_file(&self, dest: impl AsRef<Path>) -> anyhow::Result<()> {
let out = toml::to_vec(self)?;
let mut opts = tokio::fs::OpenOptions::new();
opts.create(true).write(true);
// TODO(thomastaylor312): Figure out what the proper permissions are on windows (probably
// creator/owner with read/write permissions and everything else excluded) and figure out
// how to set those
#[cfg(target_family = "unix")]
opts.mode(0o600);
let mut file = opts.open(dest).await?;
file.write_all(&out).await?;
file.flush().await?;
Ok(())
}
}
/// This enumerates the select criteria of the key based on the given Label
pub enum LabelMatch {
/// Key will be selected with an exact match of the given label.
/// Matches are case sensitive
FullMatch(String),
/// Key will be selected with a partial match of the given label,
/// Matches are case insensitive.
///
/// For example: "pika" will match "Pikachu" and "puff" will match "Jigglypuff"
PartialMatch(String),
}
impl SecretKeyStorage for SecretKeyFile {
fn get_first_matching(
&self,
role: &SignatureRole,
label_match: Option<&LabelMatch>,
) -> Option<&SecretKeyEntry> {
self.key.iter().find(|k| {
k.roles.contains(role)
&& match label_match {
Some(LabelMatch::FullMatch(label)) => k.label.eq(label),
Some(LabelMatch::PartialMatch(label)) => k.label.contains(label),
None => true,
}
})
}
fn get_all_matching(
&self,
role: &SignatureRole,
label_match: Option<&LabelMatch>,
) -> Vec<&SecretKeyEntry> {
self.key
.iter()
.filter(|k| {
k.roles.contains(role)
&& match label_match {
Some(LabelMatch::FullMatch(label)) => k.label.eq(label),
Some(LabelMatch::PartialMatch(label)) => k.label.contains(label),
None => true,
}
})
.collect()
}
}
#[cfg(test)]
mod test {
use super::*;
use ed25519_dalek::SigningKey;
#[test]
fn test_parse_role() {
// Happy path
"Creator".parse::<SignatureRole>().expect("should parse");
"Proxy".parse::<SignatureRole>().expect("should parse");
"Host".parse::<SignatureRole>().expect("should parse");
"Approver".parse::<SignatureRole>().expect("should parse");
// Odd formatting
"CrEaToR"
.parse::<SignatureRole>()
.expect("mixed case should parse");
" ProxY "
.parse::<SignatureRole>()
.expect("extra spacing should parse");
// Unhappy path
"yipyipyip"
.parse::<SignatureRole>()
.expect_err("non-existent shouldn't parse");
}
#[test]
fn test_sign_label() {
let mut rng = rand::rngs::OsRng {};
let keypair = SigningKey::generate(&mut rng);
let mut ke = KeyEntry {
label: "Matt Butcher <[email protected]>".to_owned(),
key: "jTtZIzQCfZh8xy6st40xxLwxVw++cf0C0cMH3nJBF+c=".to_owned(),
roles: vec![SignatureRole::Host],
label_signature: None,
};
let pubkey = keypair.verifying_key();
ke.sign_label(keypair);
assert!(ke.label_signature.is_some());
ke.verify_label(pubkey).expect("verification failed");
}
#[tokio::test]
async fn test_secret_keys() {
let mut kr = SecretKeyFile::default();
assert_eq!(kr.key.len(), 0);
kr.key
.push(SecretKeyEntry::new("test", vec![SignatureRole::Proxy]));
assert_eq!(kr.key.len(), 1);
let outdir = tempfile::tempdir().expect("created a temp dir");
let dest = outdir.path().join("testkey.toml");
kr.save_file(&dest)
.await
.expect("Should write new key to file");
#[cfg(target_family = "unix")]
{
use std::os::unix::fs::PermissionsExt;
let metadata = tokio::fs::metadata(&dest).await.unwrap();
// This masks out the bits we don't care about
assert_eq!(
metadata.permissions().mode() & 0o00600,
0o600,
"Permissions of saved key should be 0600"
)
}
let newfile = SecretKeyFile::load_file(dest)
.await
.expect("Should load key from file");
assert_eq!(newfile.key.len(), 1);
}
}