summaryrefslogtreecommitdiffstats
path: root/openpgp/src/tpk/tsk.rs
blob: 978affcbc2cd8b49fe58373a0e84e35fd96fc26b (plain)
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
use std::io;

use Result;
use TPK;
use packet::{Key, Tag};
use serialize::{Serialize, SerializeKey};

/// A reference to a TPK that allows serialization of secret keys.
///
/// To avoid accidental leakage `TPK::serialize()` skips secret keys.
/// To serialize `TPK`s with secret keys, use [`TPK::as_tsk()`] to
/// create a `TSK`, which is a shim on top of the `TPK`, and serialize
/// this.
///
/// [`TPK::as_tsk()`]: ../struct.TPK.html#method.as_tsk
///
/// # Example
/// ```
/// # use sequoia_openpgp::{*, tpk::*, parse::Parse, serialize::Serialize};
/// # f().unwrap();
/// # fn f() -> Result<()> {
/// let (tpk, _) = TPKBuilder::default().generate()?;
/// assert!(tpk.is_tsk());
///
/// let mut buf = Vec::new();
/// tpk.as_tsk().serialize(&mut buf)?;
///
/// let tpk_ = TPK::from_bytes(&buf)?;
/// assert!(tpk_.is_tsk());
/// assert_eq!(tpk, tpk_);
/// # Ok(()) }
pub struct TSK<'a> {
    tpk: &'a TPK,
    filter: Option<Box<'a + Fn(&'a Key) -> bool>>,
}

impl<'a> TSK<'a> {
    /// Creates a new view for the given `TPK`.
    pub(crate) fn new(tpk: &'a TPK) -> Self {
        Self {
            tpk: tpk,
            filter: None,
        }
    }

    /// Filters which secret keys to export using the given predicate.
    ///
    /// Note that the given filter replaces any existing filter.
    ///
    /// # Example
    /// ```
    /// # use sequoia_openpgp::{*, tpk::*, parse::Parse, serialize::Serialize};
    /// # f().unwrap();
    /// # fn f() -> Result<()> {
    /// let (tpk, _) = TPKBuilder::default().add_signing_subkey().generate()?;
    /// assert_eq!(tpk.keys_valid().secret(true).count(), 2);
    ///
    /// // Only write out the primary key's secret.
    /// let mut buf = Vec::new();
    /// tpk.as_tsk().set_filter(|k| k == tpk.primary()).serialize(&mut buf)?;
    ///
    /// let tpk_ = TPK::from_bytes(&buf)?;
    /// assert_eq!(tpk_.keys_valid().secret(true).count(), 1);
    /// assert!(tpk_.primary().secret().is_some());
    /// # Ok(()) }
    pub fn set_filter<P>(mut self, predicate: P) -> Self
        where P: 'a + Fn(&'a Key) -> bool
    {
        self.filter = Some(Box::new(predicate));
        self
    }
}

impl<'a> Serialize for TSK<'a> {
    fn serialize<W: io::Write>(&self, o: &mut W) -> Result<()> {
        // Serializes public or secret key depending on the filter.
        let serialize_key = |o: &mut W, key: &'a Key, tag_public, tag_secret| {
            key.serialize(o,
                          if self.filter.as_ref().map(
                              |f| f(key)).unwrap_or(true)
                          {
                              tag_secret
                          } else {
                              tag_public
                          })
        };
        serialize_key(o, &self.tpk.primary, Tag::PublicKey, Tag::SecretKey)?;

        for s in self.tpk.primary_selfsigs.iter() {
            s.serialize(o)?;
        }
        for s in self.tpk.primary_self_revocations.iter() {
            s.serialize(o)?;
        }
        for s in self.tpk.primary_certifications.iter() {
            s.serialize(o)?;
        }
        for s in self.tpk.primary_other_revocations.iter() {
            s.serialize(o)?;
        }

        for u in self.tpk.userids() {
            u.userid().serialize(o)?;
            for s in u.self_revocations() {
                s.serialize(o)?;
            }
            for s in u.selfsigs() {
                s.serialize(o)?;
            }
            for s in u.other_revocations() {
                s.serialize(o)?;
            }
            for s in u.certifications() {
                s.serialize(o)?;
            }
        }

        for u in self.tpk.user_attributes() {
            u.user_attribute().serialize(o)?;
            for s in u.self_revocations() {
                s.serialize(o)?;
            }
            for s in u.selfsigs() {
                s.serialize(o)?;
            }
            for s in u.other_revocations() {
                s.serialize(o)?;
            }
            for s in u.certifications() {
                s.serialize(o)?;
            }
        }

        for k in self.tpk.subkeys() {
            serialize_key(o, k.subkey(), Tag::PublicSubkey, Tag::SecretSubkey)?;
            for s in k.self_revocations() {
                s.serialize(o)?;
            }
            for s in k.selfsigs() {
                s.serialize(o)?;
            }
            for s in k.other_revocations() {
                s.serialize(o)?;
            }
            for s in k.certifications() {
                s.serialize(o)?;
            }
        }

        for u in self.tpk.unknowns.iter() {
            u.unknown.serialize(o)?;

            for s in u.sigs.iter() {
                s.serialize(o)?;
            }
        }

        for s in self.tpk.bad.iter() {
            s.serialize(o)?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use parse::Parse;
    use serialize::Serialize;

    fn test_tpk(name: &str) -> Result<TPK> {
        let path = format!("tests/data/keys/{}.pgp", name);
        TPK::from_file(path)
    }

    fn test_tsk(name: &str) -> Result<TPK> {
        let path = format!("tests/data/keys/{}-private.pgp", name);
        TPK::from_file(path)
    }

    const PUBLIC_TESTS: &[&str] = &[
        "dennis-simon-anton",
        "dsa2048-elgamal3072",
        "emmelie-dorothea-dina-samantha-awina-ed25519",
        "erika-corinna-daniela-simone-antonia-nistp256",
        "erika-corinna-daniela-simone-antonia-nistp384",
        "erika-corinna-daniela-simone-antonia-nistp521",
        "testy-new",
        "testy",
        "neal",
        "dkg-sigs-out-of-order",
    ];
    const SECRET_TESTS: &[&str] = &[
        "dennis-simon-anton",
        "dsa2048-elgamal3072",
        "emmelie-dorothea-dina-samantha-awina-ed25519",
        "erika-corinna-daniela-simone-antonia-nistp256",
        "erika-corinna-daniela-simone-antonia-nistp384",
        "erika-corinna-daniela-simone-antonia-nistp521",
        "testy-new",
        "testy-nistp256",
        "testy-nistp384",
        "testy-nistp521",
        "testy",
    ];

    /// Demonstrates that public keys and all components are
    /// serialized.
    #[test]
    fn roundtrip_tpk() {
        for test in PUBLIC_TESTS {
            let tpk = match test_tpk(dbg!(test)) {
                Ok(t) => t,