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
//! DANE protocol client.
//!
//! [DANE] is a protocol for retrieving and storing OpenPGP
//! certificates in the DNS.
//!
//! [DANE]: https://datatracker.ietf.org/doc/html/rfc7929

use std::time::Duration;

use base64::{Engine as _, engine::general_purpose};

use super::email::EmailAddress;

use sequoia_openpgp::{
    self as openpgp,
    fmt,
    Cert,
    Packet,
    parse::Parse,
    serialize::SerializeInto,
    types::{HashAlgorithm, RevocationStatus},
    cert::prelude::*,
};

use super::Result;

use hickory_client::rr::{RData, RecordType};
use hickory_resolver::config::ResolverOpts;
use hickory_resolver::TokioAsyncResolver;

/// Generates a Fully Qualified Domain Name that holds the OPENPGPKEY
/// record for given `local` and `domain` parameters.
///
/// See: <https://datatracker.ietf.org/doc/html/rfc7929>
fn generate_fqdn(local: &str, domain: &str) -> Result<String> {
    let mut ctx = HashAlgorithm::SHA256.context()?;
    ctx.update(local.as_bytes());

    let mut digest = vec![0; ctx.digest_size()];
    ctx.digest(&mut digest)?;

    Ok(format!(
        "{}._openpgpkey.{}",
        fmt::hex::encode(&digest[..28]),
        domain
    ))
}

/// Retrieves raw values for `OPENPGPKEY` records for User IDs with a
/// given e-mail address using the [DANE] protocol.
///
/// This function unconditionally validates DNSSEC records and returns
/// the found certificates only on validation success.
///
/// [DANE]: https://datatracker.ietf.org/doc/html/rfc7929
async fn get_raw(email_address: impl AsRef<str>) -> Result<Vec<Vec<u8>>> {
    let email_address = EmailAddress::from(email_address)?;
    let fqdn = generate_fqdn(&email_address.local_part, &email_address.domain)?;

    let mut opts = ResolverOpts::default();
    opts.validate = true;

    let resolver = TokioAsyncResolver::tokio(Default::default(), opts);

    let answers = resolver
        .lookup(fqdn, RecordType::OPENPGPKEY)
        .await
        .map_err(Error::NotFound)?;

    let mut bytes = vec![];

    for record in answers.iter() {
        if let RData::OPENPGPKEY(key) = record {
            bytes.push(key.public_key().into());
        }
    }

    Ok(bytes)
}

/// Retrieves certificates that contain User IDs with a given e-mail
/// address using the [DANE] protocol.
///
/// This function unconditionally validates DNSSEC records and returns
/// the found certificates only on validation success.
///
/// [DANE]: https://datatracker.ietf.org/doc/html/rfc7929
///
/// # Examples
///
/// ```no_run
/// # use sequoia_net::{Result, dane};
/// # use sequoia_openpgp::Cert;
/// # async fn f() -> Result<()> {
/// let email_address = "john@example.com";
/// let certs = dane::get(email_address).await?;
/// # Ok(())
/// # }
/// ```
pub async fn get(email_address: impl AsRef<str>) -> Result<Vec<Result<Cert>>> {
    let mut certs = vec![];

    for bytes in get_raw(email_address).await?.iter() {
        // Section 2 of RFC7929 says that a record may only contain a
        // single cert, but there may be more than one record:
        //
        //   A user that wishes to specify more than one OpenPGP key,
        //   for example, because they are transitioning to a newer
        //   stronger key, can do so by adding multiple OPENPGPKEY
        //   records.  A single OPENPGPKEY DNS record MUST only
        //   contain one OpenPGP key.
        certs.push(Cert::from_bytes(bytes));
    }

    Ok(certs)
}

/// Generates a [DANE] record for the given cert in the zonefile
/// format.
///
/// Only user IDs with email addresses in `fqdn` are considered.
///
/// If `ttl` is `None`, records are cached for three hours.
///
/// We make an effort to shrink the certificate so that it fits within
/// `size_target`.  However, this is a best-effort mechanism, and we
/// may emit larger resource records.  If `size_target` is `None`, we
/// try to shrink the certificates to 12k.
///
/// [DANE]: https://datatracker.ietf.org/doc/html/rfc7929
pub fn generate<'a, F, T, L>(cert: &ValidCert<'a>, fqdn: F, ttl: T,
                             size_target: L)
                             -> Result<Vec<String>>
where
    F: AsRef<str>,
    T: Into<Option<Duration>>,
    L: Into<Option<usize>>,
{
    generate_(cert, fqdn.as_ref(), ttl.into(), size_target.into(), false)
}

/// Generates a [DANE] record for the given cert in the zonefile
/// format.
///
/// This is like [`generate`], but uses the generic syntax for servers
/// that do not support the OPENPGPKEY RRtype.
///
/// Only user IDs with email addresses in `fqdn` are considered.
///
/// If `ttl` is `None`, records are cached for three hours.
///
/// We make an effort to shrink the certificate so that it fits within
/// `size_target`.  However, this is a best-effort mechanism, and we
/// may emit larger resource records.  If `size_target` is `None`, we
/// try to shrink the certificates to 12k.
///
/// [DANE]: https://datatracker.ietf.org/doc/html/rfc7929
pub fn generate_generic<'a, F, T, L>(cert: &ValidCert<'a>, fqdn: F, ttl: T,
                                     size_target: L)
                                     -> Result<Vec<String>>
where
    F: AsRef<str>,
    T: Into<Option<Duration>>,
    L: Into<Option<usize>>,
{
    generate_(cert, fqdn.as_ref(), ttl.into(), size_target.into(), true)
}

fn generate_<'a>(cert: &ValidCert<'a>, fqdn: &str, ttl: Option<Duration>,
                 size_target: Option<usize>, generic: bool)
                 -> Result<Vec<String>>
{
    let ttl = ttl.unwrap_or(Duration::new(3 * 60 * 60, 0));
    // This is somewhat arbitrary, but Gandi doesn't like the
    // records being larger than 16k under base64 encoding.
    let size_target = size_target.unwrap_or(16384 / 4 * 3);

    let policy = cert.policy();
    let time = cert.time();

    // First, check which UserIDs are in `domain`.
    let mut addresses: Vec<_> =
        cert.userids().filter_map(|uidb| {
            uidb.userid().email2().unwrap_or(None)
                .and_then(|e| EmailAddress::from(e).ok())
                .filter(|e| e.domain == fqdn)
        })
        .collect();

    // We want to emit one record per email-address, even if multiple
    // user IDs map to that address.
    addresses.sort();
    addresses.dedup();

    // Any?
    if addresses.is_empty() {
        return Err(openpgp::Error::InvalidArgument(
            format!("Cert {} does not have a User ID in {}", cert, fqdn)
        ).into());
    }

    let mut records = Vec::new();
    for email in addresses.into_iter() {
        // Create a trimmed down view of cert, following the advice in
        // RFC7929, Section 2.1.2.  Reducing the Transferable Public
        // Key Size.

        // 1. & 2. Retain all user IDs matching the current email
        // address, no user attribute.
        let mut cert = cert.cert().clone()
            .retain_userids(
                |u| u.email2().unwrap_or(None)
                    .and_then(|e| EmailAddress::from(e).ok())
                    .as_ref() == Some(&email))
            .retain_user_attributes(|_| false);

        // 3a. Keep only alive subkeys.
        if cert.serialized_len() > size_target {
            cert = cert.retain_subkeys(
                |s| s.with_policy(policy, time)
                    .map(|s| s.alive().is_ok()).unwrap_or(false));
        }

        // 3b. For expired components, only keep the component and
        // revocation signatures.
        if cert.serialized_len() > size_target {
            let mut acc: Vec<Packet> = Vec::new();
            let vcert = cert.with_policy(policy, time)?;
            acc.push(vcert.primary_key().key().clone().into());
            vcert.primary_key().signatures()
                .for_each(|s| acc.push(s.clone().into()));

            for uidb in vcert.userids() {
                acc.push(uidb.userid().clone().into());
                match uidb.revocation_status() {
                    | RevocationStatus::Revoked(revs)
                    | RevocationStatus::CouldBe(revs) => {
                        revs.iter()
                            .for_each(|&s| acc.push(s.clone().into()));
                    },
                    RevocationStatus::NotAsFarAsWeKnow => {
                        uidb.signatures()
                            .for_each(|s| acc.push(s.clone().into()));
                    },
                }
            }

            for skb in vcert.keys().subkeys() {
                acc.push(skb.key().clone().into());
                match skb.revocation_status() {
                    | RevocationStatus::Revoked(revs)
                    | RevocationStatus::CouldBe(revs) => {
                        revs.iter()
                            .for_each(|&s| acc.push(s.clone().into()));
                    },
                    RevocationStatus::NotAsFarAsWeKnow => {
                        skb.signatures()
                            .for_each(|s| acc.push(s.clone().into()));
                    },
                }
            }

            cert = Cert::from_packets(acc.into_iter())?;
        }

        // 4. Only keep the current binding signatures.
        if cert.serialized_len() > size_target {
            let mut acc: Vec<Packet> = Vec::new();
            let vcert = cert.with_policy(policy, time)?;
            acc.push(vcert.primary_key().key().clone().into());
            acc.push(vcert.primary_key().binding_signature().clone().into());
            vcert.primary_key().self_revocations()
                .chain(vcert.primary_key().other_revocations())
                .chain(vcert.primary_key().certifications())
                .for_each(|s| acc.push(s.clone().into()));

            for uidb in vcert.userids() {
                acc.push(uidb.userid().clone().into());
                acc.push(uidb.binding_signature().clone().into());
                uidb.self_revocations()
                    .chain(uidb.other_revocations())
                    .chain(uidb.certifications())
                    .for_each(|s| acc.push(s.clone().into()));
            }

            for skb in vcert.keys().subkeys() {
                acc.push(skb.key().clone().into());
                acc.push(skb.binding_signature().clone().into());
                skb.self_revocations()
                    .chain(skb.other_revocations())
                    .chain(skb.certifications())
                    .for_each(|s| acc.push(s.clone().into()));
            }

            cert = Cert::from_packets(acc.into_iter())?;
        }

        // 5. Strip third-party certifications.
        if cert.serialized_len() > size_target {
            let mut acc: Vec<Packet> = Vec::new();
            let vcert = cert.with_policy(policy, time)?;
            acc.push(vcert.primary_key().key().clone().into());
            acc.push(vcert.primary_key().binding_signature().clone().into());
            vcert.primary_key().self_revocations()
                .chain(vcert.primary_key().other_revocations())
                .for_each(|s| acc.push(s.clone().into()));

            for uidb in vcert.userids() {
                acc.push(uidb.userid().clone().into());
                acc.push(uidb.binding_signature().clone().into());
                uidb.self_revocations()
                    .chain(uidb.other_revocations())
                    .for_each(|s| acc.push(s.clone().into()));
            }

            for skb in vcert.keys().subkeys() {
                acc.push(skb.key().clone().into());
                acc.push(skb.binding_signature().clone().into());
                skb.self_revocations()
                    .chain(skb.other_revocations())
                    .for_each(|s| acc.push(s.clone().into()));
            }

            cert = Cert::from_packets(acc.into_iter())?;
        }

        let bin = cert.to_vec()?;
        if generic {
            records.push(format!(
                "; {} => {}\n{}. {} IN TYPE61 \\# {} {}",
                email,
                cert.fingerprint(),
                generate_fqdn(&email.local_part, fqdn)?,
                ttl.as_secs(),
                bin.len(),
                openpgp::fmt::hex::encode(&bin)));
        } else {
            records.push(format!(
                "; {} => {}\n{}. {} IN OPENPGPKEY {}",
                email,
                cert.fingerprint(),
                generate_fqdn(&email.local_part, fqdn)?,
                ttl.as_secs(),
                general_purpose::STANDARD.encode(&bin)));
        }
    }

    Ok(records)
}

/// Errors for this module.
#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum Error {
    /// A requested cert was not found.
    #[error("Cert not found")]
    NotFound(#[from] hickory_resolver::error::ResolveError),
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_generating_fqdn() {
        assert_eq!(
            generate_fqdn("dkg", "debian.org").unwrap(),
            "A47CB586A51ACB93ACB9EF806F35F29131548E59E2FACD58CF6232E3._openpgpkey.debian.org"
        );
    }

    #[test]
    fn test_generating_fqdn_lower_case() {
        // Must NOT lowercase "DKG" into "dkg".
        // See: https://datatracker.ietf.org/doc/html/rfc7929#section-4
        assert_eq!(
            generate_fqdn("DKG", "DEBIAN.ORG").unwrap(),
            "46DE800073B375157AD8F4371E2713E118E3128FB1B4321ACE452F95._openpgpkey.DEBIAN.ORG"
        );
    }

    #[test]
    fn test_generate() -> Result<()> {
        let p = openpgp::policy::StandardPolicy::new();
        let (cert, _) = openpgp::cert::CertBuilder::new()
            .add_userid("dkg <dkg@debian.org>")
            .add_userid("dkg <dkg@somethingsomethinghorsesomething.org>")
            .add_transport_encryption_subkey()
            .generate()?;
        let vcert = cert.with_policy(&p, None)?;
        let records = generate(&vcert, "debian.org", None, None)?;
        assert_eq!(records.len(), 1);
        let record = &records[0];
        eprintln!("{}", record);
        assert!(record.starts_with(&format!(
            "; dkg@debian.org => {}\n\
             A47CB586A51ACB93ACB9EF806F35F29131548E59E2FACD58CF6232E3\
             ._openpgpkey.debian.org. 10800 IN OPENPGPKEY ",
            cert.fingerprint())));
        let asc = record.split(' ').last().unwrap();
        let bin = general_purpose::STANDARD.decode(&asc)?;
        let c = Cert::from_bytes(&bin)?;
        assert_eq!(c.userids().count(), 1);

        Ok(())
    }

    #[test]
    fn test_generate_aliasing() -> Result<()> {
        let p = openpgp::policy::StandardPolicy::new();
        let (cert, _) = openpgp::cert::CertBuilder::new()
            .add_userid("dkg")
            .add_userid("dkg <dkg@debian.org>")
            .add_userid("<dkg@debian.org>")
            .add_userid("dkg@debian.org")
            .add_userid("dkg <dkg@somethingsomethinghorsesomething.org>")
            .add_transport_encryption_subkey()
            .generate()?;
        let vcert = cert.with_policy(&p, None)?;
        let records = generate(&vcert, "debian.org", None, None)?;
        assert_eq!(records.len(), 1);
        let record = &records[0];
        eprintln!("{}", record);
        assert!(record.starts_with(&format!(
            "; dkg@debian.org => {}\n\
             A47CB586A51ACB93ACB9EF806F35F29131548E59E2FACD58CF6232E3\
             ._openpgpkey.debian.org. 10800 IN OPENPGPKEY ",
            cert.fingerprint())));
        let asc = record.split(' ').last().unwrap();
        let bin = general_purpose::STANDARD.decode(&asc)?;
        let c = Cert::from_bytes(&bin)?;
        assert_eq!(c.userids().count(), 3);

        Ok(())
    }

    #[test]
    fn test_generate_disjoint() -> Result<()> {
        let p = openpgp::policy::StandardPolicy::new();
        let (cert, _) = openpgp::cert::CertBuilder::new()
            .add_userid("dkg")
            .add_userid("dkg <dkg@debian.org>")
            .add_userid("dkg <evildkg@debian.org>")
            .add_userid("dkg <dkg@somethingsomethinghorsesomething.org>")
            .add_transport_encryption_subkey()
            .generate()?;
        let vcert = cert.with_policy(&p, None)?;
        let records = generate(&vcert, "debian.org", None, None)?;
        assert_eq!(records.len(), 2);
        for record in records {
            eprintln!("{}", record);
            let asc = record.split(' ').last().unwrap();
            let bin = general_purpose::STANDARD.decode(&asc)?;
            let c = Cert::from_bytes(&bin)?;
            assert_eq!(c.userids().count(), 1);
        }

        Ok(())
    }

    #[test]
    fn test_generate_generic() -> Result<()> {
        let p = openpgp::policy::StandardPolicy::new();
        let (cert, _) = openpgp::cert::CertBuilder::new()
            .add_userid("dkg <dkg@debian.org>")
            .add_transport_encryption_subkey()
            .generate()?;
        let vcert = cert.with_policy(&p, None)?;
        let records =
            generate_generic(&vcert, "debian.org", Duration::new(300, 0), None)?;
        assert_eq!(records.len(), 1);
        let record = &records[0];
        eprintln!("{}", record);
        assert!(record.starts_with(&format!(
            "; dkg@debian.org => {}\n\
             A47CB586A51ACB93ACB9EF806F35F29131548E59E2FACD58CF6232E3\
             ._openpgpkey.debian.org. 300 IN TYPE61 \\# {} ",
            cert.fingerprint(),
            cert.serialized_len())));
        let asc = record.split(' ').last().unwrap();
        let bin = openpgp::fmt::hex::decode(&asc)?;
        let c = Cert::from_bytes(&bin)?;
        assert_eq!(c.userids().count(), 1);

        Ok(())
    }
}