-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhandler.rs
More file actions
1495 lines (1322 loc) · 50.4 KB
/
handler.rs
File metadata and controls
1495 lines (1322 loc) · 50.4 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 2025 Lablup Inc. and Jeongkyu Shin
//
// 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.
//! SSH handler implementation for the russh server.
//!
//! This module implements the `russh::server::Handler` trait which handles
//! all SSH protocol events for a single connection.
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use futures::FutureExt;
use russh::keys::ssh_key;
use russh::server::{Auth, Msg, Session};
use russh::{Channel, ChannelId, MethodKind, MethodSet, Pty};
use tokio::sync::RwLock;
use zeroize::Zeroizing;
use super::auth::AuthProvider;
use super::config::ServerConfig;
use super::exec::CommandExecutor;
use super::pty::PtyConfig as PtyMasterConfig;
use super::security::AuthRateLimiter;
use super::session::{ChannelState, PtyConfig, SessionId, SessionInfo, SessionManager};
use super::sftp::SftpHandler;
use super::shell::ShellSession;
use crate::shared::rate_limit::RateLimiter;
/// SSH handler for a single client connection.
///
/// This struct implements the `russh::server::Handler` trait to handle
/// SSH protocol events such as authentication, channel operations, and data transfer.
pub struct SshHandler {
/// Remote address of the connected client.
peer_addr: Option<SocketAddr>,
/// Server configuration.
config: Arc<ServerConfig>,
/// Shared session manager.
sessions: Arc<RwLock<SessionManager>>,
/// Authentication provider for verifying credentials.
auth_provider: Arc<dyn AuthProvider>,
/// Rate limiter for authentication attempts.
rate_limiter: RateLimiter<String>,
/// Auth rate limiter with ban support (fail2ban-like).
auth_rate_limiter: Option<AuthRateLimiter>,
/// Session information for this connection.
session_info: Option<SessionInfo>,
/// Active channels for this connection.
channels: HashMap<ChannelId, ChannelState>,
}
impl SshHandler {
/// Create a new SSH handler for a client connection.
pub fn new(
peer_addr: Option<SocketAddr>,
config: Arc<ServerConfig>,
sessions: Arc<RwLock<SessionManager>>,
) -> Self {
let auth_provider = config.create_auth_provider();
// Rate limiter: allow burst of 5 attempts, refill 1 attempt per second
// Note: This creates a per-handler rate limiter. For production use,
// prefer with_rate_limiter() to share a rate limiter across handlers.
let rate_limiter = RateLimiter::with_simple_config(5, 1.0);
Self {
peer_addr,
config,
sessions,
auth_provider,
rate_limiter,
auth_rate_limiter: None,
session_info: Some(SessionInfo::new(peer_addr)),
channels: HashMap::new(),
}
}
/// Create a new SSH handler with a shared rate limiter.
///
/// This is the preferred constructor for production use as it shares
/// the rate limiter across all handlers, providing server-wide rate limiting.
pub fn with_rate_limiter(
peer_addr: Option<SocketAddr>,
config: Arc<ServerConfig>,
sessions: Arc<RwLock<SessionManager>>,
rate_limiter: RateLimiter<String>,
) -> Self {
let auth_provider = config.create_auth_provider();
Self {
peer_addr,
config,
sessions,
auth_provider,
rate_limiter,
auth_rate_limiter: None,
session_info: Some(SessionInfo::new(peer_addr)),
channels: HashMap::new(),
}
}
/// Create a new SSH handler with shared rate limiters including auth ban support.
///
/// This is the preferred constructor for production use as it shares
/// both rate limiters across all handlers, providing server-wide rate limiting
/// and fail2ban-like functionality.
pub fn with_rate_limiters(
peer_addr: Option<SocketAddr>,
config: Arc<ServerConfig>,
sessions: Arc<RwLock<SessionManager>>,
rate_limiter: RateLimiter<String>,
auth_rate_limiter: AuthRateLimiter,
) -> Self {
let auth_provider = config.create_auth_provider();
Self {
peer_addr,
config,
sessions,
auth_provider,
rate_limiter,
auth_rate_limiter: Some(auth_rate_limiter),
session_info: Some(SessionInfo::new(peer_addr)),
channels: HashMap::new(),
}
}
/// Create a new SSH handler with a custom auth provider.
///
/// This is useful for testing or when you need a different auth provider.
pub fn with_auth_provider(
peer_addr: Option<SocketAddr>,
config: Arc<ServerConfig>,
sessions: Arc<RwLock<SessionManager>>,
auth_provider: Arc<dyn AuthProvider>,
) -> Self {
let rate_limiter = RateLimiter::with_simple_config(5, 1.0);
Self {
peer_addr,
config,
sessions,
auth_provider,
rate_limiter,
auth_rate_limiter: None,
session_info: Some(SessionInfo::new(peer_addr)),
channels: HashMap::new(),
}
}
/// Get the peer address of the connected client.
pub fn peer_addr(&self) -> Option<SocketAddr> {
self.peer_addr
}
/// Get the session ID, if the session has been created.
pub fn session_id(&self) -> Option<SessionId> {
self.session_info.as_ref().map(|s| s.id)
}
/// Check if the connection is authenticated.
pub fn is_authenticated(&self) -> bool {
self.session_info.as_ref().is_some_and(|s| s.authenticated)
}
/// Get the authenticated username, if any.
pub fn username(&self) -> Option<&str> {
self.session_info.as_ref().and_then(|s| s.user.as_deref())
}
/// Build the method set of allowed authentication methods.
fn allowed_methods(&self) -> MethodSet {
let mut methods = MethodSet::empty();
if self.config.allow_publickey_auth {
methods.push(MethodKind::PublicKey);
}
if self.config.allow_password_auth {
methods.push(MethodKind::Password);
}
if self.config.allow_keyboard_interactive {
methods.push(MethodKind::KeyboardInteractive);
}
methods
}
/// Check if the maximum authentication attempts has been exceeded.
fn auth_attempts_exceeded(&self) -> bool {
self.session_info
.as_ref()
.is_some_and(|s| s.auth_attempts >= self.config.max_auth_attempts)
}
}
impl russh::server::Handler for SshHandler {
type Error = anyhow::Error;
/// Called when a new session channel is created.
fn channel_open_session(
&mut self,
channel: Channel<Msg>,
_session: &mut Session,
) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
let channel_id = channel.id();
tracing::debug!(
peer = ?self.peer_addr,
channel = ?channel_id,
"Channel opened for session"
);
// Store the channel itself so we can use it for subsystems like SFTP
self.channels
.insert(channel_id, ChannelState::with_channel(channel));
async { Ok(true) }
}
/// Handle 'none' authentication.
///
/// Always rejects and advertises available authentication methods.
fn auth_none(
&mut self,
user: &str,
) -> impl std::future::Future<Output = Result<Auth, Self::Error>> + Send {
tracing::debug!(
user = %user,
peer = ?self.peer_addr,
"Auth none attempt"
);
// Create session info if not already created
let peer_addr = self.peer_addr;
let sessions = Arc::clone(&self.sessions);
let methods = self.allowed_methods();
// We need to handle session creation
let session_info_ref = &mut self.session_info;
async move {
if session_info_ref.is_none() {
let mut sessions_guard = sessions.write().await;
if let Some(info) = sessions_guard.create_session(peer_addr) {
tracing::info!(
session_id = %info.id,
peer = ?peer_addr,
"New session created"
);
*session_info_ref = Some(info);
} else {
tracing::warn!(
peer = ?peer_addr,
"Session limit reached, rejecting connection"
);
return Ok(Auth::Reject {
proceed_with_methods: None,
partial_success: false,
});
}
}
// Reject with available methods
tracing::debug!(
methods = ?methods,
"Rejecting auth_none, advertising methods"
);
Ok(Auth::Reject {
proceed_with_methods: Some(methods),
partial_success: false,
})
}
}
/// Handle public key authentication.
///
/// Verifies the public key against the user's authorized_keys file.
fn auth_publickey(
&mut self,
user: &str,
public_key: &ssh_key::PublicKey,
) -> impl std::future::Future<Output = Result<Auth, Self::Error>> + Send {
tracing::debug!(
user = %user,
peer = ?self.peer_addr,
key_type = %public_key.algorithm(),
"Public key authentication attempt"
);
// Increment auth attempts
if let Some(ref mut info) = self.session_info {
info.increment_auth_attempts();
}
// Check if max attempts exceeded
let exceeded = self.auth_attempts_exceeded();
let mut methods = self.allowed_methods();
methods.remove(MethodKind::PublicKey);
// Clone what we need for the async block
let auth_provider = Arc::clone(&self.auth_provider);
let rate_limiter = self.rate_limiter.clone();
let auth_rate_limiter = self.auth_rate_limiter.clone();
let peer_addr = self.peer_addr;
let user = user.to_string();
let public_key = public_key.clone();
// Get mutable reference to session_info for authentication update
let session_info = &mut self.session_info;
async move {
// Check if IP is banned (fail2ban-like check)
if let Some(ref limiter) = auth_rate_limiter {
if let Some(ip) = peer_addr.map(|a| a.ip()) {
if limiter.is_banned(&ip).await {
tracing::warn!(
user = %user,
peer = ?peer_addr,
"Rejected auth from banned IP"
);
return Ok(Auth::Reject {
proceed_with_methods: None,
partial_success: false,
});
}
}
}
if exceeded {
tracing::warn!(
user = %user,
peer = ?peer_addr,
"Max authentication attempts exceeded"
);
return Ok(Auth::Reject {
proceed_with_methods: None,
partial_success: false,
});
}
// Check rate limiting based on peer address
let rate_key = peer_addr
.map(|addr| addr.ip().to_string())
.unwrap_or_else(|| "unknown".to_string());
if rate_limiter.is_rate_limited(&rate_key).await {
tracing::warn!(
user = %user,
peer = ?peer_addr,
"Rate limited authentication attempt"
);
return Ok(Auth::Reject {
proceed_with_methods: None,
partial_success: false,
});
}
// Try to acquire a rate limit token
if rate_limiter.try_acquire(&rate_key).await.is_err() {
tracing::warn!(
user = %user,
peer = ?peer_addr,
"Rate limit exceeded"
);
return Ok(Auth::Reject {
proceed_with_methods: None,
partial_success: false,
});
}
// Verify public key using auth provider
match auth_provider.verify_publickey(&user, &public_key).await {
Ok(result) if result.is_accepted() => {
tracing::info!(
user = %user,
peer = ?peer_addr,
key_type = %public_key.algorithm(),
"Public key authentication successful"
);
// Mark session as authenticated
if let Some(ref mut info) = session_info {
info.authenticate(&user);
}
// Record success to reset failure counter
if let Some(ref limiter) = auth_rate_limiter {
if let Some(ip) = peer_addr.map(|a| a.ip()) {
limiter.record_success(&ip).await;
}
}
Ok(Auth::Accept)
}
Ok(_) => {
tracing::debug!(
user = %user,
peer = ?peer_addr,
key_type = %public_key.algorithm(),
"Public key authentication rejected"
);
// Record failure for ban tracking
if let Some(ref limiter) = auth_rate_limiter {
if let Some(ip) = peer_addr.map(|a| a.ip()) {
let banned = limiter.record_failure(ip).await;
if banned {
tracing::warn!(
user = %user,
peer = ?peer_addr,
"IP banned due to too many failed auth attempts"
);
}
}
}
let proceed = if methods.is_empty() {
None
} else {
Some(methods)
};
Ok(Auth::Reject {
proceed_with_methods: proceed,
partial_success: false,
})
}
Err(e) => {
tracing::error!(
user = %user,
peer = ?peer_addr,
error = %e,
"Error during public key verification"
);
// Record failure for ban tracking
if let Some(ref limiter) = auth_rate_limiter {
if let Some(ip) = peer_addr.map(|a| a.ip()) {
limiter.record_failure(ip).await;
}
}
let proceed = if methods.is_empty() {
None
} else {
Some(methods)
};
Ok(Auth::Reject {
proceed_with_methods: proceed,
partial_success: false,
})
}
}
}
}
/// Handle password authentication.
///
/// Verifies the password against configured users using the auth provider.
/// Implements rate limiting and tracks failed authentication attempts.
fn auth_password(
&mut self,
user: &str,
password: &str,
) -> impl std::future::Future<Output = Result<Auth, Self::Error>> + Send {
tracing::debug!(
user = %user,
peer = ?self.peer_addr,
"Password authentication attempt"
);
// Increment auth attempts
if let Some(ref mut info) = self.session_info {
info.increment_auth_attempts();
}
// Check if max attempts exceeded
let exceeded = self.auth_attempts_exceeded();
let mut methods = self.allowed_methods();
methods.remove(MethodKind::Password);
// Clone what we need for the async block
let auth_provider = Arc::clone(&self.auth_provider);
let rate_limiter = self.rate_limiter.clone();
let auth_rate_limiter = self.auth_rate_limiter.clone();
let peer_addr = self.peer_addr;
let user = user.to_string();
// Use Zeroizing to ensure password is securely cleared from memory when dropped
let password = Zeroizing::new(password.to_string());
let allow_password = self.config.allow_password_auth;
// Get mutable reference to session_info for authentication update
let session_info = &mut self.session_info;
async move {
// Check if IP is banned (fail2ban-like check)
if let Some(ref limiter) = auth_rate_limiter {
if let Some(ip) = peer_addr.map(|a| a.ip()) {
if limiter.is_banned(&ip).await {
tracing::warn!(
user = %user,
peer = ?peer_addr,
"Rejected password auth from banned IP"
);
return Ok(Auth::Reject {
proceed_with_methods: None,
partial_success: false,
});
}
}
}
// Check if password auth is enabled
if !allow_password {
tracing::debug!(
user = %user,
"Password authentication disabled"
);
let proceed = if methods.is_empty() {
None
} else {
Some(methods)
};
return Ok(Auth::Reject {
proceed_with_methods: proceed,
partial_success: false,
});
}
if exceeded {
tracing::warn!(
user = %user,
peer = ?peer_addr,
"Max authentication attempts exceeded"
);
return Ok(Auth::Reject {
proceed_with_methods: None,
partial_success: false,
});
}
// Check rate limiting based on peer address
let rate_key = peer_addr
.map(|addr| addr.ip().to_string())
.unwrap_or_else(|| "unknown".to_string());
if rate_limiter.is_rate_limited(&rate_key).await {
tracing::warn!(
user = %user,
peer = ?peer_addr,
"Rate limited password authentication attempt"
);
return Ok(Auth::Reject {
proceed_with_methods: None,
partial_success: false,
});
}
// Try to acquire a rate limit token
if rate_limiter.try_acquire(&rate_key).await.is_err() {
tracing::warn!(
user = %user,
peer = ?peer_addr,
"Rate limit exceeded for password authentication"
);
return Ok(Auth::Reject {
proceed_with_methods: None,
partial_success: false,
});
}
// Verify password using auth provider
match auth_provider.verify_password(&user, &password).await {
Ok(result) if result.is_accepted() => {
tracing::info!(
user = %user,
peer = ?peer_addr,
"Password authentication successful"
);
// Mark session as authenticated
if let Some(ref mut info) = session_info {
info.authenticate(&user);
}
// Record success to reset failure counter
if let Some(ref limiter) = auth_rate_limiter {
if let Some(ip) = peer_addr.map(|a| a.ip()) {
limiter.record_success(&ip).await;
}
}
Ok(Auth::Accept)
}
Ok(_) => {
tracing::debug!(
user = %user,
peer = ?peer_addr,
"Password authentication rejected"
);
// Record failure for ban tracking
if let Some(ref limiter) = auth_rate_limiter {
if let Some(ip) = peer_addr.map(|a| a.ip()) {
let banned = limiter.record_failure(ip).await;
if banned {
tracing::warn!(
user = %user,
peer = ?peer_addr,
"IP banned due to too many failed password auth attempts"
);
}
}
}
let proceed = if methods.is_empty() {
None
} else {
Some(methods)
};
Ok(Auth::Reject {
proceed_with_methods: proceed,
partial_success: false,
})
}
Err(e) => {
tracing::error!(
user = %user,
peer = ?peer_addr,
error = %e,
"Error during password verification"
);
// Record failure for ban tracking
if let Some(ref limiter) = auth_rate_limiter {
if let Some(ip) = peer_addr.map(|a| a.ip()) {
limiter.record_failure(ip).await;
}
}
let proceed = if methods.is_empty() {
None
} else {
Some(methods)
};
Ok(Auth::Reject {
proceed_with_methods: proceed,
partial_success: false,
})
}
}
}
}
/// Handle PTY request.
///
/// Stores the PTY configuration for the channel.
#[allow(clippy::too_many_arguments)]
fn pty_request(
&mut self,
channel_id: ChannelId,
term: &str,
col_width: u32,
row_height: u32,
pix_width: u32,
pix_height: u32,
_modes: &[(Pty, u32)],
session: &mut Session,
) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send {
tracing::debug!(
term = %term,
cols = %col_width,
rows = %row_height,
"PTY request"
);
if let Some(channel_state) = self.channels.get_mut(&channel_id) {
let pty_config = PtyConfig::new(
term.to_string(),
col_width,
row_height,
pix_width,
pix_height,
);
channel_state.set_pty(pty_config);
let _ = session.channel_success(channel_id);
} else {
tracing::warn!("PTY request for unknown channel");
let _ = session.channel_failure(channel_id);
}
async { Ok(()) }
}
/// Handle exec request.
///
/// Executes the requested command and streams output back to the client.
/// The command is executed via the configured shell with proper environment
/// setup based on the authenticated user.
fn exec_request(
&mut self,
channel_id: ChannelId,
data: &[u8],
session: &mut Session,
) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send {
// Parse command from data
let command = match std::str::from_utf8(data) {
Ok(cmd) => cmd.to_string(),
Err(e) => {
tracing::warn!(
channel = ?channel_id,
error = %e,
"Invalid UTF-8 in exec command"
);
let _ = session.channel_failure(channel_id);
return async { Ok(()) }.boxed();
}
};
tracing::debug!(
channel = ?channel_id,
command = %command,
"Exec request received"
);
// Update channel state
if let Some(channel_state) = self.channels.get_mut(&channel_id) {
channel_state.set_exec(command.clone());
}
// Get authenticated user info
let username = match self.session_info.as_ref().and_then(|s| s.user.clone()) {
Some(user) => user,
None => {
tracing::warn!(
channel = ?channel_id,
"Exec request without authenticated user"
);
let _ = session.channel_failure(channel_id);
return async { Ok(()) }.boxed();
}
};
// Clone what we need for the async block
let auth_provider = Arc::clone(&self.auth_provider);
let exec_config = self.config.exec.clone();
let handle = session.handle();
let peer_addr = self.peer_addr;
// Signal channel success before executing
let _ = session.channel_success(channel_id);
async move {
// Get user info from auth provider
let user_info = match auth_provider.get_user_info(&username).await {
Ok(Some(info)) => info,
Ok(None) => {
tracing::error!(
user = %username,
"User not found after authentication"
);
let _ = handle.exit_status_request(channel_id, 1).await;
let _ = handle.eof(channel_id).await;
let _ = handle.close(channel_id).await;
return Ok(());
}
Err(e) => {
tracing::error!(
user = %username,
error = %e,
"Failed to get user info"
);
let _ = handle.exit_status_request(channel_id, 1).await;
let _ = handle.eof(channel_id).await;
let _ = handle.close(channel_id).await;
return Ok(());
}
};
tracing::info!(
user = %username,
peer = ?peer_addr,
command = %command,
"Executing command"
);
// Create executor and run command
let executor = CommandExecutor::new(exec_config);
let exit_code = match executor
.execute(&command, &user_info, channel_id, handle.clone())
.await
{
Ok(code) => code,
Err(e) => {
tracing::error!(
user = %username,
command = %command,
error = %e,
"Command execution failed"
);
1 // Default error exit code
}
};
tracing::debug!(
user = %username,
command = %command,
exit_code = %exit_code,
"Command completed"
);
// Send exit status, EOF, and close channel
let _ = handle
.exit_status_request(channel_id, exit_code as u32)
.await;
let _ = handle.eof(channel_id).await;
let _ = handle.close(channel_id).await;
Ok(())
}
.boxed()
}
/// Handle shell request.
///
/// Starts an interactive shell session for the authenticated user.
/// Uses Handle-based I/O for PTY output to avoid notify_waiters() race conditions.
/// The key insight is that Handle::data() uses notify_one() which stores a permit
/// if no task is waiting, while ChannelTx uses notify_waiters() which only wakes
/// tasks that are currently waiting. This causes intermittent failures with rapid
/// connections when using ChannelStream-based I/O.
fn shell_request(
&mut self,
channel_id: ChannelId,
session: &mut Session,
) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send {
tracing::debug!(channel = ?channel_id, "Shell request");
// Get authenticated user info
let username = match self.session_info.as_ref().and_then(|s| s.user.clone()) {
Some(user) => user,
None => {
tracing::warn!(
channel = ?channel_id,
"Shell request without authenticated user"
);
let _ = session.channel_failure(channel_id);
return async { Ok(()) }.boxed();
}
};
// Get PTY configuration
let pty_config = match self.channels.get_mut(&channel_id) {
Some(state) => {
let config = state
.pty
.as_ref()
.map(|pty| {
PtyMasterConfig::new(
pty.term.clone(),
pty.col_width,
pty.row_height,
pty.pix_width,
pty.pix_height,
)
})
.unwrap_or_default();
state.set_shell();
config
}
None => {
tracing::warn!(
channel = ?channel_id,
"Shell request but channel state not found"
);
let _ = session.channel_failure(channel_id);
return async { Ok(()) }.boxed();
}
};
// Create shell session (sync) to get the PTY
let shell_session = match ShellSession::new(channel_id, pty_config.clone()) {
Ok(session) => session,
Err(e) => {
tracing::error!(
channel = ?channel_id,
error = %e,
"Failed to create shell session"
);
let _ = session.channel_failure(channel_id);
return async { Ok(()) }.boxed();
}
};
// Get PTY reference for window_change_request
let pty = Arc::clone(shell_session.pty());
// Create channel for SSH -> PTY data (client input)
let (data_tx, data_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(1024);
// Store handles in channel state for window_change callbacks and data forwarding
if let Some(state) = self.channels.get_mut(&channel_id) {
state.set_shell_handles(data_tx, Arc::clone(&pty));
}
// Clone what we need for the async block
let auth_provider = Arc::clone(&self.auth_provider);
let peer_addr = self.peer_addr;
let handle = session.handle();
// Signal success before starting shell
let _ = session.channel_success(channel_id);
async move {
// Get user info from auth provider
let user_info = match auth_provider.get_user_info(&username).await {
Ok(Some(info)) => info,
Ok(None) => {
tracing::error!(
user = %username,
"User not found after authentication for shell"
);
return Ok(());
}
Err(e) => {
tracing::error!(
user = %username,
error = %e,
"Failed to get user info for shell"
);
return Ok(());
}
};
tracing::info!(
user = %username,
peer = ?peer_addr,
term = %pty_config.term,
size = %format!("{}x{}", pty_config.col_width, pty_config.row_height),
"Starting shell session"
);
// Spawn shell process (async part)
let mut shell_session = shell_session;
if let Err(e) = shell_session.spawn_shell_process(&user_info).await {
tracing::error!(
user = %username,
error = %e,
"Failed to spawn shell process"
);
return Ok(());
}
// Get child process for the I/O loop
let child = shell_session.take_child();
tracing::debug!(
channel = ?channel_id,
"Spawning shell I/O task with Handle-based approach"
);
// IMPORTANT: Spawn the I/O loop instead of awaiting it!
// The session loop needs to keep running to flush Handle::data() messages
// to the network. If we await here, the session loop is blocked.
tokio::spawn(async move {
let exit_code = crate::server::shell::run_shell_io_loop_with_handle(
channel_id,
pty,
child,
handle.clone(),
data_rx,
)
.await;
tracing::info!(
channel = ?channel_id,
exit_code = exit_code,
"Shell session completed"
);