aws_lc_rs/aead/
chacha20_poly1305_openssh.rs

1// Copyright 2016 Brian Smith.
2// SPDX-License-Identifier: ISC
3// Modifications copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0 OR ISC
5
6//! The [chacha20-poly1305@openssh.com] AEAD-ish construct.
7//!
8//! This should only be used by SSH implementations. It has a similar, but
9//! different API from `aws_lc_rs::aead` because the construct cannot use the same
10//! API as `aws_lc_rs::aead` due to the way the construct handles the encrypted
11//! packet length.
12//!
13//! The concatenation of a and b is denoted `a||b`. `K_1` and `K_2` are defined
14//! in the [chacha20-poly1305@openssh.com] specification. `packet_length`,
15//! `padding_length`, `payload`, and `random padding` are defined in
16//! [RFC 4253]. The term `plaintext` is used as a shorthand for
17//! `padding_length||payload||random padding`.
18//!
19//! [chacha20-poly1305@openssh.com]:
20//!    http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.chacha20poly1305?annotate=HEAD
21//! [RFC 4253]: https://tools.ietf.org/html/rfc4253
22//!
23//! # FIPS
24//! The APIs offered in this module must not be used.
25
26use super::{poly1305, Nonce, Tag};
27use crate::cipher::block::BLOCK_LEN;
28use crate::cipher::chacha::{self, ChaCha20Key};
29use crate::endian::BigEndian;
30use crate::iv::FixedLength;
31use crate::{constant_time, error};
32
33/// A key for sealing packets.
34pub struct SealingKey {
35    key: Key,
36}
37
38impl SealingKey {
39    /// Constructs a new `SealingKey`.
40    #[must_use]
41    pub fn new(key_material: &[u8; KEY_LEN]) -> SealingKey {
42        SealingKey {
43            key: Key::new(key_material),
44        }
45    }
46
47    /// Seals (encrypts and signs) a packet.
48    ///
49    /// On input, `plaintext_in_ciphertext_out` must contain the unencrypted
50    /// `packet_length||plaintext` where `plaintext` is the
51    /// `padding_length||payload||random padding`. It will be overwritten by
52    /// `encrypted_packet_length||ciphertext`, where `encrypted_packet_length`
53    /// is encrypted with `K_1` and `ciphertext` is encrypted by `K_2`.
54    //
55    // # FIPS
56    // This method must not be used.
57    #[inline]
58    pub fn seal_in_place(
59        &self,
60        sequence_number: u32,
61        plaintext_in_ciphertext_out: &mut [u8],
62        tag_out: &mut [u8; TAG_LEN],
63    ) {
64        let nonce = make_nonce(sequence_number);
65        let poly_key = derive_poly1305_key(&self.key.k_2, Nonce(FixedLength::from(nonce.as_ref())));
66
67        {
68            let (len_in_out, data_and_padding_in_out) =
69                plaintext_in_ciphertext_out.split_at_mut(PACKET_LENGTH_LEN);
70
71            self.key.k_1.encrypt_in_place(nonce.as_ref(), len_in_out, 0);
72            self.key
73                .k_2
74                .encrypt_in_place(nonce.as_ref(), data_and_padding_in_out, 1);
75        }
76
77        let Tag(tag, tag_len) = poly1305::sign(poly_key, plaintext_in_ciphertext_out);
78        debug_assert_eq!(TAG_LEN, tag_len);
79        tag_out.copy_from_slice(tag.as_ref());
80    }
81}
82
83/// A key for opening packets.
84pub struct OpeningKey {
85    key: Key,
86}
87
88impl OpeningKey {
89    /// Constructs a new `OpeningKey`.
90    #[must_use]
91    pub fn new(key_material: &[u8; KEY_LEN]) -> OpeningKey {
92        OpeningKey {
93            key: Key::new(key_material),
94        }
95    }
96
97    /// Returns the decrypted, but unauthenticated, packet length.
98    ///
99    /// Importantly, the result won't be authenticated until `open_in_place` is
100    /// called.
101    //
102    // # FIPS
103    // This method must not be used.
104    #[inline]
105    #[must_use]
106    pub fn decrypt_packet_length(
107        &self,
108        sequence_number: u32,
109        encrypted_packet_length: [u8; PACKET_LENGTH_LEN],
110    ) -> [u8; PACKET_LENGTH_LEN] {
111        let mut packet_length = encrypted_packet_length;
112        let nonce = make_nonce(sequence_number);
113        self.key
114            .k_1
115            .encrypt_in_place(nonce.as_ref(), &mut packet_length, 0);
116        packet_length
117    }
118
119    /// Opens (authenticates and decrypts) a packet.
120    ///
121    /// `ciphertext_in_plaintext_out` must be of the form
122    /// `encrypted_packet_length||ciphertext` where `ciphertext` is the
123    /// encrypted `plaintext`. When the function succeeds the ciphertext is
124    /// replaced by the plaintext and the result is `Ok(plaintext)`, where
125    /// `plaintext` is `&ciphertext_in_plaintext_out[PACKET_LENGTH_LEN..]`;
126    /// otherwise the contents of `ciphertext_in_plaintext_out` are unspecified
127    /// and must not be used.
128    ///
129    /// # Errors
130    /// `error::Unspecified` when ciphertext is invalid
131    //
132    // # FIPS
133    // This method must not be used.
134    #[inline]
135    pub fn open_in_place<'a>(
136        &self,
137        sequence_number: u32,
138        ciphertext_in_plaintext_out: &'a mut [u8],
139        tag: &[u8; TAG_LEN],
140    ) -> Result<&'a [u8], error::Unspecified> {
141        let nonce = make_nonce(sequence_number);
142
143        // We must verify the tag before decrypting so that
144        // `ciphertext_in_plaintext_out` is unmodified if verification fails.
145        // This is beyond what we guarantee.
146        let poly_key = derive_poly1305_key(&self.key.k_2, Nonce(FixedLength::from(nonce.as_ref())));
147        verify(poly_key, ciphertext_in_plaintext_out, tag)?;
148
149        let plaintext_in_ciphertext_out = &mut ciphertext_in_plaintext_out[PACKET_LENGTH_LEN..];
150        self.key
151            .k_2
152            .encrypt_in_place(nonce.as_ref(), plaintext_in_ciphertext_out, 1);
153
154        Ok(plaintext_in_ciphertext_out)
155    }
156}
157
158struct Key {
159    k_1: ChaCha20Key,
160    k_2: ChaCha20Key,
161}
162
163impl Key {
164    fn new(key_material: &[u8; KEY_LEN]) -> Key {
165        // The first half becomes K_2 and the second half becomes K_1.
166        let (k_2, k_1) = key_material.split_at(chacha::KEY_LEN);
167        let k_1: [u8; chacha::KEY_LEN] = k_1.try_into().unwrap();
168        let k_2: [u8; chacha::KEY_LEN] = k_2.try_into().unwrap();
169        Key {
170            k_1: ChaCha20Key::from(k_1),
171            k_2: ChaCha20Key::from(k_2),
172        }
173    }
174}
175
176#[inline]
177fn make_nonce(sequence_number: u32) -> Nonce {
178    Nonce::from(BigEndian::from(sequence_number))
179}
180
181/// The length of key.
182pub const KEY_LEN: usize = chacha::KEY_LEN * 2;
183
184/// The length in bytes of the `packet_length` field in a SSH packet.
185pub const PACKET_LENGTH_LEN: usize = 4; // 32 bits
186
187/// The length in bytes of an authentication tag.
188pub const TAG_LEN: usize = BLOCK_LEN;
189
190#[inline]
191fn verify(key: poly1305::Key, msg: &[u8], tag: &[u8; TAG_LEN]) -> Result<(), error::Unspecified> {
192    let Tag(calculated_tag, _) = poly1305::sign(key, msg);
193    constant_time::verify_slices_are_equal(calculated_tag.as_ref(), tag)
194}
195
196#[inline]
197#[allow(clippy::needless_pass_by_value)]
198pub(super) fn derive_poly1305_key(chacha_key: &ChaCha20Key, nonce: Nonce) -> poly1305::Key {
199    let mut key_bytes = [0u8; 2 * BLOCK_LEN];
200    chacha_key.encrypt_in_place(nonce.as_ref(), &mut key_bytes, 0);
201    poly1305::Key::new(key_bytes)
202}
203
204#[cfg(test)]
205mod tests {
206    use crate::aead::chacha20_poly1305_openssh::{
207        derive_poly1305_key, OpeningKey, SealingKey, KEY_LEN, TAG_LEN,
208    };
209    use crate::aead::Nonce;
210    use crate::cipher::chacha::ChaCha20Key;
211    use crate::endian::{BigEndian, FromArray, LittleEndian};
212    use crate::test;
213
214    #[test]
215    fn derive_poly1305_test() {
216        let chacha_key =
217            test::from_hex("98bef1469be7269837a45bfbc92a5a6ac762507cf96443bf33b96b1bd4c6f8f6")
218                .unwrap();
219        let expected_poly1305_key =
220            test::from_hex("759de17d6d6258a436e36ecf75e3f00e4d9133ec05c4c855a9ec1a4e4e873b9d")
221                .unwrap();
222        let chacha_key = chacha_key.as_slice();
223        let chacha_key_bytes: [u8; 32] = <[u8; 32]>::try_from(chacha_key).unwrap();
224        let chacha_key = ChaCha20Key::from(chacha_key_bytes);
225        {
226            let iv = Nonce::from(&[45u32, 897, 4567]);
227            let poly1305_key = derive_poly1305_key(&chacha_key, iv);
228            assert_eq!(&expected_poly1305_key, &poly1305_key.key_and_nonce);
229        }
230
231        {
232            let iv = Nonce::from(&LittleEndian::<u32>::from_array(&[45u32, 897, 4567]));
233            let poly1305_key = derive_poly1305_key(&chacha_key, iv);
234            assert_eq!(&expected_poly1305_key, &poly1305_key.key_and_nonce);
235        }
236
237        {
238            let iv = Nonce::from(&BigEndian::<u32>::from_array(&[45u32, 897, 4567]));
239            let poly1305_key = derive_poly1305_key(&chacha_key, iv);
240            assert_ne!(&expected_poly1305_key, &poly1305_key.key_and_nonce);
241        }
242    }
243
244    #[test]
245    #[allow(clippy::cast_possible_truncation)]
246    fn test_decrypt_packet_length() {
247        let key_bytes: [u8; KEY_LEN] = test::from_dirty_hex("98bef1469be7269837a45bfbc92a5a6ac762\
248        507cf96443bf33b96b1bd4c6f8f6759de17d6d6258a436e36ecf75e3f00e4d9133ec05c4c855a9ec1a4e4e873b9d")
249            .try_into().unwrap();
250
251        let sealing_key = SealingKey::new(&key_bytes);
252        let opening_key = OpeningKey::new(&key_bytes);
253
254        let plaintext = b"Hello World!";
255        let packet_length = plaintext.len() as u32;
256        let packet_length = packet_length.to_be_bytes();
257        let mut in_out = Vec::new();
258
259        in_out.extend_from_slice(&packet_length);
260        in_out.extend_from_slice(plaintext);
261
262        let mut tag = [0u8; TAG_LEN];
263        sealing_key.seal_in_place(0, &mut in_out, &mut tag);
264
265        let encrypted_length: [u8; 4] = in_out[0..4].to_owned().try_into().unwrap();
266        let decrypted_length = opening_key.decrypt_packet_length(0, encrypted_length);
267        let decrypted_length = u32::from_be_bytes(decrypted_length);
268        assert_eq!(plaintext.len() as u32, decrypted_length);
269    }
270
271    #[test]
272    fn test_types() {
273        test::compile_time_assert_send::<OpeningKey>();
274        test::compile_time_assert_sync::<OpeningKey>();
275
276        test::compile_time_assert_send::<SealingKey>();
277        test::compile_time_assert_sync::<SealingKey>();
278    }
279}