bssh-russh 0.60.1

Temporary fork of russh with high-frequency PTY output fix (Handle::data from spawned tasks)
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
// Copyright 2016 Pierre-Étienne Meunier
//
// 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::borrow::Cow;

use log::debug;
use rand_core::Rng;
use ssh_encoding::{Decode, Encode};
use ssh_key::{Algorithm, EcdsaCurve, HashAlg, PrivateKey};

use crate::cipher::CIPHERS;
use crate::helpers::NameList;
use crate::kex::{
    EXTENSION_OPENSSH_STRICT_KEX_AS_CLIENT, EXTENSION_OPENSSH_STRICT_KEX_AS_SERVER, KexCause,
};
use crate::keys::key::safe_rng;
#[cfg(not(target_arch = "wasm32"))]
use crate::server::Config;
use crate::sshbuffer::PacketWriter;
use crate::{AlgorithmKind, Error, cipher, compression, kex, mac, msg};

#[cfg(target_arch = "wasm32")]
/// WASM-only stub
pub struct Config {
    keys: Vec<PrivateKey>,
}

#[derive(Debug, Clone)]
pub struct Names {
    pub kex: kex::Name,
    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
    pub key: Algorithm,
    pub cipher: cipher::Name,
    pub client_mac: mac::Name,
    pub server_mac: mac::Name,
    pub server_compression: compression::Compression,
    pub client_compression: compression::Compression,
    pub ignore_guessed: bool,
    // Prevent accidentally contructing [Names] without a [KeyCause]
    // as strict kext algo is not sent during a rekey and hence the state
    // of [strict_kex] cannot be known without a [KexCause].
    strict_kex: bool,
}

impl Names {
    pub fn strict_kex(&self) -> bool {
        self.strict_kex
    }
}

/// Lists of preferred algorithms. This is normally hard-coded into implementations.
#[derive(Debug, Clone)]
pub struct Preferred {
    /// Preferred key exchange algorithms.
    pub kex: Cow<'static, [kex::Name]>,
    /// Preferred host & public key algorithms.
    pub key: Cow<'static, [Algorithm]>,
    /// Preferred symmetric ciphers.
    pub cipher: Cow<'static, [cipher::Name]>,
    /// Preferred MAC algorithms.
    pub mac: Cow<'static, [mac::Name]>,
    /// Preferred compression algorithms.
    pub compression: Cow<'static, [compression::Name]>,
}

pub(crate) fn is_key_compatible_with_algo(key: &PrivateKey, algo: &Algorithm) -> bool {
    match algo {
        // All RSA keys are compatible with all RSA based algos.
        Algorithm::Rsa { .. } => key.algorithm().is_rsa(),
        // Other keys have to match exactly
        a => key.algorithm() == *a,
    }
}

impl Preferred {
    pub(crate) fn possible_host_key_algos_for_keys(
        &self,
        available_host_keys: &[PrivateKey],
    ) -> Vec<Algorithm> {
        self.key
            .iter()
            .filter(|n| {
                available_host_keys
                    .iter()
                    .any(|k| is_key_compatible_with_algo(k, n))
            })
            .cloned()
            .collect::<Vec<_>>()
    }
}

const SAFE_KEX_ORDER: &[kex::Name] = &[
    kex::MLKEM768X25519_SHA256,
    kex::CURVE25519,
    kex::CURVE25519_PRE_RFC_8731,
    kex::DH_GEX_SHA256,
    kex::DH_G18_SHA512,
    kex::DH_G17_SHA512,
    kex::DH_G16_SHA512,
    kex::DH_G15_SHA512,
    kex::DH_G14_SHA256,
    kex::EXTENSION_SUPPORT_AS_CLIENT,
    kex::EXTENSION_SUPPORT_AS_SERVER,
    kex::EXTENSION_OPENSSH_STRICT_KEX_AS_CLIENT,
    kex::EXTENSION_OPENSSH_STRICT_KEX_AS_SERVER,
];

const KEX_EXTENSION_NAMES: &[kex::Name] = &[
    kex::EXTENSION_SUPPORT_AS_CLIENT,
    kex::EXTENSION_SUPPORT_AS_SERVER,
    kex::EXTENSION_OPENSSH_STRICT_KEX_AS_CLIENT,
    kex::EXTENSION_OPENSSH_STRICT_KEX_AS_SERVER,
];

const CIPHER_ORDER: &[cipher::Name] = &[
    cipher::CHACHA20_POLY1305,
    cipher::AES_256_GCM,
    cipher::AES_256_CTR,
    cipher::AES_192_CTR,
    cipher::AES_128_CTR,
];

const HMAC_ORDER: &[mac::Name] = &[
    mac::HMAC_SHA512_ETM,
    mac::HMAC_SHA256_ETM,
    mac::HMAC_SHA512,
    mac::HMAC_SHA256,
    mac::HMAC_SHA1_ETM,
    mac::HMAC_SHA1,
];

const COMPRESSION_ORDER: &[compression::Name] = &[
    compression::NONE,
    #[cfg(feature = "flate2")]
    compression::ZLIB,
    #[cfg(feature = "flate2")]
    compression::ZLIB_LEGACY,
];

impl Preferred {
    pub const DEFAULT: Preferred = Preferred {
        kex: Cow::Borrowed(SAFE_KEX_ORDER),
        key: Cow::Borrowed(&[
            Algorithm::Ed25519,
            Algorithm::Ecdsa {
                curve: EcdsaCurve::NistP256,
            },
            Algorithm::Ecdsa {
                curve: EcdsaCurve::NistP384,
            },
            Algorithm::Ecdsa {
                curve: EcdsaCurve::NistP521,
            },
            Algorithm::Rsa {
                hash: Some(HashAlg::Sha512),
            },
            Algorithm::Rsa {
                hash: Some(HashAlg::Sha256),
            },
            Algorithm::Rsa { hash: None },
        ]),
        cipher: Cow::Borrowed(CIPHER_ORDER),
        mac: Cow::Borrowed(HMAC_ORDER),
        compression: Cow::Borrowed(COMPRESSION_ORDER),
    };

    pub const COMPRESSED: Preferred = Preferred {
        kex: Cow::Borrowed(SAFE_KEX_ORDER),
        key: Preferred::DEFAULT.key,
        cipher: Cow::Borrowed(CIPHER_ORDER),
        mac: Cow::Borrowed(HMAC_ORDER),
        compression: Cow::Borrowed(COMPRESSION_ORDER),
    };
}

impl Default for Preferred {
    fn default() -> Preferred {
        Preferred::DEFAULT
    }
}

pub(crate) fn parse_kex_algo_list(list: &str) -> Vec<&str> {
    list.split(',').collect()
}

pub(crate) trait Select {
    fn is_server() -> bool;

    fn select<S: AsRef<str> + Clone>(
        a: &[S],
        b: &[&str],
        kind: AlgorithmKind,
    ) -> Result<(bool, S), Error>;

    /// `available_host_keys`, if present, is used to limit the host key algorithms to the ones we have keys for.
    fn read_kex(
        buffer: &[u8],
        pref: &Preferred,
        available_host_keys: Option<&[PrivateKey]>,
        cause: &KexCause,
    ) -> Result<Names, Error> {
        let &Some(mut r) = &buffer.get(17..) else {
            return Err(Error::Inconsistent);
        };

        // Key exchange

        let kex_string = String::decode(&mut r)?;
        // Filter out extension kex names from both lists before selecting
        let _local_kexes_no_ext = pref
            .kex
            .iter()
            .filter(|k| !KEX_EXTENSION_NAMES.contains(k))
            .cloned()
            .collect::<Vec<_>>();
        let _remote_kexes_no_ext = parse_kex_algo_list(&kex_string)
            .into_iter()
            .filter(|k| {
                kex::Name::try_from(*k)
                    .ok()
                    .map(|k| !KEX_EXTENSION_NAMES.contains(&k))
                    .unwrap_or(false)
            })
            .collect::<Vec<_>>();
        let (kex_both_first, kex_algorithm) = Self::select(
            &_local_kexes_no_ext,
            &_remote_kexes_no_ext,
            AlgorithmKind::Kex,
        )?;

        // Strict kex detection

        let strict_kex_requested = pref.kex.contains(if Self::is_server() {
            &EXTENSION_OPENSSH_STRICT_KEX_AS_SERVER
        } else {
            &EXTENSION_OPENSSH_STRICT_KEX_AS_CLIENT
        });
        let strict_kex_provided = Self::select(
            &[if Self::is_server() {
                EXTENSION_OPENSSH_STRICT_KEX_AS_CLIENT
            } else {
                EXTENSION_OPENSSH_STRICT_KEX_AS_SERVER
            }],
            &parse_kex_algo_list(&kex_string),
            AlgorithmKind::Kex,
        )
        .is_ok();

        if strict_kex_requested && strict_kex_provided {
            debug!("strict kex enabled")
        }

        // Host key

        let key_string = String::decode(&mut r)?;
        let possible_host_key_algos = match available_host_keys {
            Some(available_host_keys) => pref.possible_host_key_algos_for_keys(available_host_keys),
            None => pref.key.iter().map(ToOwned::to_owned).collect::<Vec<_>>(),
        };

        let (key_both_first, key_algorithm) = Self::select(
            &possible_host_key_algos[..],
            &parse_kex_algo_list(&key_string),
            AlgorithmKind::Key,
        )?;

        // Cipher

        let cipher_string = String::decode(&mut r)?;
        let (_cipher_both_first, cipher) = Self::select(
            &pref.cipher,
            &parse_kex_algo_list(&cipher_string),
            AlgorithmKind::Cipher,
        )?;
        String::decode(&mut r)?; // cipher server-to-client.

        // MAC

        let need_mac = CIPHERS.get(&cipher).map(|x| x.needs_mac()).unwrap_or(false);

        let client_mac = match Self::select(
            &pref.mac,
            &parse_kex_algo_list(&String::decode(&mut r)?),
            AlgorithmKind::Mac,
        ) {
            Ok((_, m)) => m,
            Err(e) => {
                if need_mac {
                    return Err(e);
                } else {
                    mac::NONE
                }
            }
        };
        let server_mac = match Self::select(
            &pref.mac,
            &parse_kex_algo_list(&String::decode(&mut r)?),
            AlgorithmKind::Mac,
        ) {
            Ok((_, m)) => m,
            Err(e) => {
                if need_mac {
                    return Err(e);
                } else {
                    mac::NONE
                }
            }
        };

        // Compression

        // client-to-server compression.
        let client_compression = compression::Compression::new(
            &Self::select(
                &pref.compression,
                &parse_kex_algo_list(&String::decode(&mut r)?),
                AlgorithmKind::Compression,
            )?
            .1,
        );

        // server-to-client compression.
        let server_compression = compression::Compression::new(
            &Self::select(
                &pref.compression,
                &parse_kex_algo_list(&String::decode(&mut r)?),
                AlgorithmKind::Compression,
            )?
            .1,
        );
        String::decode(&mut r)?; // languages client-to-server
        String::decode(&mut r)?; // languages server-to-client

        let follows = u8::decode(&mut r)? != 0;
        Ok(Names {
            kex: kex_algorithm,
            key: key_algorithm,
            cipher,
            client_mac,
            server_mac,
            client_compression,
            server_compression,
            // Ignore the next packet if (1) it follows and (2) it's not the correct guess.
            ignore_guessed: follows && !(kex_both_first && key_both_first),
            strict_kex: (strict_kex_requested && strict_kex_provided) || cause.is_strict_rekey(),
        })
    }
}

pub struct Server;
pub struct Client;

impl Select for Server {
    fn is_server() -> bool {
        true
    }

    fn select<S: AsRef<str> + Clone>(
        server_list: &[S],
        client_list: &[&str],
        kind: AlgorithmKind,
    ) -> Result<(bool, S), Error> {
        let mut both_first_choice = true;
        for c in client_list {
            for s in server_list {
                if c == &s.as_ref() {
                    return Ok((both_first_choice, s.clone()));
                }
                both_first_choice = false
            }
        }
        Err(Error::NoCommonAlgo {
            kind,
            ours: server_list.iter().map(|x| x.as_ref().to_owned()).collect(),
            theirs: client_list.iter().map(|x| (*x).to_owned()).collect(),
        })
    }
}

impl Select for Client {
    fn is_server() -> bool {
        false
    }

    fn select<S: AsRef<str> + Clone>(
        client_list: &[S],
        server_list: &[&str],
        kind: AlgorithmKind,
    ) -> Result<(bool, S), Error> {
        let mut both_first_choice = true;
        for c in client_list {
            for s in server_list {
                if s == &c.as_ref() {
                    return Ok((both_first_choice, c.clone()));
                }
                both_first_choice = false
            }
        }
        Err(Error::NoCommonAlgo {
            kind,
            ours: client_list.iter().map(|x| x.as_ref().to_owned()).collect(),
            theirs: server_list.iter().map(|x| (*x).to_owned()).collect(),
        })
    }
}

pub(crate) fn write_kex(
    prefs: &Preferred,
    writer: &mut PacketWriter,
    server_config: Option<&Config>,
) -> Result<Vec<u8>, Error> {
    writer.packet(|w| {
        // buf.clear();
        msg::KEXINIT.encode(w)?;

        let mut cookie = [0; 16];
        safe_rng().fill_bytes(&mut cookie);
        for b in cookie {
            b.encode(w)?;
        }

        NameList(
            prefs
                .kex
                .iter()
                .filter(|k| {
                    !(if server_config.is_some() {
                        [
                            crate::kex::EXTENSION_SUPPORT_AS_CLIENT,
                            crate::kex::EXTENSION_OPENSSH_STRICT_KEX_AS_CLIENT,
                        ]
                    } else {
                        [
                            crate::kex::EXTENSION_SUPPORT_AS_SERVER,
                            crate::kex::EXTENSION_OPENSSH_STRICT_KEX_AS_SERVER,
                        ]
                    })
                    .contains(*k)
                })
                .map(|x| x.as_ref().to_owned())
                .collect(),
        )
        .encode(w)?; // kex algo

        if let Some(server_config) = server_config {
            // Only advertise host key algorithms that we have keys for.
            NameList(
                prefs
                    .key
                    .iter()
                    .filter(|algo| {
                        server_config
                            .keys
                            .iter()
                            .any(|k| is_key_compatible_with_algo(k, algo))
                    })
                    .map(|x| x.to_string())
                    .collect(),
            )
            .encode(w)?;
        } else {
            NameList(prefs.key.iter().map(ToString::to_string).collect()).encode(w)?;
        }

        // cipher client to server
        NameList(
            prefs
                .cipher
                .iter()
                .map(|x| x.as_ref().to_string())
                .collect(),
        )
        .encode(w)?;

        // cipher server to client
        NameList(
            prefs
                .cipher
                .iter()
                .map(|x| x.as_ref().to_string())
                .collect(),
        )
        .encode(w)?;

        // mac client to server
        NameList(prefs.mac.iter().map(|x| x.as_ref().to_string()).collect()).encode(w)?;

        // mac server to client
        NameList(prefs.mac.iter().map(|x| x.as_ref().to_string()).collect()).encode(w)?;

        // compress client to server
        NameList(
            prefs
                .compression
                .iter()
                .map(|x| x.as_ref().to_string())
                .collect(),
        )
        .encode(w)?;

        // compress server to client
        NameList(
            prefs
                .compression
                .iter()
                .map(|x| x.as_ref().to_string())
                .collect(),
        )
        .encode(w)?;

        Vec::<String>::new().encode(w)?; // languages client to server
        Vec::<String>::new().encode(w)?; // languages server to client

        0u8.encode(w)?; // doesn't follow
        0u32.encode(w)?; // reserved
        Ok(())
    })
}