-
Notifications
You must be signed in to change notification settings - Fork 643
Expand file tree
/
Copy pathssh.rs
More file actions
1563 lines (1407 loc) · 51.7 KB
/
ssh.rs
File metadata and controls
1563 lines (1407 loc) · 51.7 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
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! Embedded SSH server for sandbox access.
use crate::child_env;
use crate::policy::SandboxPolicy;
use crate::process::drop_privileges;
use crate::sandbox;
#[cfg(target_os = "linux")]
use crate::{register_managed_child, unregister_managed_child};
use miette::{IntoDiagnostic, Result};
use nix::pty::{Winsize, openpty};
use nix::unistd::setsid;
use rand_core::OsRng;
use russh::keys::{Algorithm, PrivateKey};
use russh::server::{Auth, Handle, Session};
use russh::{ChannelId, CryptoVec};
use std::collections::HashMap;
use std::io::{Read, Write};
use std::net::SocketAddr;
use std::os::fd::{AsRawFd, RawFd};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
use tracing::{info, warn};
const PREFACE_MAGIC: &str = "NSSH1";
#[cfg(test)]
const SSH_HANDSHAKE_SECRET_ENV: &str = "OPENSHELL_SSH_HANDSHAKE_SECRET";
/// A time-bounded set of nonces used to detect replayed NSSH1 handshakes.
/// Each entry records the `Instant` it was inserted; a background reaper task
/// periodically evicts entries older than the handshake skew window.
type NonceCache = Arc<Mutex<HashMap<String, Instant>>>;
/// Perform SSH server initialization: generate a host key, build the config,
/// and bind the TCP listener. Extracted so that startup errors can be forwarded
/// through the readiness channel rather than being silently logged.
async fn ssh_server_init(
listen_addr: SocketAddr,
ca_file_paths: &Option<(PathBuf, PathBuf)>,
) -> Result<(
TcpListener,
Arc<russh::server::Config>,
Option<Arc<(PathBuf, PathBuf)>>,
)> {
let mut rng = OsRng;
let host_key = PrivateKey::random(&mut rng, Algorithm::Ed25519).into_diagnostic()?;
let mut config = russh::server::Config {
auth_rejection_time: Duration::from_secs(1),
..Default::default()
};
config.keys.push(host_key);
let config = Arc::new(config);
let ca_paths = ca_file_paths.as_ref().map(|p| Arc::new(p.clone()));
let listener = TcpListener::bind(listen_addr).await.into_diagnostic()?;
info!(addr = %listen_addr, "SSH server listening");
Ok((listener, config, ca_paths))
}
#[allow(clippy::too_many_arguments)]
pub async fn run_ssh_server(
listen_addr: SocketAddr,
ready_tx: tokio::sync::oneshot::Sender<Result<()>>,
policy: SandboxPolicy,
workdir: Option<String>,
handshake_secret: String,
handshake_skew_secs: u64,
netns_fd: Option<RawFd>,
proxy_url: Option<String>,
ca_file_paths: Option<(PathBuf, PathBuf)>,
provider_env: HashMap<String, String>,
) -> Result<()> {
let (listener, config, ca_paths) = match ssh_server_init(listen_addr, &ca_file_paths).await {
Ok(v) => {
// Signal that the SSH server has bound the socket and is ready to
// accept connections. The parent task awaits this before spawning
// the entrypoint process, ensuring exec requests won't race
// against server startup.
let _ = ready_tx.send(Ok(()));
v
}
Err(err) => {
let _ = ready_tx.send(Err(err));
return Ok(());
}
};
// Nonce cache for replay detection. Entries are evicted by a background
// reaper once they exceed the handshake skew window.
let nonce_cache: NonceCache = Arc::new(Mutex::new(HashMap::new()));
// Background task that periodically purges expired nonces.
let reaper_cache = nonce_cache.clone();
let ttl = Duration::from_secs(handshake_skew_secs);
tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(60));
loop {
interval.tick().await;
if let Ok(mut cache) = reaper_cache.lock() {
cache.retain(|_, inserted| inserted.elapsed() < ttl);
}
}
});
loop {
let (stream, peer) = listener.accept().await.into_diagnostic()?;
stream.set_nodelay(true).into_diagnostic()?;
let config = config.clone();
let policy = policy.clone();
let workdir = workdir.clone();
let secret = handshake_secret.clone();
let proxy_url = proxy_url.clone();
let ca_paths = ca_paths.clone();
let provider_env = provider_env.clone();
let nonce_cache = nonce_cache.clone();
tokio::spawn(async move {
if let Err(err) = handle_connection(
stream,
peer,
config,
policy,
workdir,
&secret,
handshake_skew_secs,
netns_fd,
proxy_url,
ca_paths,
provider_env,
&nonce_cache,
)
.await
{
warn!(error = %err, "SSH connection failed");
}
});
}
}
#[allow(clippy::too_many_arguments)]
async fn handle_connection(
mut stream: tokio::net::TcpStream,
peer: SocketAddr,
config: Arc<russh::server::Config>,
policy: SandboxPolicy,
workdir: Option<String>,
secret: &str,
handshake_skew_secs: u64,
netns_fd: Option<RawFd>,
proxy_url: Option<String>,
ca_file_paths: Option<Arc<(PathBuf, PathBuf)>>,
provider_env: HashMap<String, String>,
nonce_cache: &NonceCache,
) -> Result<()> {
info!(peer = %peer, "SSH connection: reading handshake preface");
let mut line = String::new();
read_line(&mut stream, &mut line).await?;
info!(peer = %peer, preface_len = line.len(), "SSH connection: preface received, verifying");
if !verify_preface(&line, secret, handshake_skew_secs, nonce_cache)? {
warn!(peer = %peer, "SSH connection: handshake verification failed");
let _ = stream.write_all(b"ERR\n").await;
return Ok(());
}
stream.write_all(b"OK\n").await.into_diagnostic()?;
info!(peer = %peer, "SSH handshake accepted");
let handler = SshHandler::new(
policy,
workdir,
netns_fd,
proxy_url,
ca_file_paths,
provider_env,
);
russh::server::run_stream(config, stream, handler)
.await
.map_err(|err| miette::miette!("ssh stream error: {err}"))?;
Ok(())
}
async fn read_line(stream: &mut tokio::net::TcpStream, buf: &mut String) -> Result<()> {
let mut bytes = Vec::new();
loop {
let mut byte = [0u8; 1];
let n = stream.read(&mut byte).await.into_diagnostic()?;
if n == 0 {
break;
}
if byte[0] == b'\n' {
break;
}
bytes.push(byte[0]);
if bytes.len() > 1024 {
break;
}
}
*buf = String::from_utf8_lossy(&bytes).to_string();
Ok(())
}
fn verify_preface(
line: &str,
secret: &str,
handshake_skew_secs: u64,
nonce_cache: &NonceCache,
) -> Result<bool> {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() != 5 || parts[0] != PREFACE_MAGIC {
return Ok(false);
}
let token = parts[1];
let timestamp: i64 = parts[2].parse().unwrap_or(0);
let nonce = parts[3];
let signature = parts[4];
let now = i64::try_from(
SystemTime::now()
.duration_since(UNIX_EPOCH)
.into_diagnostic()?
.as_secs(),
)
.into_diagnostic()?;
let skew = (now - timestamp).unsigned_abs();
if skew > handshake_skew_secs {
return Ok(false);
}
let payload = format!("{token}|{timestamp}|{nonce}");
let expected = hmac_sha256(secret.as_bytes(), payload.as_bytes());
if signature != expected {
return Ok(false);
}
// Reject replayed nonces. The cache is bounded by the reaper task which
// evicts entries older than `handshake_skew_secs`.
let mut cache = nonce_cache
.lock()
.map_err(|_| miette::miette!("nonce cache lock poisoned"))?;
if cache.contains_key(nonce) {
warn!(nonce = nonce, "NSSH1 nonce replay detected");
return Ok(false);
}
cache.insert(nonce.to_string(), Instant::now());
Ok(true)
}
fn hmac_sha256(key: &[u8], data: &[u8]) -> String {
use hmac::{Hmac, Mac};
use sha2::Sha256;
let mut mac = Hmac::<Sha256>::new_from_slice(key).expect("hmac key");
mac.update(data);
let result = mac.finalize().into_bytes();
hex::encode(result)
}
/// Per-channel state for tracking PTY resources and I/O senders.
///
/// Each SSH channel gets its own PTY master (if a PTY was requested) and input
/// sender. This allows `window_change_request` to resize the correct PTY when
/// multiple channels are open simultaneously (e.g. parallel shells, shell +
/// sftp, etc.).
#[derive(Default)]
struct ChannelState {
input_sender: Option<mpsc::Sender<Vec<u8>>>,
pty_master: Option<std::fs::File>,
pty_request: Option<PtyRequest>,
}
struct SshHandler {
policy: SandboxPolicy,
workdir: Option<String>,
netns_fd: Option<RawFd>,
proxy_url: Option<String>,
ca_file_paths: Option<Arc<(PathBuf, PathBuf)>>,
provider_env: HashMap<String, String>,
channels: HashMap<ChannelId, ChannelState>,
}
impl SshHandler {
fn new(
policy: SandboxPolicy,
workdir: Option<String>,
netns_fd: Option<RawFd>,
proxy_url: Option<String>,
ca_file_paths: Option<Arc<(PathBuf, PathBuf)>>,
provider_env: HashMap<String, String>,
) -> Self {
Self {
policy,
workdir,
netns_fd,
proxy_url,
ca_file_paths,
provider_env,
channels: HashMap::new(),
}
}
}
impl russh::server::Handler for SshHandler {
type Error = anyhow::Error;
async fn auth_none(&mut self, _user: &str) -> Result<Auth, Self::Error> {
Ok(Auth::Accept)
}
async fn auth_publickey(
&mut self,
_user: &str,
_public_key: &russh::keys::PublicKey,
) -> Result<Auth, Self::Error> {
Ok(Auth::Accept)
}
async fn channel_open_session(
&mut self,
channel: russh::Channel<russh::server::Msg>,
_session: &mut Session,
) -> Result<bool, Self::Error> {
self.channels.insert(channel.id(), ChannelState::default());
Ok(true)
}
/// Clean up per-channel state when the channel is closed.
///
/// This is the final cleanup and subsumes `channel_eof` — if `channel_close`
/// fires without a preceding `channel_eof`, all resources (pty_master File,
/// input_sender) are dropped here.
async fn channel_close(
&mut self,
channel: ChannelId,
_session: &mut Session,
) -> Result<(), Self::Error> {
self.channels.remove(&channel);
Ok(())
}
async fn channel_open_direct_tcpip(
&mut self,
channel: russh::Channel<russh::server::Msg>,
host_to_connect: &str,
port_to_connect: u32,
_originator_address: &str,
_originator_port: u32,
_session: &mut Session,
) -> Result<bool, Self::Error> {
// Validate port range before truncating u32 -> u16. The SSH protocol
// uses u32 for ports, but valid TCP ports are 0-65535. Without this
// check, port 65537 truncates to port 1 (privileged).
if port_to_connect > u32::from(u16::MAX) {
warn!(
host = host_to_connect,
port = port_to_connect,
"direct-tcpip rejected: port exceeds valid TCP range (0-65535)"
);
return Ok(false);
}
// Only allow forwarding to loopback destinations to prevent the
// sandbox SSH server from being used as a generic proxy.
if !is_loopback_host(host_to_connect) {
warn!(
host = host_to_connect,
port = port_to_connect,
"direct-tcpip rejected: non-loopback destination"
);
return Ok(false);
}
let host = host_to_connect.to_string();
let port = port_to_connect as u16;
let netns_fd = self.netns_fd;
tokio::spawn(async move {
let addr = format!("{host}:{port}");
let tcp = match connect_in_netns(&addr, netns_fd).await {
Ok(stream) => stream,
Err(err) => {
warn!(addr = %addr, error = %err, "direct-tcpip: failed to connect");
let _ = channel.close().await;
return;
}
};
let mut channel_stream = channel.into_stream();
let mut tcp_stream = tcp;
let _ = tokio::io::copy_bidirectional(&mut channel_stream, &mut tcp_stream).await;
});
Ok(true)
}
async fn pty_request(
&mut self,
channel: ChannelId,
term: &str,
col_width: u32,
row_height: u32,
_pix_width: u32,
_pix_height: u32,
_modes: &[(russh::Pty, u32)],
session: &mut Session,
) -> Result<(), Self::Error> {
let state = self
.channels
.get_mut(&channel)
.ok_or_else(|| anyhow::anyhow!("pty_request on unknown channel {channel:?}"))?;
state.pty_request = Some(PtyRequest {
term: term.to_string(),
col_width,
row_height,
pixel_width: 0,
pixel_height: 0,
});
session.channel_success(channel)?;
Ok(())
}
async fn window_change_request(
&mut self,
channel: ChannelId,
col_width: u32,
row_height: u32,
pixel_width: u32,
pixel_height: u32,
_session: &mut Session,
) -> Result<(), Self::Error> {
let Some(state) = self.channels.get(&channel) else {
warn!("window_change_request on unknown channel {channel:?}");
return Ok(());
};
if let Some(master) = state.pty_master.as_ref() {
let winsize = Winsize {
ws_row: to_u16(row_height.max(1)),
ws_col: to_u16(col_width.max(1)),
ws_xpixel: to_u16(pixel_width),
ws_ypixel: to_u16(pixel_height),
};
if let Err(e) = unsafe_pty::set_winsize(master.as_raw_fd(), winsize) {
warn!("failed to resize PTY for channel {channel:?}: {e}");
}
}
Ok(())
}
async fn shell_request(
&mut self,
channel: ChannelId,
session: &mut Session,
) -> Result<(), Self::Error> {
session.channel_success(channel)?;
// Only allocate a PTY when the client explicitly requested one via
// pty_request. VS Code Remote-SSH sends shell_request *without* a
// preceding pty_request and expects pipe-based I/O with clean LF line
// endings. Forcing a PTY here caused CRLF translation which made
// VS Code misdetect the platform as Windows (and then try to run
// `powershell`).
self.start_shell(channel, session.handle(), None)?;
Ok(())
}
async fn exec_request(
&mut self,
channel: ChannelId,
data: &[u8],
session: &mut Session,
) -> Result<(), Self::Error> {
session.channel_success(channel)?;
let command = String::from_utf8_lossy(data).trim().to_string();
if command.is_empty() {
return Ok(());
}
self.start_shell(channel, session.handle(), Some(command))?;
Ok(())
}
async fn subsystem_request(
&mut self,
channel: ChannelId,
name: &str,
session: &mut Session,
) -> Result<(), Self::Error> {
if name == "sftp" {
session.channel_success(channel)?;
// sftp-server speaks the SFTP binary protocol over stdin/stdout,
// which is exactly what spawn_pipe_exec wires up. This enables
// modern scp (SFTP-based, OpenSSH 9.0+) and SFTP clients to
// transfer files into and out of the sandbox.
let input_sender = spawn_pipe_exec(
&self.policy,
self.workdir.clone(),
Some("/usr/lib/openssh/sftp-server".to_string()),
session.handle(),
channel,
self.netns_fd,
self.proxy_url.clone(),
self.ca_file_paths.clone(),
&self.provider_env,
)?;
let state = self.channels.get_mut(&channel).ok_or_else(|| {
anyhow::anyhow!("subsystem_request on unknown channel {channel:?}")
})?;
state.input_sender = Some(input_sender);
} else {
warn!(subsystem = name, "unsupported subsystem requested");
session.channel_failure(channel)?;
}
Ok(())
}
async fn env_request(
&mut self,
channel: ChannelId,
variable_name: &str,
variable_value: &str,
session: &mut Session,
) -> Result<(), Self::Error> {
// Accept the env request so the client knows we handled it, but we
// don't actually propagate the variables — the sandbox environment is
// controlled via policy. We must reply so VSCode doesn't stall.
let _ = (variable_name, variable_value);
session.channel_success(channel)?;
Ok(())
}
async fn data(
&mut self,
channel: ChannelId,
data: &[u8],
_session: &mut Session,
) -> Result<(), Self::Error> {
let Some(state) = self.channels.get(&channel) else {
warn!("data on unknown channel {channel:?}");
return Ok(());
};
if let Some(sender) = state.input_sender.as_ref() {
let _ = sender.send(data.to_vec());
}
Ok(())
}
async fn channel_eof(
&mut self,
channel: ChannelId,
_session: &mut Session,
) -> Result<(), Self::Error> {
// Drop the input sender so the stdin writer thread sees a
// disconnected channel and closes the child's stdin pipe. This
// is essential for commands like `cat | tar xf -` which need
// stdin EOF to know the input stream is complete.
if let Some(state) = self.channels.get_mut(&channel) {
state.input_sender.take();
} else {
warn!("channel_eof on unknown channel {channel:?}");
}
Ok(())
}
}
impl SshHandler {
fn start_shell(
&mut self,
channel: ChannelId,
handle: Handle,
command: Option<String>,
) -> anyhow::Result<()> {
let state = self
.channels
.get_mut(&channel)
.ok_or_else(|| anyhow::anyhow!("start_shell on unknown channel {channel:?}"))?;
if let Some(pty) = state.pty_request.take() {
// PTY was requested — allocate a real PTY (interactive shell or
// exec that explicitly asked for a terminal).
let (pty_master, input_sender) = spawn_pty_shell(
&self.policy,
self.workdir.clone(),
command,
&pty,
handle,
channel,
self.netns_fd,
self.proxy_url.clone(),
self.ca_file_paths.clone(),
&self.provider_env,
)?;
state.pty_master = Some(pty_master);
state.input_sender = Some(input_sender);
} else {
// No PTY requested — use plain pipes so stdout/stderr are
// separate and output has clean LF line endings. This is the
// path VSCode Remote-SSH exec commands take.
let input_sender = spawn_pipe_exec(
&self.policy,
self.workdir.clone(),
command,
handle,
channel,
self.netns_fd,
self.proxy_url.clone(),
self.ca_file_paths.clone(),
&self.provider_env,
)?;
state.input_sender = Some(input_sender);
}
Ok(())
}
}
/// Connect a TCP stream to `addr` inside the sandbox network namespace.
///
/// The SSH supervisor runs in the host network namespace while sandbox child
/// processes run in an isolated network namespace (with their own loopback).
/// A plain `TcpStream::connect("127.0.0.1:port")` from the supervisor would
/// hit the host loopback, not the sandbox loopback where services are listening.
///
/// On Linux, we spawn a dedicated OS thread, call `setns` to enter the sandbox
/// namespace, create the socket there, then convert it to a tokio `TcpStream`.
/// We use `std::thread::spawn` (not `spawn_blocking`) because `setns` changes
/// the calling thread's network namespace permanently — a tokio blocking-pool
/// thread could be reused for unrelated tasks and must not be contaminated.
/// On non-Linux platforms (no network namespace support), we connect directly.
async fn connect_in_netns(
addr: &str,
netns_fd: Option<RawFd>,
) -> std::io::Result<tokio::net::TcpStream> {
#[cfg(target_os = "linux")]
if let Some(fd) = netns_fd {
let addr = addr.to_string();
let (tx, rx) = tokio::sync::oneshot::channel();
std::thread::spawn(move || {
let result = (|| -> std::io::Result<std::net::TcpStream> {
// Enter the sandbox network namespace on this dedicated thread.
// SAFETY: setns is safe to call; this is a dedicated thread that
// will exit after the connection is established.
#[allow(unsafe_code)]
let rc = unsafe { libc::setns(fd, libc::CLONE_NEWNET) };
if rc != 0 {
return Err(std::io::Error::last_os_error());
}
std::net::TcpStream::connect(&addr)
})();
let _ = tx.send(result);
});
let std_stream = rx
.await
.map_err(|_| std::io::Error::other("netns connect thread panicked"))??;
std_stream.set_nonblocking(true)?;
return tokio::net::TcpStream::from_std(std_stream);
}
#[cfg(not(target_os = "linux"))]
let _ = netns_fd;
tokio::net::TcpStream::connect(addr).await
}
#[derive(Clone)]
struct PtyRequest {
term: String,
col_width: u32,
row_height: u32,
pixel_width: u32,
pixel_height: u32,
}
impl Default for PtyRequest {
fn default() -> Self {
Self {
term: "xterm-256color".to_string(),
col_width: 80,
row_height: 24,
pixel_width: 0,
pixel_height: 0,
}
}
}
/// Derive the session USER and HOME from the policy's `run_as_user`.
///
/// Falls back to `("sandbox", "/sandbox")` when the policy has no explicit user,
/// preserving backward compatibility with images that use the default layout.
fn session_user_and_home(policy: &SandboxPolicy) -> (String, String) {
match policy.process.run_as_user.as_deref() {
Some(user) if !user.is_empty() => {
// Look up the user's home directory from /etc/passwd.
let home = nix::unistd::User::from_name(user)
.ok()
.flatten()
.map(|u| u.dir.to_string_lossy().into_owned())
.unwrap_or_else(|| format!("/home/{user}"));
(user.to_string(), home)
}
_ => ("sandbox".to_string(), "/sandbox".to_string()),
}
}
fn apply_child_env(
cmd: &mut Command,
session_home: &str,
session_user: &str,
term: &str,
proxy_url: Option<&str>,
ca_file_paths: Option<&(PathBuf, PathBuf)>,
provider_env: &HashMap<String, String>,
) {
let path = std::env::var("PATH").unwrap_or_else(|_| "/usr/local/bin:/usr/bin:/bin".into());
cmd.env_clear()
.env("OPENSHELL_SANDBOX", "1")
.env("HOME", session_home)
.env("USER", session_user)
.env("SHELL", "/bin/bash")
.env("PATH", &path)
.env("TERM", term);
if let Some(url) = proxy_url {
for (key, value) in child_env::proxy_env_vars(url) {
cmd.env(key, value);
}
}
if let Some((ca_cert_path, combined_bundle_path)) = ca_file_paths {
for (key, value) in child_env::tls_env_vars(ca_cert_path, combined_bundle_path) {
cmd.env(key, value);
}
}
for (key, value) in provider_env {
cmd.env(key, value);
}
}
#[allow(clippy::too_many_arguments)]
fn spawn_pty_shell(
policy: &SandboxPolicy,
workdir: Option<String>,
command: Option<String>,
pty: &PtyRequest,
handle: Handle,
channel: ChannelId,
netns_fd: Option<RawFd>,
proxy_url: Option<String>,
ca_file_paths: Option<Arc<(PathBuf, PathBuf)>>,
provider_env: &HashMap<String, String>,
) -> anyhow::Result<(std::fs::File, mpsc::Sender<Vec<u8>>)> {
let winsize = Winsize {
ws_row: to_u16(pty.row_height.max(1)),
ws_col: to_u16(pty.col_width.max(1)),
ws_xpixel: to_u16(pty.pixel_width),
ws_ypixel: to_u16(pty.pixel_height),
};
let openpty = openpty(Some(&winsize), None)?;
let master = std::fs::File::from(openpty.master);
let slave = std::fs::File::from(openpty.slave);
let slave_fd = slave.as_raw_fd();
let stdin = slave.try_clone()?;
let stdout = slave.try_clone()?;
let stderr = slave;
let mut reader = master.try_clone()?;
let mut writer = master.try_clone()?;
let mut cmd = command.map_or_else(
|| {
let mut c = Command::new("/bin/bash");
c.arg("-i");
c
},
|command| {
let mut c = Command::new("/bin/bash");
c.arg("-lc").arg(command);
c
},
);
let term = if pty.term.is_empty() {
"xterm-256color"
} else {
pty.term.as_str()
};
// Derive USER and HOME from the policy's run_as_user when available,
// falling back to "sandbox" / "/sandbox" for backward compatibility.
let (session_user, session_home) = session_user_and_home(policy);
apply_child_env(
&mut cmd,
&session_home,
&session_user,
term,
proxy_url.as_deref(),
ca_file_paths.as_deref(),
provider_env,
);
cmd.stdin(stdin).stdout(stdout).stderr(stderr);
if let Some(dir) = workdir.as_deref() {
cmd.current_dir(dir);
}
#[cfg(unix)]
{
unsafe_pty::install_pre_exec(
&mut cmd,
policy.clone(),
workdir.clone(),
slave_fd,
netns_fd,
);
}
let mut child = cmd.spawn()?;
#[cfg(target_os = "linux")]
let child_pid = child.id();
#[cfg(target_os = "linux")]
register_managed_child(child_pid);
let master_file = master;
let (sender, receiver) = mpsc::channel::<Vec<u8>>();
std::thread::spawn(move || {
while let Ok(bytes) = receiver.recv() {
if writer.write_all(&bytes).is_err() {
break;
}
let _ = writer.flush();
}
});
let runtime = tokio::runtime::Handle::current();
let runtime_reader = runtime.clone();
let handle_clone = handle.clone();
// Signal from the reader thread to the exit thread that all output has
// been forwarded. The exit thread waits for this before sending the
// exit-status and closing the channel, ensuring the correct SSH protocol
// ordering: data → EOF → exit-status → close.
let (reader_done_tx, reader_done_rx) = mpsc::channel::<()>();
std::thread::spawn(move || {
let mut buf = [0u8; 4096];
loop {
match reader.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
let data = CryptoVec::from_slice(&buf[..n]);
let handle_clone = handle_clone.clone();
let _ = runtime_reader
.block_on(async move { handle_clone.data(channel, data).await });
}
}
}
// Send EOF to indicate no more data will be sent on this channel.
let eof_handle = handle_clone.clone();
let _ = runtime_reader.block_on(async move { eof_handle.eof(channel).await });
// Notify the exit thread that all output has been forwarded.
let _ = reader_done_tx.send(());
});
let handle_exit = handle;
let runtime_exit = runtime;
std::thread::spawn(move || {
let status = child.wait().ok();
#[cfg(target_os = "linux")]
unregister_managed_child(child_pid);
let code = status.and_then(|s| s.code()).unwrap_or(1).unsigned_abs();
// Wait for the reader thread to finish forwarding all output before
// sending exit-status and closing the channel. This prevents the
// race where close() was called before exit_status_request().
//
// Use a timeout because a backgrounded grandchild process (e.g.
// `nohup daemon &`) may hold the PTY slave open indefinitely,
// preventing the reader from reaching EOF. Two seconds is enough
// for any remaining buffered data to drain.
let _ = reader_done_rx.recv_timeout(Duration::from_secs(2));
drop(runtime_exit.spawn(async move {
let _ = handle_exit.exit_status_request(channel, code).await;
let _ = handle_exit.close(channel).await;
}));
});
Ok((master_file, sender))
}
/// Spawn a command using plain pipes (no PTY).
///
/// stdout is forwarded as SSH channel data and stderr as SSH extended data
/// (type 1), preserving the separation that clients like `VSCode` Remote-SSH
/// expect. Output retains clean LF line endings (no CRLF translation).
#[allow(clippy::too_many_arguments)]
fn spawn_pipe_exec(
policy: &SandboxPolicy,
workdir: Option<String>,
command: Option<String>,
handle: Handle,
channel: ChannelId,
netns_fd: Option<RawFd>,
proxy_url: Option<String>,
ca_file_paths: Option<Arc<(PathBuf, PathBuf)>>,
provider_env: &HashMap<String, String>,
) -> anyhow::Result<mpsc::Sender<Vec<u8>>> {
let mut cmd = command.map_or_else(
|| {
// No command — read from stdin. Do *not* pass `-i`; interactive
// mode reads .bashrc, writes prompts to stderr, and can introduce
// just enough latency for VS Code Remote-SSH's platform detection
// to time out and fall back to "windows". Plain `bash` with piped
// stdin already reads commands line-by-line (script mode), which is
// exactly what VS Code's local server expects.
Command::new("/bin/bash")
},
|command| {
let mut c = Command::new("/bin/bash");
// Use login shell (-l) so that .profile/.bashrc are sourced and
// tool-specific env vars (VIRTUAL_ENV, UV_PYTHON_INSTALL_DIR, etc.)
// are available without hardcoding them here.
c.arg("-lc").arg(command);
c
},
);
let (session_user, session_home) = session_user_and_home(policy);
apply_child_env(
&mut cmd,
&session_home,
&session_user,
"dumb",
proxy_url.as_deref(),
ca_file_paths.as_deref(),
provider_env,
);
cmd.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
if let Some(dir) = workdir.as_deref() {
cmd.current_dir(dir);
}
#[cfg(unix)]
{
unsafe_pty::install_pre_exec_no_pty(&mut cmd, policy.clone(), workdir.clone(), netns_fd);
}
let mut child = cmd.spawn()?;
#[cfg(target_os = "linux")]
let child_pid = child.id();
#[cfg(target_os = "linux")]
register_managed_child(child_pid);
let child_stdin = child.stdin.take();
let child_stdout = child.stdout.take().expect("stdout must be piped");
let child_stderr = child.stderr.take().expect("stderr must be piped");
// stdin writer thread
let (sender, receiver) = mpsc::channel::<Vec<u8>>();
std::thread::spawn(move || {
let Some(mut stdin) = child_stdin else {
return;
};
while let Ok(bytes) = receiver.recv() {
if stdin.write_all(&bytes).is_err() {
break;
}
let _ = stdin.flush();
}
});
let runtime = tokio::runtime::Handle::current();
// Signal from the reader threads to the exit thread that all output has
// been forwarded.
let (reader_done_tx, reader_done_rx) = mpsc::channel::<()>();
// stdout reader
let stdout_handle = handle.clone();
let stdout_runtime = runtime.clone();
let reader_done_stdout = reader_done_tx.clone();
std::thread::spawn(move || {
let mut reader = child_stdout;
let mut buf = [0u8; 4096];
loop {
match reader.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
let data = CryptoVec::from_slice(&buf[..n]);
let h = stdout_handle.clone();
let _ = stdout_runtime.block_on(async move { h.data(channel, data).await });
}
}
}
let _ = reader_done_stdout.send(());