1 // Copyright 2016 Brian Smith.
2 //
3 // Permission to use, copy, modify, and/or distribute this software for any
4 // purpose with or without fee is hereby granted, provided that the above
5 // copyright notice and this permission notice appear in all copies.
6 //
7 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
10 // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 // OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14 
15 //! The [[email protected]] AEAD-ish construct.
16 //!
17 //! This should only be used by SSH implementations. It has a similar, but
18 //! different API from `ring::aead` because the construct cannot use the same
19 //! API as `ring::aead` due to the way the construct handles the encrypted
20 //! packet length.
21 //!
22 //! The concatenation of a and b is denoted `a||b`. `K_1` and `K_2` are defined
23 //! in the [[email protected]] specification. `packet_length`,
24 //! `padding_length`, `payload`, and `random padding` are defined in
25 //! [RFC 4253]. The term `plaintext` is used as a shorthand for
26 //! `padding_length||payload||random padding`.
27 //!
28 //! [[email protected]]:
29 //!    http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.chacha20poly1305?annotate=HEAD
30 //! [RFC 4253]: https://tools.ietf.org/html/rfc4253
31 
32 use super::{
33     chacha::{self, *},
34     chacha20_poly1305::derive_poly1305_key,
35     cpu, poly1305,
36     polyfill::ChunksFixed,
37     Nonce, Tag,
38 };
39 use crate::{constant_time, endian::*, error};
40 
41 /// A key for sealing packets.
42 pub struct SealingKey {
43     key: Key,
44 }
45 
46 impl SealingKey {
47     /// Constructs a new `SealingKey`.
new(key_material: &[u8; KEY_LEN]) -> Self48     pub fn new(key_material: &[u8; KEY_LEN]) -> Self {
49         Self {
50             key: Key::new(key_material, cpu::features()),
51         }
52     }
53 
54     /// Seals (encrypts and signs) a packet.
55     ///
56     /// On input, `plaintext_in_ciphertext_out` must contain the unencrypted
57     /// `packet_length||plaintext` where `plaintext` is the
58     /// `padding_length||payload||random padding`. It will be overwritten by
59     /// `encrypted_packet_length||ciphertext`, where `encrypted_packet_length`
60     /// is encrypted with `K_1` and `ciphertext` is encrypted by `K_2`.
seal_in_place( &self, sequence_number: u32, plaintext_in_ciphertext_out: &mut [u8], tag_out: &mut [u8; TAG_LEN], )61     pub fn seal_in_place(
62         &self,
63         sequence_number: u32,
64         plaintext_in_ciphertext_out: &mut [u8],
65         tag_out: &mut [u8; TAG_LEN],
66     ) {
67         let mut counter = make_counter(sequence_number);
68         let poly_key = derive_poly1305_key(&self.key.k_2, counter.increment());
69 
70         {
71             let (len_in_out, data_and_padding_in_out) =
72                 plaintext_in_ciphertext_out.split_at_mut(PACKET_LENGTH_LEN);
73 
74             self.key
75                 .k_1
76                 .encrypt_in_place(make_counter(sequence_number), len_in_out);
77             self.key
78                 .k_2
79                 .encrypt_in_place(counter, data_and_padding_in_out);
80         }
81 
82         let Tag(tag) = poly1305::sign(poly_key, plaintext_in_ciphertext_out);
83         tag_out.copy_from_slice(tag.as_ref());
84     }
85 }
86 
87 /// A key for opening packets.
88 pub struct OpeningKey {
89     key: Key,
90 }
91 
92 impl OpeningKey {
93     /// Constructs a new `OpeningKey`.
new(key_material: &[u8; KEY_LEN]) -> Self94     pub fn new(key_material: &[u8; KEY_LEN]) -> Self {
95         Self {
96             key: Key::new(key_material, cpu::features()),
97         }
98     }
99 
100     /// Returns the decrypted, but unauthenticated, packet length.
101     ///
102     /// Importantly, the result won't be authenticated until `open_in_place` is
103     /// called.
decrypt_packet_length( &self, sequence_number: u32, encrypted_packet_length: [u8; PACKET_LENGTH_LEN], ) -> [u8; PACKET_LENGTH_LEN]104     pub fn decrypt_packet_length(
105         &self,
106         sequence_number: u32,
107         encrypted_packet_length: [u8; PACKET_LENGTH_LEN],
108     ) -> [u8; PACKET_LENGTH_LEN] {
109         let mut packet_length = encrypted_packet_length;
110         let counter = make_counter(sequence_number);
111         self.key.k_1.encrypt_in_place(counter, &mut packet_length);
112         packet_length
113     }
114 
115     /// Opens (authenticates and decrypts) a packet.
116     ///
117     /// `ciphertext_in_plaintext_out` must be of the form
118     /// `encrypted_packet_length||ciphertext` where `ciphertext` is the
119     /// encrypted `plaintext`. When the function succeeds the ciphertext is
120     /// replaced by the plaintext and the result is `Ok(plaintext)`, where
121     /// `plaintext` is `&ciphertext_in_plaintext_out[PACKET_LENGTH_LEN..]`;
122     /// otherwise the contents of `ciphertext_in_plaintext_out` are unspecified
123     /// and must not be used.
open_in_place<'a>( &self, sequence_number: u32, ciphertext_in_plaintext_out: &'a mut [u8], tag: &[u8; TAG_LEN], ) -> Result<&'a [u8], error::Unspecified>124     pub fn open_in_place<'a>(
125         &self,
126         sequence_number: u32,
127         ciphertext_in_plaintext_out: &'a mut [u8],
128         tag: &[u8; TAG_LEN],
129     ) -> Result<&'a [u8], error::Unspecified> {
130         let mut counter = make_counter(sequence_number);
131 
132         // We must verify the tag before decrypting so that
133         // `ciphertext_in_plaintext_out` is unmodified if verification fails.
134         // This is beyond what we guarantee.
135         let poly_key = derive_poly1305_key(&self.key.k_2, counter.increment());
136         verify(poly_key, ciphertext_in_plaintext_out, tag)?;
137 
138         let plaintext_in_ciphertext_out = &mut ciphertext_in_plaintext_out[PACKET_LENGTH_LEN..];
139         self.key
140             .k_2
141             .encrypt_in_place(counter, plaintext_in_ciphertext_out);
142 
143         Ok(plaintext_in_ciphertext_out)
144     }
145 }
146 
147 struct Key {
148     k_1: chacha::Key,
149     k_2: chacha::Key,
150 }
151 
152 impl Key {
new(key_material: &[u8; KEY_LEN], cpu_features: cpu::Features) -> Self153     fn new(key_material: &[u8; KEY_LEN], cpu_features: cpu::Features) -> Self {
154         // The first half becomes K_2 and the second half becomes K_1.
155         let &[k_2, k_1]: &[[u8; chacha::KEY_LEN]; 2] = key_material.chunks_fixed();
156         Self {
157             k_1: chacha::Key::new(k_1, cpu_features),
158             k_2: chacha::Key::new(k_2, cpu_features),
159         }
160     }
161 }
162 
make_counter(sequence_number: u32) -> Counter163 fn make_counter(sequence_number: u32) -> Counter {
164     let nonce = [
165         BigEndian::ZERO,
166         BigEndian::ZERO,
167         BigEndian::from(sequence_number),
168     ];
169     Counter::zero(Nonce::assume_unique_for_key(*(nonce.as_byte_array())))
170 }
171 
172 /// The length of key.
173 pub const KEY_LEN: usize = chacha::KEY_LEN * 2;
174 
175 /// The length in bytes of the `packet_length` field in a SSH packet.
176 pub const PACKET_LENGTH_LEN: usize = 4; // 32 bits
177 
178 /// The length in bytes of an authentication tag.
179 pub const TAG_LEN: usize = super::TAG_LEN;
180 
verify(key: poly1305::Key, msg: &[u8], tag: &[u8; TAG_LEN]) -> Result<(), error::Unspecified>181 fn verify(key: poly1305::Key, msg: &[u8], tag: &[u8; TAG_LEN]) -> Result<(), error::Unspecified> {
182     let Tag(calculated_tag) = poly1305::sign(key, msg);
183     constant_time::verify_slices_are_equal(calculated_tag.as_ref(), tag)
184 }
185