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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate log;
extern crate thrussh_libsodium as sodium;
#[macro_use]
extern crate thiserror;
pub use cryptovec::CryptoVec;
mod auth;
mod cipher;
mod compression;
mod kex;
mod key;
mod msg;
mod negotiation;
mod ssh_read;
mod sshbuffer;
pub use negotiation::{Named, Preferred};
mod pty;
pub use pty::Pty;
macro_rules! push_packet {
( $buffer:expr, $x:expr ) => {{
use byteorder::{BigEndian, ByteOrder};
let i0 = $buffer.len();
$buffer.extend(b"\0\0\0\0");
let x = $x;
let i1 = $buffer.len();
use std::ops::DerefMut;
let buf = $buffer.deref_mut();
BigEndian::write_u32(&mut buf[i0..], (i1 - i0 - 4) as u32);
x
}};
}
type Sha256Hash = generic_array::GenericArray<u8, <sha2::Sha256 as digest::FixedOutputDirty>::OutputSize>;
mod session;
pub mod server;
pub mod client;
#[derive(Debug, Error)]
pub enum Error {
#[error("Could not read key")]
CouldNotReadKey,
#[error("Key exchange init failed")]
KexInit,
#[error("No common key exchange algorithm")]
NoCommonKexAlgo,
#[error("No common key algorithm")]
NoCommonKeyAlgo,
#[error("No common key cipher")]
NoCommonCipher,
#[error("No common compression algorithm")]
NoCommonCompression,
#[error("invalid SSH version string")]
Version,
#[error("Key exchange failed")]
Kex,
#[error("Wrong packet authentication code")]
PacketAuth,
#[error("Inconsistent state of the protocol")]
Inconsistent,
#[error("Not yet authenticated")]
NotAuthenticated,
#[error("Index out of bounds")]
IndexOutOfBounds,
#[error("Unknown server key")]
UnknownKey,
#[error("Wrong server signature")]
WrongServerSig,
#[error("Channel not open")]
WrongChannel,
#[error("Disconnected")]
Disconnect,
#[error("No home directory when saving host key")]
NoHomeDir,
#[error("Key changed, line {}", line)]
KeyChanged { line: usize },
#[error("Connection closed by the remote side")]
HUP,
#[error("Connection timeout")]
ConnectionTimeout,
#[error("No authentication method")]
NoAuthMethod,
#[error("Channel send error")]
SendError,
#[error(transparent)]
Keys(#[from] thrussh_keys::Error),
#[error(transparent)]
IO(#[from] std::io::Error),
#[error(transparent)]
Utf8(#[from] std::str::Utf8Error),
#[error(transparent)]
Compress(#[from] flate2::CompressError),
#[error(transparent)]
Decompress(#[from] flate2::DecompressError),
#[error(transparent)]
Join(#[from] tokio::task::JoinError),
#[error(transparent)]
#[cfg(feature = "openssl")]
Openssl(#[from] openssl::error::ErrorStack),
#[error(transparent)]
Elapsed(#[from] tokio::time::error::Elapsed),
}
#[derive(Debug, Error)]
#[error("Could not reach the event loop")]
pub struct SendError {}
pub trait FromFinished<T>: futures::Future<Output = Result<T, Error>> {
fn finished(t: T) -> Self;
}
impl<T> FromFinished<T> for futures::future::Ready<Result<T, Error>> {
fn finished(t: T) -> Self {
futures::future::ready(Ok(t))
}
}
impl<T: 'static> FromFinished<T> for Box<dyn futures::Future<Output = Result<T, Error>> + Unpin> {
fn finished(t: T) -> Self {
Box::new(futures::future::ready(Ok(t)))
}
}
#[derive(Debug, Clone)]
pub struct Limits {
pub rekey_write_limit: usize,
pub rekey_read_limit: usize,
pub rekey_time_limit: std::time::Duration,
}
impl Limits {
pub fn new(write_limit: usize, read_limit: usize, time_limit: std::time::Duration) -> Limits {
assert!(write_limit <= 1 << 30 && read_limit <= 1 << 30);
Limits {
rekey_write_limit: write_limit,
rekey_read_limit: read_limit,
rekey_time_limit: time_limit,
}
}
}
impl Default for Limits {
fn default() -> Self {
Limits {
rekey_write_limit: 1 << 30,
rekey_read_limit: 1 << 30,
rekey_time_limit: std::time::Duration::from_secs(3600),
}
}
}
pub use auth::{AgentAuthError, MethodSet, Signer};
#[allow(missing_docs)]
#[derive(Debug)]
pub enum Disconnect {
HostNotAllowedToConnect = 1,
ProtocolError = 2,
KeyExchangeFailed = 3,
#[doc(hidden)]
Reserved = 4,
MACError = 5,
CompressionError = 6,
ServiceNotAvailable = 7,
ProtocolVersionNotSupported = 8,
HostKeyNotVerifiable = 9,
ConnectionLost = 10,
ByApplication = 11,
TooManyConnections = 12,
AuthCancelledByUser = 13,
NoMoreAuthMethodsAvailable = 14,
IllegalUserName = 15,
}
#[allow(missing_docs)]
#[derive(Debug, Clone)]
pub enum Sig {
ABRT,
ALRM,
FPE,
HUP,
ILL,
INT,
KILL,
PIPE,
QUIT,
SEGV,
TERM,
USR1,
Custom(String),
}
impl Sig {
fn name(&self) -> &str {
match *self {
Sig::ABRT => "ABRT",
Sig::ALRM => "ALRM",
Sig::FPE => "FPE",
Sig::HUP => "HUP",
Sig::ILL => "ILL",
Sig::INT => "INT",
Sig::KILL => "KILL",
Sig::PIPE => "PIPE",
Sig::QUIT => "QUIT",
Sig::SEGV => "SEGV",
Sig::TERM => "TERM",
Sig::USR1 => "USR1",
Sig::Custom(ref c) => c,
}
}
fn from_name(name: &[u8]) -> Result<Sig, Error> {
match name {
b"ABRT" => Ok(Sig::ABRT),
b"ALRM" => Ok(Sig::ALRM),
b"FPE" => Ok(Sig::FPE),
b"HUP" => Ok(Sig::HUP),
b"ILL" => Ok(Sig::ILL),
b"INT" => Ok(Sig::INT),
b"KILL" => Ok(Sig::KILL),
b"PIPE" => Ok(Sig::PIPE),
b"QUIT" => Ok(Sig::QUIT),
b"SEGV" => Ok(Sig::SEGV),
b"TERM" => Ok(Sig::TERM),
b"USR1" => Ok(Sig::USR1),
x => Ok(Sig::Custom(std::str::from_utf8(x)?.to_string())),
}
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
#[allow(missing_docs)]
pub enum ChannelOpenFailure {
AdministrativelyProhibited = 1,
ConnectFailed = 2,
UnknownChannelType = 3,
ResourceShortage = 4,
}
impl ChannelOpenFailure {
fn from_u32(x: u32) -> Option<ChannelOpenFailure> {
match x {
1 => Some(ChannelOpenFailure::AdministrativelyProhibited),
2 => Some(ChannelOpenFailure::ConnectFailed),
3 => Some(ChannelOpenFailure::UnknownChannelType),
4 => Some(ChannelOpenFailure::ResourceShortage),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ChannelId(u32);
#[derive(Debug)]
pub(crate) struct Channel {
recipient_channel: u32,
sender_channel: ChannelId,
recipient_window_size: u32,
sender_window_size: u32,
recipient_maximum_packet_size: u32,
sender_maximum_packet_size: u32,
pub confirmed: bool,
wants_reply: bool,
pending_data: std::collections::VecDeque<(CryptoVec, Option<u32>, usize)>,
}
#[derive(Debug)]
pub enum ChannelMsg {
Data {
data: CryptoVec,
},
ExtendedData {
data: CryptoVec,
ext: u32,
},
Eof,
Close,
XonXoff {
client_can_do: bool,
},
ExitStatus {
exit_status: u32,
},
ExitSignal {
signal_name: Sig,
core_dumped: bool,
error_message: String,
lang_tag: String,
},
WindowAdjusted {
new_size: u32,
},
Success,
}
#[cfg(test)]
mod test_compress {
use super::server::{Auth, Server as _, Session};
use super::*;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
#[tokio::test]
async fn compress_local_test() {
let _ = env_logger::try_init();
let client_key = thrussh_keys::key::KeyPair::generate_ed25519().unwrap();
let client_pubkey = Arc::new(client_key.clone_public_key());
let mut config = server::Config::default();
config.preferred = Preferred::COMPRESSED;
config.connection_timeout = None;
config.auth_rejection_time = std::time::Duration::from_secs(3);
config
.keys
.push(thrussh_keys::key::KeyPair::generate_ed25519().unwrap());
let config = Arc::new(config);
let mut sh = Server {
client_pubkey,
clients: Arc::new(Mutex::new(HashMap::new())),
id: 0,
};
let socket = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = socket.local_addr().unwrap();
tokio::spawn(async move {
let (socket, _) = socket.accept().await.unwrap();
let server = sh.new(socket.peer_addr().ok());
server::run_stream(config, socket, server).await.unwrap();
});
let mut config = client::Config::default();
config.preferred = Preferred::COMPRESSED;
let config = Arc::new(config);
dbg!(&addr);
let mut session = client::connect(config, addr, Client {}).await.unwrap();
let authenticated = session
.authenticate_publickey(std::env::var("USER").unwrap(), Arc::new(client_key))
.await
.unwrap();
assert!(authenticated);
let mut channel = session.channel_open_session().await.unwrap();
let data = &b"Hello, world!"[..];
channel.data(data).await.unwrap();
let msg = channel.wait().await.unwrap();
match msg {
ChannelMsg::Data { data: msg_data } => {
assert_eq!(*data, *msg_data)
}
msg => panic!("Unexpected message {:?}", msg),
}
}
#[derive(Clone)]
struct Server {
client_pubkey: Arc<thrussh_keys::key::PublicKey>,
clients: Arc<Mutex<HashMap<(usize, ChannelId), super::server::Handle>>>,
id: usize,
}
impl server::Server for Server {
type Handler = Self;
fn new(&mut self, _: Option<std::net::SocketAddr>) -> Self {
let s = self.clone();
self.id += 1;
s
}
}
impl server::Handler for Server {
type Error = super::Error;
type FutureAuth = futures::future::Ready<Result<(Self, server::Auth), Self::Error>>;
type FutureUnit = futures::future::Ready<Result<(Self, Session), Self::Error>>;
type FutureBool = futures::future::Ready<Result<(Self, Session, bool), Self::Error>>;
fn finished_auth(self, auth: Auth) -> Self::FutureAuth {
futures::future::ready(Ok((self, auth)))
}
fn finished_bool(self, b: bool, s: Session) -> Self::FutureBool {
futures::future::ready(Ok((self, s, b)))
}
fn finished(self, s: Session) -> Self::FutureUnit {
futures::future::ready(Ok((self, s)))
}
fn channel_open_session(self, channel: ChannelId, session: Session) -> Self::FutureUnit {
{
let mut clients = self.clients.lock().unwrap();
clients.insert((self.id, channel), session.handle());
}
self.finished(session)
}
fn auth_publickey(self, _: &str, _: &thrussh_keys::key::PublicKey) -> Self::FutureAuth {
debug!("auth_publickey");
self.finished_auth(server::Auth::Accept)
}
fn data(self, channel: ChannelId, data: &[u8], mut session: Session) -> Self::FutureUnit {
debug!("server data = {:?}", std::str::from_utf8(data));
session.data(channel, CryptoVec::from_slice(data));
self.finished(session)
}
}
struct Client {}
impl client::Handler for Client {
type Error = super::Error;
type FutureUnit = futures::future::Ready<Result<(Self, client::Session), Self::Error>>;
type FutureBool = futures::future::Ready<Result<(Self, bool), Self::Error>>;
fn finished_bool(self, b: bool) -> Self::FutureBool {
futures::future::ready(Ok((self, b)))
}
fn finished(self, session: client::Session) -> Self::FutureUnit {
futures::future::ready(Ok((self, session)))
}
fn check_server_key(
self,
server_public_key: &thrussh_keys::key::PublicKey,
) -> Self::FutureBool {
println!("check_server_key: {:?}", server_public_key);
self.finished_bool(true)
}
}
}