-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmod.rs
More file actions
2197 lines (2038 loc) · 75.9 KB
/
mod.rs
File metadata and controls
2197 lines (2038 loc) · 75.9 KB
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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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.
//
//! # Implementing clients
//!
//! Maybe surprisingly, the data types used by Russh to implement
//! clients are relatively more complicated than for servers. This is
//! mostly related to the fact that clients are generally used both in
//! a synchronous way (in the case of SSH, we can think of sending a
//! shell command), and asynchronously (because the server may send
//! unsollicited messages), and hence need to handle multiple
//! interfaces.
//!
//! The [Session](client::Session) is passed to the [Handler](client::Handler)
//! when the client receives data.
//!
//! Check out the following examples:
//!
//! * [Client that connects to a server, runs a command and prints its output](https://github.com/warp-tech/russh/blob/main/russh/examples/client_exec_simple.rs)
//! * [Client that connects to a server, runs a command in a PTY and provides interactive input/output](https://github.com/warp-tech/russh/blob/main/russh/examples/client_exec_interactive.rs)
//! * [SFTP client (with `russh-sftp`)](https://github.com/warp-tech/russh/blob/main/russh/examples/sftp_client.rs)
//!
//! [Session]: client::Session
use std::borrow::Cow;
use std::collections::{HashMap, VecDeque};
use std::convert::TryInto;
use std::num::Wrapping;
use std::pin::Pin;
use std::sync::Arc;
#[cfg(not(target_arch = "wasm32"))]
use std::time::Duration;
use futures::Future;
use futures::task::{Context, Poll};
use kex::ClientKex;
use log::{debug, error, trace, warn};
use russh_util::time::Instant;
use ssh_encoding::Decode;
use ssh_key::{Algorithm, Certificate, HashAlg, PrivateKey, PublicKey};
use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt, ReadHalf, WriteHalf};
use tokio::pin;
use tokio::sync::mpsc::{
Receiver, Sender, UnboundedReceiver, UnboundedSender, channel, unbounded_channel,
};
use tokio::sync::oneshot;
pub use crate::auth::AuthResult;
use crate::channels::{
Channel, ChannelMsg, ChannelReadHalf, ChannelRef, ChannelWriteHalf, WindowSizeRef,
};
use crate::cipher::{self, OpeningKey, clear};
use crate::kex::{KexAlgorithmImplementor, KexCause, KexProgress, SessionKexState};
use crate::keys::PrivateKeyWithHashAlg;
use crate::msg::{is_kex_msg, validate_server_msg_strict_kex};
use crate::session::{CommonSession, EncryptedState, GlobalRequestResponse, NewKeys};
use crate::ssh_read::SshRead;
use crate::sshbuffer::{IncomingSshPacket, PacketWriter, SSHBuffer, SshId};
use crate::{
ChannelId, ChannelOpenFailure, Disconnect, Error, Limits, MethodSet, Sig, auth, map_err, msg,
negotiation,
};
mod encrypted;
mod kex;
mod session;
#[cfg(test)]
mod test;
/// Actual client session's state.
///
/// It is in charge of multiplexing and keeping track of various channels
/// that may get opened and closed during the lifetime of an SSH session and
/// allows sending messages to the server.
#[derive(Debug)]
pub struct Session {
kex: SessionKexState<ClientKex>,
common: CommonSession<Arc<Config>>,
receiver: Receiver<Msg>,
sender: UnboundedSender<Reply>,
channels: HashMap<ChannelId, ChannelRef>,
target_window_size: u32,
pending_reads: Vec<Vec<u8>>,
pending_len: u32,
inbound_channel_sender: Sender<Msg>,
inbound_channel_receiver: Receiver<Msg>,
open_global_requests: VecDeque<GlobalRequestResponse>,
server_sig_algs: Option<Vec<Algorithm>>,
}
impl Drop for Session {
fn drop(&mut self) {
debug!("drop session")
}
}
#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
enum Reply {
AuthSuccess,
AuthFailure {
proceed_with_methods: MethodSet,
partial_success: bool,
},
ChannelOpenFailure,
SignRequest {
key: ssh_key::PublicKey,
data: Vec<u8>,
},
SignRequestCert {
cert: Certificate,
hash_alg: Option<HashAlg>,
data: Vec<u8>,
},
AuthInfoRequest {
name: String,
instructions: String,
prompts: Vec<Prompt>,
},
}
#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub enum Msg {
Authenticate {
user: String,
method: auth::Method,
},
AuthInfoResponse {
responses: Vec<String>,
},
Signed {
data: Vec<u8>,
},
ChannelOpenSession {
channel_ref: ChannelRef,
},
ChannelOpenX11 {
originator_address: String,
originator_port: u32,
channel_ref: ChannelRef,
},
ChannelOpenDirectTcpIp {
host_to_connect: String,
port_to_connect: u32,
originator_address: String,
originator_port: u32,
channel_ref: ChannelRef,
},
ChannelOpenDirectStreamLocal {
socket_path: String,
channel_ref: ChannelRef,
},
TcpIpForward {
/// Provide a channel for the reply result to request a reply from the server
reply_channel: Option<oneshot::Sender<Option<u32>>>,
address: String,
port: u32,
},
CancelTcpIpForward {
/// Provide a channel for the reply result to request a reply from the server
reply_channel: Option<oneshot::Sender<bool>>,
address: String,
port: u32,
},
StreamLocalForward {
/// Provide a channel for the reply result to request a reply from the server
reply_channel: Option<oneshot::Sender<bool>>,
socket_path: String,
},
CancelStreamLocalForward {
/// Provide a channel for the reply result to request a reply from the server
reply_channel: Option<oneshot::Sender<bool>>,
socket_path: String,
},
Close {
id: ChannelId,
},
Disconnect {
reason: Disconnect,
description: String,
language_tag: String,
},
Channel(ChannelId, ChannelMsg),
Rekey,
AwaitExtensionInfo {
extension_name: String,
reply_channel: oneshot::Sender<()>,
},
GetServerSigAlgs {
reply_channel: oneshot::Sender<Option<Vec<Algorithm>>>,
},
/// Send a keepalive packet to the remote
Keepalive {
want_reply: bool,
},
Ping {
reply_channel: oneshot::Sender<()>,
},
NoMoreSessions {
want_reply: bool,
},
}
impl From<(ChannelId, ChannelMsg)> for Msg {
fn from((id, msg): (ChannelId, ChannelMsg)) -> Self {
Msg::Channel(id, msg)
}
}
#[derive(Debug)]
pub enum KeyboardInteractiveAuthResponse {
Success,
Failure {
/// The server suggests to proceed with these auth methods
remaining_methods: MethodSet,
/// The server says that though auth method has been accepted,
/// further authentication is required
partial_success: bool,
},
InfoRequest {
name: String,
instructions: String,
prompts: Vec<Prompt>,
},
}
#[derive(Debug)]
pub struct Prompt {
pub prompt: String,
pub echo: bool,
}
#[derive(Debug)]
pub struct RemoteDisconnectInfo {
pub reason_code: crate::Disconnect,
pub message: String,
pub lang_tag: String,
}
#[derive(Debug)]
pub enum DisconnectReason<E: From<crate::Error> + Send> {
ReceivedDisconnect(RemoteDisconnectInfo),
Error(E),
}
/// Handle to a session, used to send messages to a client outside of
/// the request/response cycle.
pub struct Handle<H: Handler> {
sender: Sender<Msg>,
receiver: UnboundedReceiver<Reply>,
join: russh_util::runtime::JoinHandle<Result<(), H::Error>>,
channel_buffer_size: usize,
}
impl<H: Handler> Drop for Handle<H> {
fn drop(&mut self) {
debug!("drop handle")
}
}
impl<H: Handler> Handle<H> {
pub fn is_closed(&self) -> bool {
self.sender.is_closed()
}
/// Perform no authentication. This is useful for testing, but should not be
/// used in most other circumstances.
pub async fn authenticate_none<U: Into<String>>(
&mut self,
user: U,
) -> Result<AuthResult, crate::Error> {
let user = user.into();
self.sender
.send(Msg::Authenticate {
user,
method: auth::Method::None,
})
.await
.map_err(|_| crate::Error::SendError)?;
self.wait_recv_reply().await
}
/// Perform password-based SSH authentication.
pub async fn authenticate_password<U: Into<String>, P: Into<String>>(
&mut self,
user: U,
password: P,
) -> Result<AuthResult, crate::Error> {
let user = user.into();
self.sender
.send(Msg::Authenticate {
user,
method: auth::Method::Password {
password: password.into(),
},
})
.await
.map_err(|_| crate::Error::SendError)?;
self.wait_recv_reply().await
}
/// Initiate Keyboard-Interactive based SSH authentication.
///
/// * `submethods` - Hints to the server the preferred methods to be used for authentication
pub async fn authenticate_keyboard_interactive_start<
U: Into<String>,
S: Into<Option<String>>,
>(
&mut self,
user: U,
submethods: S,
) -> Result<KeyboardInteractiveAuthResponse, crate::Error> {
self.sender
.send(Msg::Authenticate {
user: user.into(),
method: auth::Method::KeyboardInteractive {
submethods: submethods.into().unwrap_or_else(|| "".to_owned()),
},
})
.await
.map_err(|_| crate::Error::SendError)?;
self.wait_recv_keyboard_interactive_reply().await
}
/// Respond to AuthInfoRequests from the server. A server can send any number of these Requests
/// including empty requests. You may have to call this function multple times in order to
/// complete Keyboard-Interactive based SSH authentication.
///
/// * `responses` - The responses to each prompt. The number of responses must match the number
/// of prompts. If a prompt has an empty string, then the response should be an empty string.
pub async fn authenticate_keyboard_interactive_respond(
&mut self,
responses: Vec<String>,
) -> Result<KeyboardInteractiveAuthResponse, crate::Error> {
self.sender
.send(Msg::AuthInfoResponse { responses })
.await
.map_err(|_| crate::Error::SendError)?;
self.wait_recv_keyboard_interactive_reply().await
}
async fn wait_recv_keyboard_interactive_reply(
&mut self,
) -> Result<KeyboardInteractiveAuthResponse, crate::Error> {
loop {
match self.receiver.recv().await {
Some(Reply::AuthSuccess) => return Ok(KeyboardInteractiveAuthResponse::Success),
Some(Reply::AuthFailure {
proceed_with_methods: remaining_methods,
partial_success,
}) => {
return Ok(KeyboardInteractiveAuthResponse::Failure {
remaining_methods,
partial_success,
});
}
Some(Reply::AuthInfoRequest {
name,
instructions,
prompts,
}) => {
return Ok(KeyboardInteractiveAuthResponse::InfoRequest {
name,
instructions,
prompts,
});
}
None => return Err(crate::Error::RecvError),
_ => {}
}
}
}
async fn wait_recv_reply(&mut self) -> Result<AuthResult, crate::Error> {
loop {
match self.receiver.recv().await {
Some(Reply::AuthSuccess) => return Ok(AuthResult::Success),
Some(Reply::AuthFailure {
proceed_with_methods: remaining_methods,
partial_success,
}) => {
return Ok(AuthResult::Failure {
remaining_methods,
partial_success,
});
}
None => {
return Ok(AuthResult::Failure {
remaining_methods: MethodSet::empty(),
partial_success: false,
});
}
_ => {}
}
}
}
/// Perform public key-based SSH authentication.
///
/// For RSA keys, you'll need to decide on which hash algorithm to use.
/// This is the difference between what is also known as
/// `ssh-rsa`, `rsa-sha2-256`, and `rsa-sha2-512` "keys" in OpenSSH.
/// You can use [Handle::best_supported_rsa_hash] to automatically
/// figure out the best hash algorithm for RSA keys.
pub async fn authenticate_publickey<U: Into<String>>(
&mut self,
user: U,
key: PrivateKeyWithHashAlg,
) -> Result<AuthResult, crate::Error> {
let user = user.into();
self.sender
.send(Msg::Authenticate {
user,
method: auth::Method::PublicKey { key },
})
.await
.map_err(|_| crate::Error::SendError)?;
self.wait_recv_reply().await
}
/// Perform public OpenSSH Certificate-based SSH authentication
pub async fn authenticate_openssh_cert<U: Into<String>>(
&mut self,
user: U,
key: Arc<PrivateKey>,
cert: Certificate,
) -> Result<AuthResult, crate::Error> {
let user = user.into();
self.sender
.send(Msg::Authenticate {
user,
method: auth::Method::OpenSshCertificate { key, cert },
})
.await
.map_err(|_| crate::Error::SendError)?;
self.wait_recv_reply().await
}
/// Authenticate using a custom method that implements the
/// [`Signer`][auth::Signer] trait. Currently, this crate only provides an
/// implementation for an [SSH agent][crate::keys::agent::client::AgentClient].
pub async fn authenticate_publickey_with<U: Into<String>, S: auth::Signer>(
&mut self,
user: U,
key: ssh_key::PublicKey,
hash_alg: Option<HashAlg>,
signer: &mut S,
) -> Result<AuthResult, S::Error> {
let user = user.into();
if self
.sender
.send(Msg::Authenticate {
user,
method: auth::Method::FuturePublicKey { key, hash_alg },
})
.await
.is_err()
{
return Err((crate::SendError {}).into());
}
loop {
let reply = self.receiver.recv().await;
match reply {
Some(Reply::AuthSuccess) => return Ok(AuthResult::Success),
Some(Reply::AuthFailure {
proceed_with_methods: remaining_methods,
partial_success,
}) => {
return Ok(AuthResult::Failure {
remaining_methods,
partial_success,
});
}
Some(Reply::SignRequest { key, data }) => {
let data = signer.auth_sign(&key.into(), hash_alg, data).await;
let data = match data {
Ok(data) => data,
Err(e) => return Err(e),
};
if self.sender.send(Msg::Signed { data }).await.is_err() {
return Err((crate::SendError {}).into());
}
}
None => {
return Ok(AuthResult::Failure {
remaining_methods: MethodSet::empty(),
partial_success: false,
});
}
_ => {}
}
}
}
/// Authenticate using a certificate with a custom signer that implements the
/// [`Signer`][auth::Signer] trait. This is for certificate-based authentication
/// where the signing is delegated to an external signer (e.g., SSH agent).
///
/// For RSA certificates, you can specify the hash algorithm to use.
pub async fn authenticate_certificate_with<U: Into<String>, S: auth::Signer>(
&mut self,
user: U,
cert: Certificate,
hash_alg: Option<HashAlg>,
signer: &mut S,
) -> Result<AuthResult, S::Error> {
let user = user.into();
if self
.sender
.send(Msg::Authenticate {
user,
method: auth::Method::FutureCertificate { cert, hash_alg },
})
.await
.is_err()
{
return Err((crate::SendError {}).into());
}
loop {
let reply = self.receiver.recv().await;
match reply {
Some(Reply::AuthSuccess) => return Ok(AuthResult::Success),
Some(Reply::AuthFailure {
proceed_with_methods: remaining_methods,
partial_success,
}) => {
return Ok(AuthResult::Failure {
remaining_methods,
partial_success,
});
}
Some(Reply::SignRequestCert {
cert,
hash_alg,
data,
}) => {
let data = signer.auth_sign(&cert.into(), hash_alg, data).await;
let data = match data {
Ok(data) => data,
Err(e) => return Err(e),
};
if self.sender.send(Msg::Signed { data }).await.is_err() {
return Err((crate::SendError {}).into());
}
}
None => {
return Ok(AuthResult::Failure {
remaining_methods: MethodSet::empty(),
partial_success: false,
});
}
_ => {}
}
}
}
/// Wait for confirmation that a channel is open
async fn wait_channel_confirmation(
&self,
mut receiver: Receiver<ChannelMsg>,
window_size_ref: WindowSizeRef,
) -> Result<Channel<Msg>, crate::Error> {
loop {
match receiver.recv().await {
Some(ChannelMsg::Open {
id,
max_packet_size,
window_size,
}) => {
window_size_ref.update(window_size).await;
return Ok(Channel {
write_half: ChannelWriteHalf {
id,
sender: self.sender.clone(),
max_packet_size,
window_size: window_size_ref,
},
read_half: ChannelReadHalf { receiver },
});
}
Some(ChannelMsg::OpenFailure(reason)) => {
return Err(crate::Error::ChannelOpenFailure(reason));
}
None => {
debug!("channel confirmation sender was dropped");
return Err(crate::Error::Disconnect);
}
msg => {
debug!("msg = {msg:?}");
}
}
}
}
/// See [`Handle::best_supported_rsa_hash`].
#[cfg(not(target_arch = "wasm32"))]
async fn await_extension_info(&self, extension_name: String) -> Result<(), crate::Error> {
let (sender, receiver) = oneshot::channel();
self.sender
.send(Msg::AwaitExtensionInfo {
extension_name,
reply_channel: sender,
})
.await
.map_err(|_| crate::Error::SendError)?;
let _ = tokio::time::timeout(Duration::from_secs(1), receiver).await;
Ok(())
}
/// Returns the best RSA hash algorithm supported by the server,
/// as indicated by the `server-sig-algs` extension.
/// If the server does not support the extension,
/// `None` is returned. In this case you may still attempt an authentication
/// with `rsa-sha2-256` or `rsa-sha2-512` and hope for the best.
/// If the server supports the extension, but does not support `rsa-sha2-*`,
/// `Some(None)` is returned.
///
/// Note that this method will wait for up to 1 second for the server to
/// send the extension info if it hasn't done so yet (except when running under
/// WebAssembly). Unfortunately the timing of the EXT_INFO message cannot be known
/// in advance (RFC 8308).
///
/// If this method returns `None` once, then for most SSH servers
/// you can assume that it will return `None` every time.
pub async fn best_supported_rsa_hash(&self) -> Result<Option<Option<HashAlg>>, Error> {
// Wait for the extension info from the server
#[cfg(not(target_arch = "wasm32"))]
self.await_extension_info("server-sig-algs".into()).await?;
let (sender, receiver) = oneshot::channel();
self.sender
.send(Msg::GetServerSigAlgs {
reply_channel: sender,
})
.await
.map_err(|_| crate::Error::SendError)?;
if let Some(ssa) = receiver.await.map_err(|_| Error::Inconsistent)? {
let possible_algs = [
Some(ssh_key::HashAlg::Sha512),
Some(ssh_key::HashAlg::Sha256),
None,
];
for alg in possible_algs.into_iter() {
if ssa.contains(&Algorithm::Rsa { hash: alg }) {
return Ok(Some(alg));
}
}
}
Ok(None)
}
/// Request a session channel (the most basic type of
/// channel). This function returns `Some(..)` immediately if the
/// connection is authenticated, but the channel only becomes
/// usable when it's confirmed by the server, as indicated by the
/// `confirmed` field of the corresponding `Channel`.
pub async fn channel_open_session(&self) -> Result<Channel<Msg>, crate::Error> {
let (sender, receiver) = channel(self.channel_buffer_size);
let channel_ref = ChannelRef::new(sender);
let window_size_ref = channel_ref.window_size().clone();
self.sender
.send(Msg::ChannelOpenSession { channel_ref })
.await
.map_err(|_| crate::Error::SendError)?;
self.wait_channel_confirmation(receiver, window_size_ref)
.await
}
/// Request an X11 channel, on which the X11 protocol may be tunneled.
pub async fn channel_open_x11<A: Into<String>>(
&self,
originator_address: A,
originator_port: u32,
) -> Result<Channel<Msg>, crate::Error> {
let (sender, receiver) = channel(self.channel_buffer_size);
let channel_ref = ChannelRef::new(sender);
let window_size_ref = channel_ref.window_size().clone();
self.sender
.send(Msg::ChannelOpenX11 {
originator_address: originator_address.into(),
originator_port,
channel_ref,
})
.await
.map_err(|_| crate::Error::SendError)?;
self.wait_channel_confirmation(receiver, window_size_ref)
.await
}
/// Open a TCP/IP forwarding channel. This is usually done when a
/// connection comes to a locally forwarded TCP/IP port. See
/// [RFC4254](https://tools.ietf.org/html/rfc4254#section-7). The
/// TCP/IP packets can then be tunneled through the channel using
/// `.data()`. After writing a stream to a channel using
/// [`.data()`][Channel::data], be sure to call [`.eof()`][Channel::eof] to
/// indicate that no more data will be sent, or you may see hangs when
/// writing large streams.
pub async fn channel_open_direct_tcpip<A: Into<String>, B: Into<String>>(
&self,
host_to_connect: A,
port_to_connect: u32,
originator_address: B,
originator_port: u32,
) -> Result<Channel<Msg>, crate::Error> {
let (sender, receiver) = channel(self.channel_buffer_size);
let channel_ref = ChannelRef::new(sender);
let window_size_ref = channel_ref.window_size().clone();
self.sender
.send(Msg::ChannelOpenDirectTcpIp {
host_to_connect: host_to_connect.into(),
port_to_connect,
originator_address: originator_address.into(),
originator_port,
channel_ref,
})
.await
.map_err(|_| crate::Error::SendError)?;
self.wait_channel_confirmation(receiver, window_size_ref)
.await
}
pub async fn channel_open_direct_streamlocal<S: Into<String>>(
&self,
socket_path: S,
) -> Result<Channel<Msg>, crate::Error> {
let (sender, receiver) = channel(self.channel_buffer_size);
let channel_ref = ChannelRef::new(sender);
let window_size_ref = channel_ref.window_size().clone();
self.sender
.send(Msg::ChannelOpenDirectStreamLocal {
socket_path: socket_path.into(),
channel_ref,
})
.await
.map_err(|_| crate::Error::SendError)?;
self.wait_channel_confirmation(receiver, window_size_ref)
.await
}
/// Requests the server to open a TCP/IP forward channel
///
/// If port == 0 the server will choose a port that will be returned, returns 0 otherwise
pub async fn tcpip_forward<A: Into<String>>(
&self,
address: A,
port: u32,
) -> Result<u32, crate::Error> {
let (reply_send, reply_recv) = oneshot::channel();
self.sender
.send(Msg::TcpIpForward {
reply_channel: Some(reply_send),
address: address.into(),
port,
})
.await
.map_err(|_| crate::Error::SendError)?;
match reply_recv.await {
Ok(Some(port)) => Ok(port),
Ok(None) => Err(crate::Error::RequestDenied),
Err(e) => {
error!("Unable to receive TcpIpForward result: {e:?}");
Err(crate::Error::Disconnect)
}
}
}
// Requests the server to close a TCP/IP forward channel
pub async fn cancel_tcpip_forward<A: Into<String>>(
&self,
address: A,
port: u32,
) -> Result<(), crate::Error> {
let (reply_send, reply_recv) = oneshot::channel();
self.sender
.send(Msg::CancelTcpIpForward {
reply_channel: Some(reply_send),
address: address.into(),
port,
})
.await
.map_err(|_| crate::Error::SendError)?;
match reply_recv.await {
Ok(true) => Ok(()),
Ok(false) => Err(crate::Error::RequestDenied),
Err(e) => {
error!("Unable to receive CancelTcpIpForward result: {e:?}");
Err(crate::Error::Disconnect)
}
}
}
// Requests the server to open a UDS forward channel
pub async fn streamlocal_forward<A: Into<String>>(
&self,
socket_path: A,
) -> Result<(), crate::Error> {
let (reply_send, reply_recv) = oneshot::channel();
self.sender
.send(Msg::StreamLocalForward {
reply_channel: Some(reply_send),
socket_path: socket_path.into(),
})
.await
.map_err(|_| crate::Error::SendError)?;
match reply_recv.await {
Ok(true) => Ok(()),
Ok(false) => Err(crate::Error::RequestDenied),
Err(e) => {
error!("Unable to receive StreamLocalForward result: {e:?}");
Err(crate::Error::Disconnect)
}
}
}
// Requests the server to close a UDS forward channel
pub async fn cancel_streamlocal_forward<A: Into<String>>(
&self,
socket_path: A,
) -> Result<(), crate::Error> {
let (reply_send, reply_recv) = oneshot::channel();
self.sender
.send(Msg::CancelStreamLocalForward {
reply_channel: Some(reply_send),
socket_path: socket_path.into(),
})
.await
.map_err(|_| crate::Error::SendError)?;
match reply_recv.await {
Ok(true) => Ok(()),
Ok(false) => Err(crate::Error::RequestDenied),
Err(e) => {
error!("Unable to receive CancelStreamLocalForward result: {e:?}");
Err(crate::Error::Disconnect)
}
}
}
/// Sends a disconnect message.
pub async fn disconnect(
&self,
reason: Disconnect,
description: &str,
language_tag: &str,
) -> Result<(), crate::Error> {
self.sender
.send(Msg::Disconnect {
reason,
description: description.into(),
language_tag: language_tag.into(),
})
.await
.map_err(|_| crate::Error::SendError)?;
Ok(())
}
/// Send data to the session referenced by this handler.
///
/// This is useful for server-initiated channels; for channels created by
/// the client, prefer to use the Channel returned from the `open_*` methods.
pub async fn data(
&self,
id: ChannelId,
data: impl Into<bytes::Bytes>,
) -> Result<(), bytes::Bytes> {
let data = data.into();
self.sender
.send(Msg::Channel(id, ChannelMsg::Data { data: data.clone() }))
.await
.map_err(|e| match e.0 {
Msg::Channel(_, ChannelMsg::Data { data, .. }) => data,
_ => unreachable!(),
})
}
/// Asynchronously perform a session re-key at the next opportunity
pub async fn rekey_soon(&self) -> Result<(), Error> {
self.sender
.send(Msg::Rekey)
.await
.map_err(|_| Error::SendError)?;
Ok(())
}
/// Send a keepalive package to the remote peer.
pub async fn send_keepalive(&self, want_reply: bool) -> Result<(), Error> {
self.sender
.send(Msg::Keepalive { want_reply })
.await
.map_err(|_| Error::SendError)
}
/// Send a keepalive/ping package to the remote peer, and wait for the reply/pong.
pub async fn send_ping(&self) -> Result<(), Error> {
let (sender, receiver) = oneshot::channel();
self.sender
.send(Msg::Ping {
reply_channel: sender,
})
.await
.map_err(|_| Error::SendError)?;
let _ = receiver.await;
Ok(())
}
/// Send a no-more-sessions request to the remote peer.
pub async fn no_more_sessions(&self, want_reply: bool) -> Result<(), Error> {
self.sender
.send(Msg::NoMoreSessions { want_reply })
.await
.map_err(|_| Error::SendError)
}
}
impl<H: Handler> Future for Handle<H> {
type Output = Result<(), H::Error>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
match Future::poll(Pin::new(&mut self.join), cx) {
Poll::Ready(r) => Poll::Ready(match r {
Ok(Ok(x)) => Ok(x),
Err(e) => Err(crate::Error::from(e).into()),
Ok(Err(e)) => Err(e),
}),
Poll::Pending => Poll::Pending,
}
}
}
/// Connect to a server at the address specified, using the [`Handler`]
/// (implemented by you) and [`Config`] specified. Returns a future that
/// resolves to a [`Handle`]. This handle can then be used to create channels,
/// which in turn can be used to tunnel TCP connections, request a PTY, execute
/// commands, etc. The future will resolve to an error if the connection fails.
/// This function creates a connection to the `addr` specified using a
/// [`tokio::net::TcpStream`] and then calls [`connect_stream`] under the hood.
#[cfg(not(target_arch = "wasm32"))]
pub async fn connect<H: Handler + Send + 'static, A: tokio::net::ToSocketAddrs>(
config: Arc<Config>,
addrs: A,
handler: H,
) -> Result<Handle<H>, H::Error> {
let socket = map_err!(tokio::net::TcpStream::connect(addrs).await)?;
if config.as_ref().nodelay
&& let Err(e) = socket.set_nodelay(true) {
warn!("set_nodelay() failed: {e:?}");
}
connect_stream(config, socket, handler).await
}
/// Connect a stream to a server. This stream must implement
/// [`tokio::io::AsyncRead`] and [`tokio::io::AsyncWrite`], as well as [`Unpin`]
/// and [`Send`]. Typically, you may prefer to use [`connect`], which uses a
/// [`tokio::net::TcpStream`] and then calls this function under the hood.
pub async fn connect_stream<H, R>(
config: Arc<Config>,
mut stream: R,
handler: H,
) -> Result<Handle<H>, H::Error>
where
H: Handler + Send + 'static,
R: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
// Writing SSH id.
let mut write_buffer = SSHBuffer::new();
debug!("ssh id = {:?}", config.as_ref().client_id);
write_buffer.send_ssh_id(&config.as_ref().client_id);
map_err!(stream.write_all(&write_buffer.buffer).await)?;
// Reading SSH id and allocating a session if correct.
let mut stream = SshRead::new(stream);
let sshid = stream.read_ssh_id().await?;