ring/aead/
chacha20_poly1305_openssh.rs

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 [chacha20-poly1305@openssh.com] 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 [chacha20-poly1305@openssh.com] 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//! [chacha20-poly1305@openssh.com]:
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
32use super::{
33    chacha::{self, *},
34    chacha20_poly1305::derive_poly1305_key,
35    cpu, poly1305, Nonce, Tag,
36};
37use crate::{constant_time, endian::*, error};
38use core::convert::TryInto;
39
40/// A key for sealing packets.
41pub struct SealingKey {
42    key: Key,
43}
44
45impl SealingKey {
46    /// Constructs a new `SealingKey`.
47    pub fn new(key_material: &[u8; KEY_LEN]) -> SealingKey {
48        SealingKey {
49            key: Key::new(key_material, cpu::features()),
50        }
51    }
52
53    /// Seals (encrypts and signs) a packet.
54    ///
55    /// On input, `plaintext_in_ciphertext_out` must contain the unencrypted
56    /// `packet_length||plaintext` where `plaintext` is the
57    /// `padding_length||payload||random padding`. It will be overwritten by
58    /// `encrypted_packet_length||ciphertext`, where `encrypted_packet_length`
59    /// is encrypted with `K_1` and `ciphertext` is encrypted by `K_2`.
60    pub fn seal_in_place(
61        &self,
62        sequence_number: u32,
63        plaintext_in_ciphertext_out: &mut [u8],
64        tag_out: &mut [u8; TAG_LEN],
65    ) {
66        let mut counter = make_counter(sequence_number);
67        let poly_key =
68            derive_poly1305_key(&self.key.k_2, counter.increment(), self.key.cpu_features);
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.
88pub struct OpeningKey {
89    key: Key,
90}
91
92impl OpeningKey {
93    /// Constructs a new `OpeningKey`.
94    pub fn new(key_material: &[u8; KEY_LEN]) -> OpeningKey {
95        OpeningKey {
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.
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.
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 =
136            derive_poly1305_key(&self.key.k_2, counter.increment(), self.key.cpu_features);
137        verify(poly_key, ciphertext_in_plaintext_out, tag)?;
138
139        let plaintext_in_ciphertext_out = &mut ciphertext_in_plaintext_out[PACKET_LENGTH_LEN..];
140        self.key
141            .k_2
142            .encrypt_in_place(counter, plaintext_in_ciphertext_out);
143
144        Ok(plaintext_in_ciphertext_out)
145    }
146}
147
148struct Key {
149    k_1: chacha::Key,
150    k_2: chacha::Key,
151    cpu_features: cpu::Features,
152}
153
154impl Key {
155    fn new(key_material: &[u8; KEY_LEN], cpu_features: cpu::Features) -> Key {
156        // The first half becomes K_2 and the second half becomes K_1.
157        let (k_2, k_1) = key_material.split_at(chacha::KEY_LEN);
158        let k_1: [u8; chacha::KEY_LEN] = k_1.try_into().unwrap();
159        let k_2: [u8; chacha::KEY_LEN] = k_2.try_into().unwrap();
160        Key {
161            k_1: chacha::Key::from(k_1),
162            k_2: chacha::Key::from(k_2),
163            cpu_features,
164        }
165    }
166}
167
168fn make_counter(sequence_number: u32) -> Counter {
169    let nonce = [
170        BigEndian::ZERO,
171        BigEndian::ZERO,
172        BigEndian::from(sequence_number),
173    ];
174    Counter::zero(Nonce::assume_unique_for_key(*(nonce.as_byte_array())))
175}
176
177/// The length of key.
178pub const KEY_LEN: usize = chacha::KEY_LEN * 2;
179
180/// The length in bytes of the `packet_length` field in a SSH packet.
181pub const PACKET_LENGTH_LEN: usize = 4; // 32 bits
182
183/// The length in bytes of an authentication tag.
184pub const TAG_LEN: usize = super::BLOCK_LEN;
185
186fn verify(key: poly1305::Key, msg: &[u8], tag: &[u8; TAG_LEN]) -> Result<(), error::Unspecified> {
187    let Tag(calculated_tag) = poly1305::sign(key, msg);
188    constant_time::verify_slices_are_equal(calculated_tag.as_ref(), tag)
189}