russh 0.61.2

A client and server SSH library.
Documentation
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
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

use std::convert::TryInto;
use std::marker::PhantomData;

use aes::cipher::{
    InOutBuf, Iv, IvSizeUser, Key, KeyIvInit, KeySizeUser, StreamCipher, StreamCipherError,
    StreamCipherSeek,
};
#[allow(deprecated)]
use rand_core::Rng;

use super::super::Error;
use super::PACKET_LENGTH_LEN;
use crate::keys::key::safe_rng;
use crate::mac::{Mac, MacAlgorithm};

fn new_cipher_from_slices<C: KeyIvInit>(k: &[u8], n: &[u8]) -> C {
    #[allow(clippy::expect_used)]
    C::new(
        <&Key<C>>::try_from(k).expect("key length matches"),
        <&Iv<C>>::try_from(n).expect("iv length matches"),
    )
}

/// Cloneable wrapper for `Ctr128BE<>`
pub struct CtrWrapper<C>
where
    C: KeyIvInit,
{
    key: Key<C>,
    initial_iv: Iv<C>,
    pos: u64,
}

impl<C: KeyIvInit> Clone for CtrWrapper<C> {
    fn clone(&self) -> Self {
        Self {
            key: self.key.clone(),
            initial_iv: self.initial_iv.clone(),
            pos: self.pos,
        }
    }
}

impl<C: KeyIvInit> KeySizeUser for CtrWrapper<C> {
    type KeySize = <C as KeySizeUser>::KeySize;
}

impl<C: KeyIvInit> IvSizeUser for CtrWrapper<C> {
    type IvSize = <C as IvSizeUser>::IvSize;
}

impl<C: KeyIvInit> KeyIvInit for CtrWrapper<C> {
    fn new(key: &Key<Self>, iv: &Iv<Self>) -> Self {
        Self {
            key: key.clone(),
            initial_iv: iv.clone(),
            pos: 0,
        }
    }
}

impl<C: KeyIvInit + StreamCipher + StreamCipherSeek> StreamCipher for CtrWrapper<C> {
    fn check_remaining(&self, _data_len: usize) -> Result<(), StreamCipherError> {
        Ok(())
    }

    fn unchecked_apply_keystream_inout(&mut self, buf: InOutBuf<'_, '_, u8>) {
        let mut cipher = C::new(&self.key, &self.initial_iv);
        cipher.seek(self.pos);
        cipher.unchecked_apply_keystream_inout(buf);
        self.pos = cipher.current_pos();
    }

    fn unchecked_write_keystream(&mut self, buf: &mut [u8]) {
        let mut cipher = C::new(&self.key, &self.initial_iv);
        cipher.seek(self.pos);
        cipher.unchecked_write_keystream(buf);
        self.pos = cipher.current_pos();
    }
}

pub struct SshBlockCipher<C: BlockStreamCipher + PacketLengthProbe + KeySizeUser + IvSizeUser>(
    pub PhantomData<C>,
);

impl<
    C: BlockStreamCipher + PacketLengthProbe + KeySizeUser + IvSizeUser + KeyIvInit + Send + 'static,
> super::Cipher for SshBlockCipher<C>
{
    fn key_len(&self) -> usize {
        C::key_size()
    }

    fn nonce_len(&self) -> usize {
        C::iv_size()
    }

    fn needs_mac(&self) -> bool {
        true
    }

    fn make_opening_key(
        &self,
        k: &[u8],
        n: &[u8],
        m: &[u8],
        mac: &dyn MacAlgorithm,
    ) -> Box<dyn super::OpeningKey + Send> {
        Box::new(OpeningKey {
            cipher: new_cipher_from_slices::<C>(k, n),
            mac: mac.make_mac(m),
        })
    }

    fn make_sealing_key(
        &self,
        k: &[u8],
        n: &[u8],
        m: &[u8],
        mac: &dyn MacAlgorithm,
    ) -> Box<dyn super::SealingKey + Send> {
        Box::new(SealingKey {
            cipher: new_cipher_from_slices::<C>(k, n),
            mac: mac.make_mac(m),
        })
    }
}

pub struct OpeningKey<C: BlockStreamCipher + PacketLengthProbe> {
    pub(crate) cipher: C,
    pub(crate) mac: Box<dyn Mac + Send>,
}

pub struct SealingKey<C: BlockStreamCipher> {
    pub(crate) cipher: C,
    pub(crate) mac: Box<dyn Mac + Send>,
}

impl<C: BlockStreamCipher + PacketLengthProbe + KeySizeUser + IvSizeUser> super::OpeningKey
    for OpeningKey<C>
{
    fn packet_length_to_read_for_block_length(&self) -> usize {
        16
    }

    fn decrypt_packet_length(
        &self,
        _sequence_number: u32,
        encrypted_packet_length: &[u8],
    ) -> [u8; 4] {
        let mut first_block = [0u8; 16];
        // Fine because of self.packet_length_to_read_for_block_length()
        #[allow(clippy::indexing_slicing)]
        first_block.copy_from_slice(&encrypted_packet_length[..16]);

        if self.mac.is_etm() {
            // Fine because of self.packet_length_to_read_for_block_length()
            #[allow(clippy::unwrap_used, clippy::indexing_slicing)]
            encrypted_packet_length[..4].try_into().unwrap()
        } else {
            self.cipher.decrypt_packet_length_block(&mut first_block);

            // Fine because of self.packet_length_to_read_for_block_length()
            #[allow(clippy::unwrap_used, clippy::indexing_slicing)]
            first_block[..4].try_into().unwrap()
        }
    }

    fn tag_len(&self) -> usize {
        self.mac.mac_len()
    }

    fn open<'a>(
        &mut self,
        sequence_number: u32,
        ciphertext_and_tag: &'a mut [u8],
    ) -> Result<&'a [u8], Error> {
        let ciphertext_len = ciphertext_and_tag.len() - self.tag_len();
        let (ciphertext_in_plaintext_out, tag) = ciphertext_and_tag.split_at_mut(ciphertext_len);
        if self.mac.is_etm() {
            if !self
                .mac
                .verify(sequence_number, ciphertext_in_plaintext_out, tag)
            {
                return Err(Error::PacketAuth);
            }
            #[allow(clippy::indexing_slicing)]
            self.cipher
                .decrypt_data(&mut ciphertext_in_plaintext_out[PACKET_LENGTH_LEN..]);
        } else {
            self.cipher.decrypt_data(ciphertext_in_plaintext_out);

            if !self
                .mac
                .verify(sequence_number, ciphertext_in_plaintext_out, tag)
            {
                return Err(Error::PacketAuth);
            }
        }

        #[allow(clippy::indexing_slicing)]
        Ok(&ciphertext_in_plaintext_out[PACKET_LENGTH_LEN..])
    }
}

impl<C: BlockStreamCipher + KeySizeUser + IvSizeUser> super::SealingKey for SealingKey<C> {
    fn padding_length(&self, payload: &[u8]) -> usize {
        let block_size = 16;

        let pll = if self.mac.is_etm() {
            0
        } else {
            PACKET_LENGTH_LEN
        };

        let extra_len = PACKET_LENGTH_LEN + super::PADDING_LENGTH_LEN + self.mac.mac_len();

        let padding_len = if payload.len() + extra_len <= super::MINIMUM_PACKET_LEN {
            super::MINIMUM_PACKET_LEN - payload.len() - super::PADDING_LENGTH_LEN - pll
        } else {
            block_size - ((pll + super::PADDING_LENGTH_LEN + payload.len()) % block_size)
        };
        if padding_len < PACKET_LENGTH_LEN {
            padding_len + block_size
        } else {
            padding_len
        }
    }

    fn fill_padding(&self, padding_out: &mut [u8]) {
        safe_rng().fill_bytes(padding_out);
    }

    fn tag_len(&self) -> usize {
        self.mac.mac_len()
    }

    fn seal(
        &mut self,
        sequence_number: u32,
        plaintext_in_ciphertext_out: &mut [u8],
        tag_out: &mut [u8],
    ) {
        if self.mac.is_etm() {
            #[allow(clippy::indexing_slicing)]
            self.cipher
                .encrypt_data(&mut plaintext_in_ciphertext_out[PACKET_LENGTH_LEN..]);
            self.mac
                .compute(sequence_number, plaintext_in_ciphertext_out, tag_out);
        } else {
            self.mac
                .compute(sequence_number, plaintext_in_ciphertext_out, tag_out);
            self.cipher.encrypt_data(plaintext_in_ciphertext_out);
        }
    }
}

pub trait BlockStreamCipher {
    fn encrypt_data(&mut self, data: &mut [u8]);
    fn decrypt_data(&mut self, data: &mut [u8]);
}

pub(crate) trait PacketLengthProbe {
    fn decrypt_packet_length_block(&self, first_block: &mut [u8; 16]);
}

impl<T: StreamCipher> BlockStreamCipher for T {
    fn encrypt_data(&mut self, data: &mut [u8]) {
        self.apply_keystream(data);
    }

    fn decrypt_data(&mut self, data: &mut [u8]) {
        self.apply_keystream(data);
    }
}

impl<T: StreamCipher + Clone> PacketLengthProbe for T {
    fn decrypt_packet_length_block(&self, first_block: &mut [u8; 16]) {
        let mut cipher = self.clone();
        cipher.apply_keystream(first_block);
    }
}

#[cfg(test)]
mod tests {
    use aes::Aes128;
    use aes::cipher::KeyIvInit;
    use aes::cipher::StreamCipher;
    use aes::cipher::{IvSizeUser, KeySizeUser};
    use ctr::Ctr128BE;
    use digest::typenum::U16;
    use tokio::io::AsyncWriteExt;

    use super::{BlockStreamCipher, CtrWrapper, OpeningKey, PacketLengthProbe};
    use crate::mac::MacAlgorithm;
    use crate::sshbuffer::SSHBuffer;

    #[test]
    fn stream_cipher_probe_does_not_advance_cipher_state() {
        let plaintext = *b"0123456789ABCDEF";
        let key = fixture_bytes::<16>(7);
        let iv = fixture_bytes::<16>(3);

        let mut encryptor = CtrWrapper::<Ctr128BE<Aes128>>::new(&key.into(), &iv.into());
        let mut ciphertext = plaintext;
        encryptor.apply_keystream(&mut ciphertext);

        let cipher = CtrWrapper::<Ctr128BE<Aes128>>::new(&key.into(), &iv.into());
        let mut probed_block = ciphertext;
        cipher.decrypt_packet_length_block(&mut probed_block);
        assert_eq!(probed_block, plaintext);

        let mut decrypted = ciphertext;
        let mut cipher_after_probe = cipher;
        cipher_after_probe.decrypt_data(&mut decrypted);
        assert_eq!(decrypted, plaintext);
    }

    #[test]
    fn decrypt_packet_length_uses_independent_cipher_state() -> std::io::Result<()> {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()?;
        let opening = OpeningKey {
            cipher: OwnedStateCipher::new(),
            mac: crate::mac::_NONE.make_mac(&[]),
        };
        let mut opening = opening;
        let mut buffer = SSHBuffer::new();
        let bytes_read = runtime
            .block_on(async {
                let (mut writer, mut reader) = tokio::io::duplex(64);
                writer.write_all(&[0; 17]).await?;
                drop(writer);
                crate::cipher::read(&mut reader, &mut buffer, &mut opening).await
            })
            .map_err(std::io::Error::other)?;

        assert_eq!(bytes_read, 16);
        Ok(())
    }

    struct OwnedStateCipher {
        packet_length: Box<[u8; 4]>,
    }

    impl OwnedStateCipher {
        fn new() -> Self {
            Self {
                packet_length: Box::new([0, 0, 0, 13]),
            }
        }
    }

    impl Clone for OwnedStateCipher {
        fn clone(&self) -> Self {
            Self {
                packet_length: Box::new([0, 0, 0, 12]),
            }
        }
    }

    impl KeySizeUser for OwnedStateCipher {
        type KeySize = U16;
    }

    impl IvSizeUser for OwnedStateCipher {
        type IvSize = U16;
    }

    impl BlockStreamCipher for OwnedStateCipher {
        fn encrypt_data(&mut self, _data: &mut [u8]) {}

        fn decrypt_data(&mut self, data: &mut [u8]) {
            if let Some(prefix) = data.get_mut(..4) {
                prefix.copy_from_slice(&self.packet_length[..]);
            }
        }
    }

    impl PacketLengthProbe for OwnedStateCipher {
        fn decrypt_packet_length_block(&self, first_block: &mut [u8; 16]) {
            if let Some(prefix) = first_block.get_mut(..4) {
                prefix.copy_from_slice(&[0, 0, 0, 12]);
            }
        }
    }

    fn fixture_bytes<const N: usize>(seed: u8) -> [u8; N] {
        let mut bytes = [0; N];
        for (i, byte) in bytes.iter_mut().enumerate() {
            *byte = seed.wrapping_add(i as u8);
        }
        bytes
    }
}