sequoia_openpgp/packet/skesk/
v6.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
//! Symmetric-Key Encrypted Session Key Packets.
//!
//! SKESK packets hold symmetrically encrypted session keys.  The
//! session key is needed to decrypt the actual ciphertext.  See
//! [Section 5.3 of RFC 4880] for details.
//!
//! [Section 5.3 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.3

use std::ops::{Deref, DerefMut};

#[cfg(test)]
use quickcheck::{Arbitrary, Gen};

use crate::Result;
use crate::crypto::{
    self,
    S2K,
    Password,
    SessionKey,
    backend::{Backend, interface::Kdf},
};
use crate::crypto::aead::CipherOp;
use crate::Error;
use crate::types::{
    AEADAlgorithm,
    SymmetricAlgorithm,
};
use crate::packet::{
    Packet,
    SKESK,
    skesk::SKESK4,
};

/// Holds an symmetrically encrypted session key version 6.
///
/// Holds an symmetrically encrypted session key.  The session key is
/// needed to decrypt the actual ciphertext.  See [Version 6 Symmetric
/// Key Encrypted Session Key Packet Format] for details.
///
/// [Version 6 Symmetric Key Encrypted Session Key Packet Format]: https://www.rfc-editor.org/rfc/rfc9580.html#name-version-6-symmetric-key-enc
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct SKESK6 {
    /// Common fields.
    pub(crate) skesk4: SKESK4,

    /// AEAD algorithm.
    aead_algo: AEADAlgorithm,

    /// Initialization vector for the AEAD algorithm.
    aead_iv: Box<[u8]>,
}
assert_send_and_sync!(SKESK6);

impl Deref for SKESK6 {
    type Target = SKESK4;

    fn deref(&self) -> &Self::Target {
        &self.skesk4
    }
}

impl DerefMut for SKESK6 {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.skesk4
    }
}

impl SKESK6 {
    /// Creates a new SKESK version 6 packet.
    ///
    /// The given symmetric algorithm is the one used to encrypt the
    /// session key.
    pub fn new(sym_algo: SymmetricAlgorithm,
               aead_algo: AEADAlgorithm,
               s2k: S2K,
               aead_iv: Box<[u8]>,
               esk: Box<[u8]>)
               -> Result<Self> {
        Ok(SKESK6 {
            skesk4: SKESK4 {
                common: Default::default(),
                version: 6,
                sym_algo,
                s2k,
                esk: Ok(Some(esk)),
            },
            aead_algo,
            aead_iv,
        })
    }

    /// Creates a new SKESK version 6 packet with the given password.
    ///
    /// This function takes two [`SymmetricAlgorithm`] arguments: The
    /// first, `payload_algo`, is the algorithm used to encrypt the
    /// message's payload (i.e. the one used in the [`SEIP`]), and the
    /// second, `esk_algo`, is used to encrypt the session key.
    /// Usually, one should use the same algorithm, but if they
    /// differ, the `esk_algo` should be at least as strong as the
    /// `payload_algo` as not to weaken the security of the payload
    /// encryption.
    ///
    ///   [`SymmetricAlgorithm`]: crate::types::SymmetricAlgorithm
    ///   [`SEIP`]: crate::packet::SEIP
    pub fn with_password(payload_algo: SymmetricAlgorithm,
                         esk_algo: SymmetricAlgorithm,
                         esk_aead: AEADAlgorithm, s2k: S2K,
                         session_key: &SessionKey, password: &Password)
                         -> Result<Self> {
        if session_key.len() != payload_algo.key_size()? {
            return Err(Error::InvalidArgument(format!(
                "Invalid size of session key, got {} want {}",
                session_key.len(), payload_algo.key_size()?)).into());
        }

        // Derive key and make a cipher.
        let ad = [0xc3, 6, esk_algo.into(), esk_aead.into()];
        let key = s2k.derive_key(password, esk_algo.key_size()?)?;

        let mut kek: SessionKey = vec![0; esk_algo.key_size()?].into();
        Backend::hkdf_sha256(&key, None, &ad, &mut kek)?;


        // Encrypt the session key with the KEK.
        let mut iv = vec![0u8; esk_aead.nonce_size()?];
        crypto::random(&mut iv);
        let mut ctx =
            esk_aead.context(esk_algo, &kek, &ad, &iv, CipherOp::Encrypt)?;
        let mut esk_digest =
            vec![0u8; session_key.len() + esk_aead.digest_size()?];
        ctx.encrypt_seal(&mut esk_digest, session_key)?;

        // Attach digest to the ESK, we model it as one.
        SKESK6::new(esk_algo, esk_aead, s2k, iv.into_boxed_slice(),
                    esk_digest.into())
    }

    /// Derives the key inside this `SKESK6` from `password`.
    ///
    /// Returns a tuple containing a placeholder symmetric cipher and
    /// the key itself.  `SKESK6` packets do not contain the symmetric
    /// cipher algorithm and instead rely on the `AED` packet that
    /// contains it.
    pub fn decrypt(&self, password: &Password)
                   -> Result<SessionKey> {
        let key = self.s2k().derive_key(password,
                                        self.symmetric_algo().key_size()?)?;

        let mut kek: SessionKey =
            vec![0; self.symmetric_algo().key_size()?].into();
        let ad = [0xc3,
                  6 /* Version.  */,
                  self.symmetric_algo().into(),
                  self.aead_algo.into()];
        Backend::hkdf_sha256(&key, None, &ad, &mut kek)?;

        // Use the derived key to decrypt the ESK.
        let mut cipher = self.aead_algo.context(
            self.symmetric_algo(), &kek, &ad, self.aead_iv(),
            CipherOp::Decrypt)?;

        let mut plain: SessionKey =
            vec![0; self.esk().len() - self.aead_algo.digest_size()?].into();
        cipher.decrypt_verify(&mut plain, self.esk())?;
        Ok(plain)
    }

    /// Gets the AEAD algorithm.
    pub fn aead_algo(&self) -> AEADAlgorithm {
        self.aead_algo
    }

    /// Sets the AEAD algorithm.
    pub fn set_aead_algo(&mut self, algo: AEADAlgorithm) -> AEADAlgorithm {
        ::std::mem::replace(&mut self.aead_algo, algo)
    }

    /// Gets the AEAD initialization vector.
    pub fn aead_iv(&self) -> &[u8] {
        &self.aead_iv
    }

    /// Sets the AEAD initialization vector.
    pub fn set_aead_iv(&mut self, iv: Box<[u8]>) -> Box<[u8]> {
        ::std::mem::replace(&mut self.aead_iv, iv)
    }

    /// Gets the encrypted session key.
    pub fn esk(&self) -> &[u8] {
        self.skesk4.raw_esk()
    }

    /// Sets the encrypted session key.
    pub fn set_esk(&mut self, esk: Box<[u8]>) -> Box<[u8]> {
        ::std::mem::replace(&mut self.esk, Ok(Some(esk)))
            .expect("v6 SKESK can always be parsed")
            .expect("v6 SKESK packets always have an ESK")
    }
}

impl From<SKESK6> for super::SKESK {
    fn from(p: SKESK6) -> Self {
        super::SKESK::V6(p)
    }
}

impl From<SKESK6> for Packet {
    fn from(s: SKESK6) -> Self {
        Packet::SKESK(SKESK::V6(s))
    }
}

#[cfg(test)]
impl Arbitrary for SKESK6 {
    fn arbitrary(g: &mut Gen) -> Self {
        let algo = AEADAlgorithm::const_default();
        let mut iv = vec![0u8; algo.nonce_size().unwrap()];
        for b in iv.iter_mut() {
            *b = u8::arbitrary(g);
        }
        let esk_len =
            (u8::arbitrary(g) % 64) as usize + algo.digest_size().unwrap();
        let mut esk = vec![0u8; esk_len];
        for b in esk.iter_mut() {
            *b = u8::arbitrary(g);
        }
        SKESK6::new(SymmetricAlgorithm::arbitrary(g),
                    algo,
                    S2K::arbitrary(g),
                    iv.into(),
                    esk.into())
            .unwrap()
    }
}

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

    quickcheck! {
        fn roundtrip_v6(p: SKESK6) -> bool {
            let p = SKESK::from(p);
            let q = SKESK::from_bytes(&p.to_vec().unwrap()).unwrap();
            assert_eq!(p, q);
            true
        }
    }

    /// This sample packet is from RFC9580.
    #[test]
    fn v6skesk_aes128_ocb() -> Result<()> {
        sample_skesk6_packet(
            SymmetricAlgorithm::AES128,
            AEADAlgorithm::OCB,
            "crypto-refresh/v6skesk-aes128-ocb.pgp",
            b"\xe8\x0d\xe2\x43\xa3\x62\xd9\x3b\
              \x9d\xc6\x07\xed\xe9\x6a\x73\x56",
            b"\x28\xe7\x9a\xb8\x23\x97\xd3\xc6\
              \x3d\xe2\x4a\xc2\x17\xd7\xb7\x91")
    }

    /// This sample packet is from RFC9580.
    #[test]
    fn v6skesk_aes128_eax() -> Result<()> {
        sample_skesk6_packet(
            SymmetricAlgorithm::AES128,
            AEADAlgorithm::EAX,
            "crypto-refresh/v6skesk-aes128-eax.pgp",
            b"\x15\x49\x67\xe5\x90\xaa\x1f\x92\
              \x3e\x1c\x0a\xc6\x4c\x88\xf2\x3d",
            b"\x38\x81\xba\xfe\x98\x54\x12\x45\
              \x9b\x86\xc3\x6f\x98\xcb\x9a\x5e")
    }

    /// This sample packet is from RFC9580.
    #[test]
    fn v6skesk_aes128_gcm() -> Result<()> {
        sample_skesk6_packet(
            SymmetricAlgorithm::AES128,
            AEADAlgorithm::GCM,
            "crypto-refresh/v6skesk-aes128-gcm.pgp",
            b"\x25\x02\x81\x71\x5b\xba\x78\x28\
              \xef\x71\xef\x64\xc4\x78\x47\x53",
            b"\x19\x36\xfc\x85\x68\x98\x02\x74\
              \xbb\x90\x0d\x83\x19\x36\x0c\x77")
    }

    fn sample_skesk6_packet(cipher: SymmetricAlgorithm,
                            aead: AEADAlgorithm,
                            name: &str,
                            derived_key: &[u8],
                            session_key: &[u8])
                            -> Result<()> {
        let password: Password = String::from("password").into();
        let packets: Vec<Packet> =
            PacketPile::from_bytes(
                crate::tests::file(name))?
            .into_children().collect();
        assert_eq!(packets.len(), 2);
        if let Packet::SKESK(SKESK::V6(ref s)) = packets[0] {
            let derived = s.s2k().derive_key(
                &password, s.symmetric_algo().key_size()?)?;
            eprintln!("derived: {:x?}", &derived[..]);
            assert_eq!(&derived[..], derived_key);

            if aead.is_supported()
                && aead.supports_symmetric_algo(&cipher)
            {
                let sk = s.decrypt(&password)?;
                eprintln!("sk: {:x?}", &sk[..]);
                assert_eq!(&sk[..], session_key);
            } else {
                eprintln!("{}-{} is not supported, skipping decryption.",
                          cipher, aead);
            }
        } else {
            panic!("bad packet, expected v6 SKESK: {:?}", packets[0]);
        }

        Ok(())
    }
}