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
use std::fmt;
use time;

use Error;
use crypto::mpis;
use packet::Tag;
use packet;
use Packet;
use PublicKeyAlgorithm;
use SymmetricAlgorithm;
use crypto::s2k::S2K;
use Result;
use conversions::Time;
use crypto::Password;

/// Holds a public key, public subkey, private key or private subkey packet.
///
/// See [Section 5.5 of RFC 4880] for details.
///
///   [Section 5.5 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.5
#[derive(PartialEq, Eq, Hash, Clone)]
pub struct Key {
    /// CTB packet header fields.
    pub(crate) common: packet::Common,
    /// Version of the key packet. Must be 4.
    pub(crate) version: u8,
    /// When the key was created.
    pub(crate) creation_time: time::Tm,
    /// Public key algorithm of this signature.
    pub(crate) pk_algo: PublicKeyAlgorithm,
    /// Public key MPIs.
    pub(crate) mpis: mpis::PublicKey,
    /// Optional secret part of the key.
    pub(crate) secret: Option<SecretKey>,
}


impl fmt::Debug for Key {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Key")
            .field("fingerprint", &self.fingerprint())
            .field("version", &self.version)
            .field("creation_time", &format!("{}", self.creation_time.rfc3339()))
            .field("pk_algo", &self.pk_algo)
            .field("mpis", &self.mpis)
            .field("secret", &self.secret)
            .finish()
    }
}

impl fmt::Display for Key {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.fingerprint())
    }
}

impl Key {
    /// Returns a new `Key` packet.  This can be used to hold either a
    /// public key, a public subkey, a private key, or a private subkey.
    pub fn new(pk_algo: PublicKeyAlgorithm) -> Result<Self> {
        use nettle::{
            rsa,
            Yarrow,
            ed25519,ed25519::ED25519_KEY_SIZE,
            curve25519,curve25519::CURVE25519_SIZE,
        };
        use crypto::mpis::{self, MPI, PublicKey};
        use constants::{HashAlgorithm, SymmetricAlgorithm, Curve};
        use PublicKeyAlgorithm::*;
        use Error;

        #[allow(deprecated)]
        let (mpis, secret) = match pk_algo {
            RSASign | RSAEncrypt | RSAEncryptSign => {
                let mut rng = Yarrow::default();
                let (public,private) = rsa::generate_keypair(&mut rng, 3072)?;
                let (p,q,u) = private.as_rfc4880();
                let public_mpis = PublicKey::RSA {
                    e: MPI::new(&*public.e()),
                    n: MPI::new(&*public.n()),
                };
                let private_mpis = mpis::SecretKey::RSA {
                    d: MPI::new(&*private.d()),
                    p: MPI::new(&*p),
                    q: MPI::new(&*q),
                    u: MPI::new(&*u),
                };
                let sec = Some(SecretKey::Unencrypted{
                    mpis: private_mpis
                });

                (public_mpis, sec)
            }

            EdDSA => {
                let mut rng = Yarrow::default();
                let mut public = [0u8; ED25519_KEY_SIZE + 1];
                let mut private = [0u8; ED25519_KEY_SIZE];

                public[0] = 0x40;
                rng.random(&mut private);
                ed25519::public_key(&mut public[1..], &private)?;

                let public_mpis = PublicKey::EdDSA {
                    curve: Curve::Ed25519,
                    q: MPI::new(&public),
                };
                let private_mpis = mpis::SecretKey::EdDSA {
                    scalar: MPI::new(&private),
                };
                let sec = Some(SecretKey::Unencrypted{
                    mpis: private_mpis,
                });

                (public_mpis, sec)
            }

            ECDH => {
                let mut rng = Yarrow::default();
                let mut public = [0u8; CURVE25519_SIZE + 1];
                let mut private = [0u8; CURVE25519_SIZE];

                public[0] = 0x40;
                rng.random(&mut private);
                curve25519::mul_g(&mut public[1..], &private)?;

                // Reverse the scalar.  See
                // https://lists.gnupg.org/pipermail/gnupg-devel/2018-February/033437.html.
                private.reverse();

                let public_mpis = PublicKey::ECDH {
                    curve: Curve::Cv25519,
                    q: MPI::new(&public),
                    hash: HashAlgorithm::SHA256,
                    sym: SymmetricAlgorithm::AES256,
                };
                let private_mpis = mpis::SecretKey::ECDH {
                    scalar: MPI::new(&private),
                };
                let sec = Some(SecretKey::Unencrypted{
                    mpis: private_mpis,
                });

                (public_mpis, sec)
            }

            pk => {
                return Err(Error::UnsupportedPublicKeyAlgorithm(pk).into());
            }
        };

        Ok(Key {
            common: Default::default(),
            version: 4,
            creation_time: time::now().canonicalize(),
            pk_algo: pk_algo,
            mpis: mpis,
            secret: secret,
        })
    }

    /// Gets the key packet's version field.
    pub fn version(&self) -> u8 {
        self.version
    }

    /// Gets the key packet's creation time field.
    pub fn creation_time(&self) -> &time::Tm {
        &self.creation_time
    }

    /// Sets the key packet's creation time field.
    pub fn set_creation_time(&mut self, timestamp: time::Tm) {
        self.creation_time = timestamp.canonicalize();
    }

    /// Gets the public key algorithm.
    pub fn pk_algo(&self) -> PublicKeyAlgorithm {
        self.pk_algo
    }

    /// Sets the public key algorithm.
    pub fn set_pk_algo(&mut self, pk_algo: PublicKeyAlgorithm) {
        self.pk_algo = pk_algo;
    }

    /// Gets the key packet's MPIs.
    pub fn mpis(&self) -> &mpis::PublicKey {
        &self.mpis
    }

    /// Gets a mutable reference to the key packet's MPIs.
    pub fn mpis_mut(&mut self) -> &mut mpis::PublicKey {
        &mut self.mpis
    }

    /// Sets the key packet's MPIs.
    pub fn set_mpis(&mut self, mpis: mpis::PublicKey) {
        self.mpis = mpis;
    }

    /// Gets the key packet's SecretKey.
    pub fn secret(&self) -> Option<&SecretKey> {
        self.secret.as_ref()
    }

    /// Gets a mutable reference to the key packet's SecretKey.
    pub fn secret_mut(&mut self) -> Option<&mut SecretKey> {
        self.secret.as_mut()
    }

    /// Sets the key packet's SecretKey.
    pub fn set_secret(&mut self, secret: Option<SecretKey>) {
        self.secret = secret;
    }

    /// Convert the `Key` struct to a `Packet`.
    pub fn to_packet(self, tag: Tag) -> Packet {
        match tag {
            Tag::PublicKey => Packet::PublicKey(self),
            Tag::PublicSubkey => Packet::PublicSubkey(self),
            Tag::SecretKey => Packet::SecretKey(self),
            Tag::SecretSubkey => Packet::SecretSubkey(self),
            _ => panic!("Expected Tag::PublicKey, Tag::PublicSubkey, \
                         Tag::SecretKey, or Tag::SecretSubkey. \
                         Got: Tag::{:?}",
                        tag),
        }
    }
}

/// Holds the secret potion of a OpenPGP secret key or secret subkey packet.
///
/// This type allows postponing the decryption of the secret key until we need to use it.
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
pub enum SecretKey {
    /// Unencrypted secret key. Can be used as-is.
    Unencrypted {
        /// MPIs of the secret key.
        mpis: mpis::SecretKey,
    },
    /// The secret key is encrypted with a password.
    Encrypted {
        /// Key derivation mechanism to use.
        s2k: S2K,
        /// Symmetric algorithm used for encryption the secret key.
        algorithm: SymmetricAlgorithm,
        /// Encrypted MPIs prefixed with the IV.
        ciphertext: Box<[u8]>,
    },
}

impl SecretKey {
    /// Decrypts this secret key using `password`.
    ///
    /// The SecretKey type does not know what kind of key it is, so
    /// `pk_algo` is needed to parse the correct number of MPIs.
    pub fn decrypt(&self, pk_algo: PublicKeyAlgorithm, password: &Password)
                   -> Result<mpis::SecretKey> {
        use std::io::{Cursor, Read};
        use crypto::symmetric::Decryptor;

        match self {
            &SecretKey::Unencrypted { .. } =>
                Err(Error::InvalidOperation("Key is not encrypted".into())
                    .into()),
            &SecretKey::Encrypted { ref s2k, algorithm, ref ciphertext } => {
                let key = s2k.derive_key(password, algorithm.key_size()?)?;
                let mut cur = Cursor::new(ciphertext);
                let mut dec = Decryptor::new(algorithm, &key, cur)?;
                let mut trash = vec![0u8; algorithm.block_size()?];

                dec.read_exact(&mut trash)?;
                mpis::SecretKey::parse_chksumd(pk_algo, &mut dec)
            }
        }
    }
    /// Decrypts this secret key using `password`.
    ///
    /// The SecretKey type does not know what kind of key it is, so
    /// `pk_algo` is needed to parse the correct number of MPIs.
    pub fn decrypt_in_place(&mut self, pk_algo: PublicKeyAlgorithm,
                            password: &Password)
                            -> Result<()> {
        if self.is_encrypted() {
            *self = SecretKey::Unencrypted {
                mpis: self.decrypt(pk_algo, password)?,
            };
        }

        Ok(())
    }

    /// Returns true if this secret key is encrypted.
    pub fn is_encrypted(&self) -> bool {
        match self {
            &SecretKey::Encrypted { .. } => true,
            &SecretKey::Unencrypted { .. } => false,
        }
    }
}

#[cfg(test)]
mod tests {
    use packet::Tag;
    use TPK;
    use SecretKey;
    use std::path::PathBuf;
    use super::*;
    use PacketPile;
    use serialize::SerializeKey;

    fn path_to(artifact: &str) -> PathBuf {
        [env!("CARGO_MANIFEST_DIR"), "tests", "data", "keys", artifact]
            .iter().collect()
    }

    #[test]
    fn encrypted_rsa_key() {
        let mut tpk = TPK::from_file(
            path_to("testy-new-encrypted-with-123.pgp")).unwrap();
        let pair = tpk.primary_mut();
        let secret = pair.secret.as_mut().unwrap();

        assert!(secret.is_encrypted());
        secret.decrypt_in_place(pair.pk_algo, &"123".into()).unwrap();
        assert!(!secret.is_encrypted());

        match secret {
            &mut SecretKey::Unencrypted { mpis: mpis::SecretKey::RSA { .. } } =>
                {}
            _ => { unreachable!() }
        }
    }

    #[test]
    fn eq() {
        for &pk_algo in &[PublicKeyAlgorithm::RSAEncryptSign,
                          PublicKeyAlgorithm::EdDSA,
                          PublicKeyAlgorithm::ECDH] {
            let key = Key::new(pk_algo).unwrap();
            let clone = key.clone();
            assert_eq!(key, clone);
        }
    }

    #[test]
    fn roundtrip() {
        for &pk_algo in &[PublicKeyAlgorithm::RSAEncryptSign,
                          PublicKeyAlgorithm::EdDSA,
                          PublicKeyAlgorithm::ECDH] {
            let mut key = Key::new(pk_algo).unwrap();

            let mut b = Vec::new();
            key.serialize(&mut b, Tag::SecretKey).unwrap();

            let pp = PacketPile::from_bytes(&b).unwrap();
            if let Some(Packet::SecretKey(ref parsed_key)) = pp.path_ref(&[0]) {
                assert_eq!(key.common, parsed_key.common);
                assert_eq!(key.version, parsed_key.version);
                assert_eq!(key.creation_time, parsed_key.creation_time);
                assert_eq!(key.pk_algo, parsed_key.pk_algo);
                assert_eq!(key.mpis, parsed_key.mpis);
                assert_eq!(key.secret, parsed_key.secret);

                assert_eq!(&key, parsed_key);
            } else {
                panic!("bad packet: {:?}", pp.path_ref(&[0]));
            }

            let mut b = Vec::new();
            key.serialize(&mut b, Tag::PublicKey).unwrap();

            let pp = PacketPile::from_bytes(&b).unwrap();
            if let Some(Packet::PublicKey(ref parsed_key)) = pp.path_ref(&[0]) {
                assert!(parsed_key.secret().is_none());

                key.set_secret(None);
                assert_eq!(&key, parsed_key);
            } else {
                panic!("bad packet: {:?}", pp.path_ref(&[0]));
            }
        }
    }

    #[test]
    fn encryption_roundtrip() {
        use SecretKey;
        use crypto::SessionKey;
        use packet::PKESK;

        for &pk_algo in &[PublicKeyAlgorithm::RSAEncryptSign,
                          PublicKeyAlgorithm::ECDH] {
            let key = Key::new(pk_algo).unwrap();
            let secret =
                if let Some(SecretKey::Unencrypted {
                    ref mpis,
                }) = key.secret() {
                    mpis.clone()
                } else {
                    unreachable!()
                };

            let cipher = SymmetricAlgorithm::AES256;
            let sk = SessionKey::new(&mut Default::default(),
                                     cipher.key_size().unwrap());

            let pkesk = PKESK::new(cipher, &sk, &key).unwrap();
            let (cipher_, sk_) = pkesk.decrypt(&key, &secret).unwrap();

            assert_eq!(cipher, cipher_);
            assert_eq!(sk, sk_);
        }
    }
}