sett 0.4.0

Rust port of sett (data compression, encryption and transfer tool).
Documentation
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
//! Utilities for OpenPGP operations.
use sequoia_openpgp::serialize::stream::Recipient;
use tracing::{debug, trace, warn};

use super::{
    cert::{AsciiArmored, Fingerprint},
    certstore::CertStore,
    error,
    keystore::KeyStore,
};

/// Hint about an OpenPGP key or subkey for which a password is required.
///
/// This struct stores information about a secret key or subkey that can be
/// used to help users identify a key for which a password is being requested.
///
/// As signing and decryption operations are often carried-out with a subkey
/// rather than with the certificate's primary key - but users are generally
/// more familiar with the fingerprint of their primary key - the fingerprint
/// of the certificate's primary key can optionally be included via the
/// `fingerprint_primary` field.
///
/// The reason why `userid` and `fingerprint_primary` are optional is for
/// edge-cases where a signing/decryption subkey is not associated
/// with a primary key in the user's local environment.
#[derive(Clone, Debug)]
pub struct PasswordHint {
    /// Fingerprint of the key or subkey for which the password is required.
    pub fingerprint: super::cert::Fingerprint,
    /// UserID of the associated certificate.
    pub userid: Option<String>,
    /// Fingerprint of the associated certificate's primary key.
    pub fingerprint_primary: Option<super::cert::Fingerprint>,
}

/// Error type to forward to sequoia API
#[derive(Debug)]
struct ErrorForward<S>(S);

impl<S: std::fmt::Display> std::fmt::Display for ErrorForward<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl<S: std::fmt::Debug + std::fmt::Display> core::error::Error for ErrorForward<S> {}

/// Creates a detached OpenPGP signature.
pub(crate) fn sign_detached<T: sequoia_openpgp::crypto::Signer + Send + Sync>(
    data: &[u8],
    cert: T,
) -> Result<AsciiArmored, error::PgpError> {
    use sequoia_openpgp::serialize::stream::{Armorer, Message, Signer};
    use std::io::Write as _;
    let mut sink = vec![];
    let message = Armorer::new(Message::new(&mut sink))
        .kind(sequoia_openpgp::armor::Kind::Signature)
        .build()
        .map_err(error::PgpError::from)?;
    let mut message = Signer::new(message, cert)
        .map_err(error::PgpError::from)?
        .detached()
        .build()
        .map_err(error::PgpError::from)?;
    message.write_all(data).map_err(error::PgpError::from)?;
    message.finalize().map_err(error::PgpError::from)?;

    Ok(AsciiArmored(sink))
}

/// Returns encryption-capable keys.
pub(crate) fn get_recipients<'a>(
    certs: &'a [sequoia_openpgp::Cert],
    policy: &'a impl sequoia_openpgp::policy::Policy,
) -> Result<(Vec<Recipient<'a>>, Vec<sequoia_openpgp::Fingerprint>), error::PgpError> {
    let mut recipients = Vec::new();
    let mut cert_fingerprints = Vec::new();
    for cert in certs {
        // Make sure we add at least one subkey from every certificate.
        let mut found_one = false;
        for ka in cert
            .keys()
            .with_policy(policy, None)
            .supported()
            .alive()
            .revoked(false)
            .for_transport_encryption()
        {
            recipients.push(ka.into());
            cert_fingerprints.push(cert.fingerprint());
            found_one = true;
        }

        if !found_one {
            return Err(error::PgpError::Error(format!(
                "No suitable encryption subkey for {cert}"
            )));
        }
    }
    Ok((recipients, cert_fingerprints))
}

/// Signing-capable key
pub(crate) struct Signer {
    /// Key used for signing
    pub(crate) key: sequoia_keystore::Key,
    /// Fingerprint of the corresponding certificate.
    ///
    /// It is used to identify the signer and recipients in the metadata file.
    pub(crate) cert_fingerprint: sequoia_openpgp::Fingerprint,
}

impl Signer {
    #[tracing::instrument(skip_all, fields(cert=%valid_cert.fingerprint()))]
    pub(crate) async fn get<F, Fut>(
        valid_cert: &sequoia_openpgp::cert::ValidCert<'_>,
        key_store: &mut KeyStore,
        password: F,
    ) -> Result<Self, error::PgpError>
    where
        F: Fn(PasswordHint) -> Fut,
        Fut: std::future::Future<Output = crate::secret::Secret>,
    {
        let signing_capable_keys = valid_cert
            .keys()
            .alive()
            .revoked(false)
            .for_signing()
            .map(|ka| ka.key().fingerprint().into())
            .collect::<Vec<_>>();
        if signing_capable_keys.is_empty() {
            return Err(error::PgpError::Error(format!(
                "No signing-capable subkey found for the provided certificate: {valid_cert}"
            )));
        }

        let (keys, _) = key_store
            .inner
            .find_keys_async(&signing_capable_keys)
            .await
            .map_err(error::PgpError::from)?;
        if keys.is_empty() {
            return Err(error::PgpError::Error(format!(
                "No signing key found for the provided fingerprint: {}",
                valid_cert.fingerprint()
            )));
        }

        let mut errors = Vec::new();
        for mut key in keys.into_iter() {
            let cert_fingerprint = valid_cert.fingerprint();
            let hint = PasswordHint {
                fingerprint: Fingerprint(key.fingerprint()),
                userid: valid_cert
                    .userids()
                    .next()
                    .map(|ka| ka.userid().to_string()),
                fingerprint_primary: Some(Fingerprint(cert_fingerprint.clone())),
            };
            let key_description = hint_to_string(&hint);
            trace!("Attempting to unlock key: {key_description}");

            match key.locked_async().await {
                Ok(sequoia_keystore::Protection::Unlocked) => {
                    trace!("Key is already unlocked");
                    return Ok(Self {
                        key,
                        cert_fingerprint,
                    });
                }
                Ok(sequoia_keystore::Protection::Password(_)) => {
                    let unlocked = key
                        .unlock_async(password(hint).await.as_inner().clone())
                        .await;
                    if let Ok(()) = unlocked {
                        trace!("Key unlocked with the provided password");
                        return Ok(Self {
                            key,
                            cert_fingerprint,
                        });
                    } else {
                        let err_msg = format!(
                            "The provided password failed to unlock key: {key_description}"
                        );
                        debug!(err_msg);
                        errors.push(err_msg);
                    }
                }
                Ok(_) => {
                    trace!("Key is externally protected");
                    return Ok(Self {
                        key,
                        cert_fingerprint,
                    });
                }
                Err(e) => {
                    warn!("Failed to check lock status of key: {key_description}. Reason: {e}");
                    errors.push(e.to_string());
                }
            }
        }
        Err(error::PgpError::Error(if !errors.is_empty() {
            errors.join(", ")
        } else {
            format!("Unable to unlock private key: {valid_cert}")
        }))
    }
}

pub(crate) struct VerificationHelper<'cert_store, 'cert_store_ref> {
    pub(crate) cert_store: &'cert_store_ref CertStore<'cert_store>,
}

pub(crate) struct DecryptionHelper<'cert_store, 'cert_store_ref, 'key_store_ref, F> {
    pub(crate) cert_store: &'cert_store_ref CertStore<'cert_store>,
    pub(crate) key_store: &'key_store_ref mut KeyStore,
    pub(crate) password: F,
}

impl sequoia_openpgp::parse::stream::VerificationHelper for VerificationHelper<'_, '_> {
    fn get_certs(
        &mut self,
        ids: &[sequoia_openpgp::KeyHandle],
    ) -> sequoia_openpgp::Result<Vec<sequoia_openpgp::Cert>> {
        get_certs(self.cert_store, ids)
    }

    fn check(
        &mut self,
        structure: sequoia_openpgp::parse::stream::MessageStructure,
    ) -> sequoia_openpgp::Result<()> {
        check(structure)
    }
}

impl<F> sequoia_openpgp::parse::stream::VerificationHelper for DecryptionHelper<'_, '_, '_, F> {
    fn get_certs(
        &mut self,
        ids: &[sequoia_openpgp::KeyHandle],
    ) -> sequoia_openpgp::Result<Vec<sequoia_openpgp::Cert>> {
        get_certs(self.cert_store, ids)
    }

    fn check(
        &mut self,
        structure: sequoia_openpgp::parse::stream::MessageStructure,
    ) -> sequoia_openpgp::Result<()> {
        check(structure)
    }
}

fn check(
    structure: sequoia_openpgp::parse::stream::MessageStructure,
) -> sequoia_openpgp::Result<()> {
    use sequoia_openpgp::parse::stream::MessageLayer;
    for layer in structure.into_iter() {
        match layer {
            MessageLayer::Compression { algo } => trace!("Data compressed using {}", algo),
            MessageLayer::Encryption {
                sym_algo,
                aead_algo,
            } => match aead_algo {
                Some(aead_algo) => {
                    trace!(
                        "Data encrypted and protected using {}/{}",
                        sym_algo, aead_algo
                    )
                }
                None => trace!("Data encrypted using {}", sym_algo),
            },
            MessageLayer::SignatureGroup { results } => {
                if let Some(Err(err)) = results.into_iter().find(|item| item.is_err()) {
                    return Err(error::VerificationError::from(err).into());
                }
            }
        }
    }
    Ok(())
}

fn get_certs(
    cert_store: &CertStore<'_>,
    ids: &[sequoia_openpgp::KeyHandle],
) -> sequoia_openpgp::Result<Vec<sequoia_openpgp::Cert>> {
    Ok(ids
        .iter()
        .flat_map(|key_handle| {
            cert_store
                .get_certs_by_key_handle(key_handle)
                .unwrap_or_else(|e| {
                    tracing::warn!(?e);
                    Vec::new()
                })
        })
        .collect())
}

impl<F> sequoia_openpgp::parse::stream::DecryptionHelper for DecryptionHelper<'_, '_, '_, F>
where
    F: Fn(PasswordHint) -> crate::secret::Secret,
{
    #[tracing::instrument(skip_all)]
    fn decrypt(
        &mut self,
        pkesks: &[sequoia_openpgp::packet::PKESK],
        _skesks: &[sequoia_openpgp::packet::SKESK],
        sym_algo: Option<sequoia_openpgp::types::SymmetricAlgorithm>,
        decrypt: &mut dyn FnMut(
            Option<sequoia_openpgp::types::SymmetricAlgorithm>,
            &sequoia_openpgp::crypto::SessionKey,
        ) -> bool,
    ) -> sequoia_openpgp::Result<Option<sequoia_openpgp::Cert>> {
        let mut errors = Vec::new();
        match self.key_store.inner.decrypt(pkesks) {
            Ok((_i, fp, sym_algo, sk)) => {
                trace!(fingerprint=%fp, "Decrypted with an unlocked key");
                if decrypt(sym_algo, &sk) {
                    tracing::debug!("Decrypted data with key {fp}");
                    return Ok(Some(
                        self.cert_store.get_cert_by_fingerprint(&Fingerprint(fp))?.0,
                    ));
                }
            }
            Err(err) => {
                trace!("Unlocking decryption key");
                match err.downcast() {
                    Ok(sequoia_keystore::Error::InaccessibleDecryptionKey(keys)) => {
                        for key_status in keys.into_iter() {
                            let pkesk = key_status.pkesk().clone();
                            let mut key = key_status.into_key();
                            let protection = key.locked();
                            match protection {
                                Ok(sequoia_keystore::Protection::Password(_)) => {
                                    // Retrieve the user ID and primary
                                    // fingerprint of the certificate
                                    // associated with the decryption key.
                                    let fingerprint = Fingerprint(key.fingerprint());
                                    let policy = Default::default();
                                    let hint = if let Ok(cert) =
                                        self.cert_store.get_cert_by_fingerprint(&fingerprint)
                                        && let Ok(vc) = cert.validate(&policy)
                                    {
                                        super::cert::warn_if_cert_expires_soon(&vc.0);
                                        PasswordHint {
                                            fingerprint,
                                            userid: vc.userids().first().cloned(),
                                            fingerprint_primary: Some(vc.fingerprint()),
                                        }
                                    } else {
                                        PasswordHint {
                                            fingerprint,
                                            userid: None,
                                            fingerprint_primary: None,
                                        }
                                    };
                                    let key_description = hint_to_string(&hint);

                                    // Try to unlock the decryption subkey.
                                    // The password is retrieved via a call to
                                    // the "password callback", which can e.g.
                                    // prompt the user to enter a password.
                                    if let Ok(()) =
                                        key.unlock((self.password)(hint).as_inner().clone())
                                    {
                                        let (sym_algo, sk) = pkesk
                                            .decrypt(&mut key, sym_algo)
                                            .ok_or(error::PgpError::from("failed"))?;
                                        if decrypt(sym_algo, &sk) {
                                            let fp = key.fingerprint();
                                            tracing::debug!(
                                                "Decrypted data with key: {key_description}"
                                            );
                                            return Ok(Some(
                                                self.cert_store
                                                    .get_cert_by_fingerprint(&Fingerprint(fp))?
                                                    .0,
                                            ));
                                        }
                                    } else {
                                        let err_msg = format!(
                                            "The provided password failed to unlock key: {key_description}"
                                        );
                                        debug!(err_msg);
                                        errors.push(err_msg);
                                    }
                                }
                                Ok(p) => {
                                    let err_msg =
                                        format!("Unsupported key protection method {p:?}");
                                    debug!(err_msg);
                                    errors.push(err_msg);
                                }
                                Err(e) => {
                                    let err_msg = e.to_string();
                                    debug!(err_msg);
                                    errors.push(err_msg);
                                }
                            }
                        }
                    }
                    Ok(err) => {
                        let err_msg = format!("Unsupported key unlock operation ({err})");
                        debug!(err_msg);
                        errors.push(err_msg);
                    }
                    Err(err) => {
                        let err_msg = format!("Failed to decrypt using the keystore ({err})");
                        debug!(err_msg);
                        errors.push(err_msg);
                    }
                }
            }
        }
        // If this point is reached, no key to decrypt the data could be found
        // or successfully unlocked with the provided password.
        Err(ErrorForward(if !errors.is_empty() {
            errors.join(", ")
        } else {
            format!(
                "Unable to find any suitable private key for decryption (expected one of: {:?})",
                pkesks
                    .iter()
                    .filter_map(|pkesk| pkesk.recipient().map(|recipient| recipient.to_hex()))
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        })
        .into())
    }
}

/// Formats the password `hint` of an OpenPGP key as a string.
pub(super) fn hint_to_string(hint: &PasswordHint) -> String {
    if let Some(fingerprint_primary) = hint.fingerprint_primary.as_ref() {
        let userid = hint.userid.as_deref().unwrap_or("--missing user ID--");
        if fingerprint_primary == &hint.fingerprint {
            // Key is a primary key.
            format!("{userid} {fingerprint_primary}")
        } else {
            // Key is a subkey: both the primary and the subkey's fingerprints
            // are included in the string to help better identify the key.
            format!(
                "{} {} (subkey {})",
                userid, fingerprint_primary, hint.fingerprint
            )
        }
    } else {
        format!("{} (key is not part of a certificate)", hint.fingerprint)
    }
}