Repository navigation
Expand file tree
/
Copy pathsftp.rs
More file actions
1354 lines (1228 loc) · 52.9 KB
/
Copy pathsftp.rs
File metadata and controls
1354 lines (1228 loc) · 52.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
//! SFTP subsystem handler.
//!
//! One [`SftpSession`] is constructed per `sftp` subsystem request and handed
//! to [`russh_sftp::server::run`], which owns the dispatch loop. The handler
//! holds owned per-channel state — no inner actor — because dispatch through
//! `run` is already serialised.
//!
//! The client sees the two directories a session and the daemon share, under
//! the names the sandbox gives them: the session's working tree at
//! [`env::WORKSPACE_ROOT`] and its home at [`env::HOME_ROOT`], side by side
//! below a synthetic root that holds nothing else. Relative paths resolve
//! against the home directory, which is also what `realpath(".")` reports:
//! that is what the sandbox sets `$HOME` to, and where SFTP and SCP put a
//! client that never spells a path out in full.
//!
//! Every client-supplied path is funnelled through [`SftpSession::resolve`],
//! which normalizes it in that namespace, maps it onto the daemon-side
//! directory it names, and rejects anything landing outside the two — whether
//! spelled with `..` or reached through a symlink.
use std::collections::HashMap;
use std::io::SeekFrom;
use boxes::SessionId;
use camino::{Utf8Path, Utf8PathBuf};
use paths::{DaemonAbsPath, DaemonRelPath};
use russh::ChannelId;
use russh::server::Session;
use russh_sftp::protocol::{
Attrs, Data, File, FileAttributes, Handle, Name, OpenFlags, Status, StatusCode,
};
use russh_sftp::server::StatusReply;
use tokio::fs::{self, OpenOptions};
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
// Every task this module spawns carries the caller's span (TEL-022): the
// clippy `disallowed-methods` for the crate names tokio's own spawn.
use crate::traced::spawn;
use crate::box_manager::BoxKeyPredicate;
use crate::connection::{ConnectionError, ConnectionHandle};
use crate::server::ServerStateHandle;
use crate::{MINIMAL_SESSION_ID_ENV, env};
/// The SSH subsystem name used to negotiate an SFTP channel.
pub const SUBSYSTEM_NAME: &str = "sftp";
/// Cap on how many directory entries are returned per `readdir` call.
/// SFTP clients call `readdir` repeatedly until they see `SSH_FX_EOF`, so
/// batching keeps individual packets within typical SFTP size limits.
const READDIR_BATCH: usize = 100;
const MAX_READ_LEN: usize = 128 * 1024;
/// Error returned by SFTP handler methods.
///
/// `russh_sftp` requires `Into<StatusReply>`: every failed request maps to a
/// single `SSH_FXP_STATUS` packet, so we lose any structured detail at the
/// wire boundary regardless. The enum exists so the handler can report the
/// *cause* in logs even though the wire only carries a status code.
///
/// `StatusReply` can also carry a human-readable message, which we
/// deliberately leave unset: `russh_sftp` then falls back to the status
/// code's own text, and an `Io` variant's message can embed host paths that
/// have no business crossing the export boundary.
#[derive(Debug)]
pub enum SftpError {
Io(std::io::Error),
/// Client-supplied path resolved outside the exported directories, or
/// named the synthetic root in a request that can only act on a real file.
PathTraversal,
/// Client referenced a handle id this session does not know about.
UnknownHandle,
/// Client referenced a handle of the wrong kind (e.g. `read` on a dir).
WrongHandleType,
/// End of file or end of directory listing.
Eof,
/// SFTP packet recognised but not implemented.
Unsupported,
/// A mutating request on a read-only session: the box is stopped or
/// exited, and its retained files are served for retrieval only.
ReadOnly,
}
impl From<std::io::Error> for SftpError {
fn from(e: std::io::Error) -> Self {
Self::Io(e)
}
}
impl From<SftpError> for StatusCode {
fn from(e: SftpError) -> StatusCode {
use std::io::ErrorKind;
match e {
SftpError::Io(io) => match io.kind() {
ErrorKind::NotFound => StatusCode::NoSuchFile,
ErrorKind::PermissionDenied => StatusCode::PermissionDenied,
ErrorKind::UnexpectedEof => StatusCode::Eof,
_ => StatusCode::Failure,
},
SftpError::PathTraversal | SftpError::ReadOnly => StatusCode::PermissionDenied,
SftpError::UnknownHandle | SftpError::WrongHandleType => StatusCode::Failure,
SftpError::Eof => StatusCode::Eof,
SftpError::Unsupported => StatusCode::OpUnsupported,
}
}
}
impl From<SftpError> for StatusReply {
fn from(e: SftpError) -> StatusReply {
StatusReply::new(e.into())
}
}
/// An SFTP handle id refers to either an open file or a snapshot of a
/// directory listing. Using an enum (rather than two parallel maps) keeps
/// "handle id of the wrong kind" representable as a single lookup.
enum OpenHandle {
File(fs::File),
/// Remaining unread directory entries; drained in `READDIR_BATCH`-sized
/// chunks by `readdir`, then `SSH_FX_EOF` on the next call.
Dir(Vec<File>),
}
/// What a client-supplied path resolved to.
enum Target {
/// The synthetic root. It has no daemon path of its own: it exists so the
/// two exports have somewhere to hang, and so a client can list `/` and
/// walk between them.
Root,
/// A path inside one of the exports, already proven to be contained.
Real(DaemonAbsPath),
}
impl Target {
/// The daemon path this names, for requests that can only act on a real
/// file. The synthetic root has nothing on disk to open, create, rename,
/// remove or chmod, so naming it is refused like any other path outside
/// the exports.
fn real(self) -> Result<DaemonAbsPath, SftpError> {
match self {
Target::Real(path) => Ok(path),
Target::Root => Err(SftpError::PathTraversal),
}
}
}
/// Per-channel SFTP server scoped to a single session's directories.
pub struct SftpSession {
/// The session's working tree, presented at [`env::WORKSPACE_ROOT`].
///
/// Canonical, and cached at construction: the session contract guarantees
/// both directories are stable for the session lifetime, so fetching them
/// per-request would round-trip through the session actor for nothing.
workspace: DaemonAbsPath,
/// The session's home directory, presented at [`env::HOME_ROOT`].
/// Canonical, for the same reason as [`SftpSession::workspace`].
home: DaemonAbsPath,
handles: HashMap<String, OpenHandle>,
next_handle_id: u64,
/// Refuse every request that changes the exports. Set for a stopped or
/// exited box, whose files are kept for retrieval and for a later resume.
read_only: bool,
}
impl SftpSession {
/// Constructs a handler scoped to one session's working tree and home.
///
/// Both are canonicalized here rather than per-request: containment is
/// decided by comparing a canonicalized path against these roots, and a
/// root reached through a symlink itself (`/var` -> `/private/var`) would
/// fail that comparison for every path under it.
///
/// # Errors
///
/// Returns the underlying [`std::io::Error`] if either directory cannot be
/// canonicalized — it is missing, unreadable, or not UTF-8.
pub async fn new(
workspace: DaemonAbsPath,
home: DaemonAbsPath,
) -> Result<Self, std::io::Error> {
Ok(Self {
workspace: canonicalize(&workspace).await?,
home: canonicalize(&home).await?,
handles: HashMap::new(),
next_handle_id: 0,
read_only: false,
})
}
/// Makes this session refuse every mutating request with
/// `SSH_FX_PERMISSION_DENIED`: an open that can write, create, truncate
/// or append, and every write, setstat, fsetstat, mkdir, rmdir, remove,
/// rename and symlink. Reads, stats, listings and path lookups still work.
#[must_use]
pub fn read_only(mut self) -> Self {
self.read_only = true;
self
}
/// Refuses the request when this session is read-only.
fn ensure_writable(&self, op: &'static str) -> Result<(), SftpError> {
if self.read_only {
tracing::debug!(op, "sftp: refused a mutating request on an ended box");
return Err(SftpError::ReadOnly);
}
Ok(())
}
/// The exported directories, each paired with the client-facing root it
/// appears under. The only place the two are enumerated.
fn exports(&self) -> [(&'static str, &DaemonAbsPath); 2] {
[
(env::WORKSPACE_ROOT, &self.workspace),
(env::HOME_ROOT, &self.home),
]
}
/// Resolves a client-supplied SFTP path to something on the daemon,
/// rejecting anything that resolves outside the exported directories.
///
/// Normalization happens in the *client's* namespace, before the mapping:
/// that way `..` is spent against the client-facing root — where
/// `/workbench/../home` is the other export and `/workbench/../..` is
/// still `/` — and never against the daemon's filesystem. What survives
/// names one of the exports, so the mapping is a prefix swap. The
/// containment check afterwards is about symlinks, which normalization
/// cannot see.
async fn resolve(&self, sftp_path: &str) -> Result<Target, SftpError> {
// A relative path is resolved against the home directory, and it is
// what `realpath(".")` hands back. SFTP and SCP both start a client at
// `$HOME`, which the sandbox points at `HOME_ROOT`. The attach shell's
// initial cwd is the working tree instead: the two surfaces genuinely
// differ, and each follows the convention of its own protocol.
let requested = if sftp_path.starts_with('/') {
Utf8PathBuf::from(sftp_path)
} else {
Utf8Path::new(env::HOME_ROOT).join(sftp_path)
};
let requested = env::normalize_absolute(&requested);
if requested == Utf8Path::new("/") {
return Ok(Target::Root);
}
// `strip_prefix` matches whole components, so `/workbenchevil` is not
// under `/workbench`.
let Some((base, rel)) = self
.exports()
.into_iter()
.find_map(|(root, base)| Some((base, requested.strip_prefix(root).ok()?)))
else {
return Err(SftpError::PathTraversal);
};
let dest = if rel.as_str().is_empty() {
base.clone()
} else {
// The typed join keeps the destination anchored: `join` takes a
// `DaemonRelPath`, where joining a raw string could replace the
// root outright. `try_new` re-checks the remainder is relative and
// `..`-free — normalization above is what makes that hold.
let rel = DaemonRelPath::try_new(rel).map_err(|_| SftpError::PathTraversal)?;
base.join(&rel)
};
contained(dest, base).await.map(Target::Real)
}
/// Resolves a path that a request is about to unlink or move over,
/// refusing the export roots themselves.
///
/// The two directories are the session's layout, and both the daemon and
/// the sandbox expect them to stay where they are. Everything *under*
/// them is the client's to destroy; an empty one would otherwise be a
/// successful `rmdir` or `rename` away from taking the session with it.
async fn resolve_below_export(&self, sftp_path: &str) -> Result<DaemonAbsPath, SftpError> {
let path = self.resolve(sftp_path).await?.real()?;
if self.exports().iter().any(|(_, base)| **base == path) {
return Err(SftpError::PathTraversal);
}
Ok(path)
}
/// Converts a resolved target back into the client-facing form.
fn client_path(&self, target: &Target) -> String {
let Target::Real(host) = target else {
return "/".to_string();
};
for (root, base) in self.exports() {
let Ok(rel) = host.strip_prefix(base) else {
continue;
};
return if rel.as_str().is_empty() {
root.to_string()
} else {
format!("{root}/{rel}")
};
}
// Unreachable: `resolve` only hands back paths under an export.
"/".to_string()
}
fn mint_handle(&mut self, h: OpenHandle) -> String {
let id = self.next_handle_id;
self.next_handle_id += 1;
let key = id.to_string();
self.handles.insert(key.clone(), h);
key
}
fn file_mut(&mut self, h: &str) -> Result<&mut fs::File, SftpError> {
match self.handles.get_mut(h) {
Some(OpenHandle::File(f)) => Ok(f),
Some(_) => Err(SftpError::WrongHandleType),
None => Err(SftpError::UnknownHandle),
}
}
fn dir_mut(&mut self, h: &str) -> Result<&mut Vec<File>, SftpError> {
match self.handles.get_mut(h) {
Some(OpenHandle::Dir(entries)) => Ok(entries),
Some(_) => Err(SftpError::WrongHandleType),
None => Err(SftpError::UnknownHandle),
}
}
}
/// Proves `dest` really lives under `base`, and returns it with every symlink
/// on the way already resolved.
///
/// `dest` need not exist — SFTP creates files, and `open` with `CREATE` names
/// one that does not. So the check walks up to the deepest ancestor that does
/// exist, canonicalizes *that*, and re-appends the missing tail: a symlinked
/// parent is refused before anything is created through it, which
/// canonicalizing only existing paths would miss.
///
/// `base` is canonical (see [`SftpSession::new`]), so the comparison is
/// symlink-free on both sides. The walk terminates because `base` exists: it
/// either finds an existing ancestor at or below `base`, or walks past it and
/// is refused.
async fn contained(dest: DaemonAbsPath, base: &DaemonAbsPath) -> Result<DaemonAbsPath, SftpError> {
let mut probe = dest;
let mut missing: Vec<String> = Vec::new();
loop {
match canonicalize(&probe).await {
Ok(real) => {
if !real.starts_with(base) {
return Err(SftpError::PathTraversal);
}
// `missing` was pushed leaf-last on the way up.
return Ok(missing
.iter()
.rev()
.fold(real, |path, name| path.sub_path_unchecked(name)));
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
// A dangling symlink canonicalizes to `NotFound` while still
// being a real directory entry. Reading it as "does not exist
// yet" would hand back the link's own path, and `open` with
// `CREATE` would then follow it and create the file it points
// at — outside `base`, which is the whole point of this walk.
if fs::symlink_metadata(probe.as_str()).await.is_ok() {
return Err(SftpError::PathTraversal);
}
let (Some(name), Some(parent)) = (probe.file_name(), probe.parent()) else {
// Ran out of path before finding anything that exists;
// only reachable above `base`, which does exist.
return Err(SftpError::PathTraversal);
};
missing.push(name.to_string());
probe = parent;
}
Err(e) => return Err(SftpError::Io(e)),
}
}
}
/// [`tokio::fs::canonicalize`], keeping the path typed and UTF-8.
async fn canonicalize(path: &DaemonAbsPath) -> Result<DaemonAbsPath, std::io::Error> {
let canonical = fs::canonicalize(path.as_str()).await?;
let canonical = Utf8PathBuf::from_path_buf(canonical)
.map_err(|p| std::io::Error::other(format!("path is not utf-8: {}", p.display())))?;
// `canonicalize` returns an absolute path by construction.
Ok(DaemonAbsPath::new_unchecked(canonical))
}
/// Attributes reported for the synthetic root: a read-only directory.
///
/// It has no inode of its own, so mode is the only thing we can honestly
/// state. Everything else — size, uid/gid, atime/mtime — is left unset, and
/// SFTP's per-field flags mean an unset field is absent from the packet
/// rather than zero. `set_dir` writes `S_IFDIR` into the mode, which is what
/// makes a client's `stat("/")` report a directory.
///
/// (Before russh-sftp 2.2, `FileAttributes::default()` supplied dummy zeros
/// rather than absent fields, so root used to advertise size 0, uid/gid 0 and
/// epoch timestamps. `FileAttributes::dummy()` is the name for that now, and
/// this is deliberately not it.)
fn root_attrs() -> FileAttributes {
let mut attrs = FileAttributes {
permissions: Some(0o555),
..FileAttributes::default()
};
attrs.set_dir(true);
attrs
}
impl russh_sftp::server::Handler for SftpSession {
type Error = SftpError;
fn unimplemented(&self) -> Self::Error {
SftpError::Unsupported
}
async fn realpath(&mut self, id: u32, path: String) -> Result<Name, Self::Error> {
let target = self.resolve(&path).await?;
Ok(Name {
id,
files: vec![File::dummy(self.client_path(&target))],
})
}
async fn stat(&mut self, id: u32, path: String) -> Result<Attrs, Self::Error> {
let attrs = match self.resolve(&path).await? {
Target::Root => root_attrs(),
Target::Real(host) => FileAttributes::from(&fs::metadata(host.as_str()).await?),
};
Ok(Attrs { id, attrs })
}
async fn lstat(&mut self, id: u32, path: String) -> Result<Attrs, Self::Error> {
// A symlink is already gone by the time we get here: `resolve`
// follows links to decide containment, so this reports the target,
// as `readdir` does. Nothing under an export can name a link outside
// it, so there is nothing to describe that `stat` would not.
let attrs = match self.resolve(&path).await? {
Target::Root => root_attrs(),
Target::Real(host) => FileAttributes::from(&fs::symlink_metadata(host.as_str()).await?),
};
Ok(Attrs { id, attrs })
}
async fn fstat(&mut self, id: u32, handle: String) -> Result<Attrs, Self::Error> {
let f = self.file_mut(&handle)?;
let m = f.metadata().await?;
Ok(Attrs {
id,
attrs: FileAttributes::from(&m),
})
}
async fn open(
&mut self,
id: u32,
filename: String,
pflags: OpenFlags,
_attrs: FileAttributes,
) -> Result<Handle, Self::Error> {
let mutating = OpenFlags::WRITE
| OpenFlags::APPEND
| OpenFlags::CREATE
| OpenFlags::TRUNCATE
| OpenFlags::EXCLUDE;
if pflags.intersects(mutating) {
self.ensure_writable("open")?;
}
let host = self.resolve(&filename).await?.real()?;
let mut opts = OpenOptions::new();
// `resolve` proved a path; this opens a *name*, and the two are only
// the same until something rewrites the leaf. Both exports are
// bind-mounted read-write into the sandbox, so an in-session process
// can sit in that gap swapping the leaf for a symlink until an open
// lands on it — with the daemon, which is not confined to the
// sandbox, doing the following. `O_NOFOLLOW` refuses that leaf
// outright. It costs nothing legitimate: `resolve` hands back a
// canonical path, so a real symlink is already resolved to its
// target by the time we get here and there is no link left to refuse.
// A swap higher up the path is not covered here — the ancestor walk
// in `contained` is what narrows that.
opts.custom_flags(libc::O_NOFOLLOW);
opts.read(pflags.contains(OpenFlags::READ))
.write(pflags.contains(OpenFlags::WRITE))
.append(pflags.contains(OpenFlags::APPEND))
.truncate(pflags.contains(OpenFlags::TRUNCATE));
// EXCLUDE implies CREATE per SFTP semantics; create_new covers both.
if pflags.contains(OpenFlags::EXCLUDE) {
opts.create_new(true);
} else if pflags.contains(OpenFlags::CREATE) {
opts.create(true);
}
let f = opts.open(host.as_str()).await?;
let handle = self.mint_handle(OpenHandle::File(f));
Ok(Handle { id, handle })
}
async fn close(&mut self, id: u32, handle: String) -> Result<Status, Self::Error> {
self.handles
.remove(&handle)
.ok_or(SftpError::UnknownHandle)?;
Ok(ok_status(id))
}
async fn read(
&mut self,
id: u32,
handle: String,
offset: u64,
len: u32,
) -> Result<Data, Self::Error> {
let f = self.file_mut(&handle)?;
f.seek(SeekFrom::Start(offset)).await?;
let mut buf = vec![0u8; (len as usize).min(MAX_READ_LEN)];
let n = f.read(&mut buf).await?;
if n == 0 {
return Err(SftpError::Eof);
}
buf.truncate(n);
Ok(Data { id, data: buf })
}
async fn write(
&mut self,
id: u32,
handle: String,
offset: u64,
data: Vec<u8>,
) -> Result<Status, Self::Error> {
self.ensure_writable("write")?;
let f = self.file_mut(&handle)?;
f.seek(SeekFrom::Start(offset)).await?;
f.write_all(&data).await?;
Ok(ok_status(id))
}
async fn opendir(&mut self, id: u32, path: String) -> Result<Handle, Self::Error> {
let host = match self.resolve(&path).await? {
// The synthetic root holds the two exports and nothing else —
// no "..", since there is nothing above it.
Target::Root => {
let mut entries = vec![File::new(".".to_string(), root_attrs())];
for (root, base) in self.exports() {
let m = fs::metadata(base.as_str()).await?;
// The exports' client-facing roots are their names, since
// they sit directly under `/`.
let name = root.trim_start_matches('/').to_string();
entries.push(File::new(name, FileAttributes::from(&m)));
}
let handle = self.mint_handle(OpenHandle::Dir(entries));
return Ok(Handle { id, handle });
}
Target::Real(host) => host,
};
let mut entries = Vec::new();
let m = fs::metadata(host.as_str()).await?;
entries.push(File::new(".".to_string(), FileAttributes::from(&m)));
// At an export root the parent on disk is a daemon directory the
// client has no business seeing; ".." there is the synthetic root.
let parent = host
.parent()
.filter(|p| p.starts_with(&self.workspace) || p.starts_with(&self.home));
let parent_attrs = match parent {
Some(parent) => FileAttributes::from(&fs::metadata(parent.as_str()).await?),
None => root_attrs(),
};
entries.push(File::new("..".to_string(), parent_attrs));
let mut read = fs::read_dir(host.as_str()).await?;
while let Some(e) = read.next_entry().await? {
let em = e.metadata().await?;
let name = e.file_name().to_string_lossy().into_owned();
entries.push(File::new(name, FileAttributes::from(&em)));
}
let handle = self.mint_handle(OpenHandle::Dir(entries));
Ok(Handle { id, handle })
}
async fn readdir(&mut self, id: u32, handle: String) -> Result<Name, Self::Error> {
let entries = self.dir_mut(&handle)?;
if entries.is_empty() {
return Err(SftpError::Eof);
}
let take = entries.len().min(READDIR_BATCH);
let files = entries.drain(..take).collect();
Ok(Name { id, files })
}
async fn mkdir(
&mut self,
id: u32,
path: String,
_attrs: FileAttributes,
) -> Result<Status, Self::Error> {
self.ensure_writable("mkdir")?;
let host = self.resolve(&path).await?.real()?;
fs::create_dir(host.as_str()).await?;
Ok(ok_status(id))
}
async fn rmdir(&mut self, id: u32, path: String) -> Result<Status, Self::Error> {
self.ensure_writable("rmdir")?;
let host = self.resolve_below_export(&path).await?;
fs::remove_dir(host.as_str()).await?;
Ok(ok_status(id))
}
async fn remove(&mut self, id: u32, filename: String) -> Result<Status, Self::Error> {
self.ensure_writable("remove")?;
let host = self.resolve_below_export(&filename).await?;
fs::remove_file(host.as_str()).await?;
Ok(ok_status(id))
}
async fn rename(
&mut self,
id: u32,
oldpath: String,
newpath: String,
) -> Result<Status, Self::Error> {
self.ensure_writable("rename")?;
let from = self.resolve_below_export(&oldpath).await?;
let to = self.resolve_below_export(&newpath).await?;
fs::rename(from.as_str(), to.as_str()).await?;
Ok(ok_status(id))
}
async fn setstat(
&mut self,
id: u32,
path: String,
attrs: FileAttributes,
) -> Result<Status, Self::Error> {
self.ensure_writable("setstat")?;
let host = self.resolve(&path).await?.real()?;
if let Some(perms) = perm_from_mode(attrs.permissions) {
// `chmod` follows symlinks, so like `open` this re-resolves the
// leaf by name and a link swapped in after the check would be
// followed out of the export. The other mutating handlers need no
// such care: `mkdir`, `rmdir`, `unlink` and `rename` all act on
// the link itself rather than what it points at.
//
// `fchmod` through an `O_NOFOLLOW` handle refuses that leaf the
// same way `open` does. `O_NONBLOCK` because this open is the
// only thing standing between a fifo planted in the workspace and
// a wedged dispatch loop; on a regular file it does nothing.
let file = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
.open(host.as_str())
.await?;
// The handle's own `fstat`, not a second lookup by name: it
// describes exactly the object about to be chmodded.
let is_dir = file.metadata().await?.is_dir();
file.set_permissions(keep_owner_access(perms, is_dir))
.await?;
}
Ok(ok_status(id))
}
async fn fsetstat(
&mut self,
id: u32,
handle: String,
attrs: FileAttributes,
) -> Result<Status, Self::Error> {
self.ensure_writable("fsetstat")?;
if let Some(perms) = perm_from_mode(attrs.permissions) {
self.file_mut(&handle)?.set_permissions(perms).await?;
}
Ok(ok_status(id))
}
/// Not served: a read-only session refuses it as a mutation, and any
/// other session reports it unsupported, as before.
async fn symlink(
&mut self,
_id: u32,
_linkpath: String,
_targetpath: String,
) -> Result<Status, Self::Error> {
self.ensure_writable("symlink")?;
Err(SftpError::Unsupported)
}
}
/// Strips the file-type bits from an SFTP permissions field and returns a
/// `std::fs::Permissions` carrying only the POSIX mode bits. Returns `None`
/// when the client omitted permissions, so callers leave the attribute
/// untouched.
fn perm_from_mode(mode: Option<u32>) -> Option<std::fs::Permissions> {
use std::os::unix::fs::PermissionsExt;
mode.map(|m| std::fs::Permissions::from_mode(m & 0o7777))
}
/// Floors a client's mode at owner `r-x` for directories, `r--` otherwise;
/// every other bit passes through.
///
/// Without it `chmod 000` is irreversible: `setstat` chmods through an open
/// handle, so a file the owner cannot read is one no later request can chmod
/// back. Owner write is not forced — read-only is a thing clients may
/// legitimately want, and it stays undoable.
fn keep_owner_access(perms: std::fs::Permissions, is_dir: bool) -> std::fs::Permissions {
use std::os::unix::fs::PermissionsExt;
let floor = if is_dir { 0o500 } else { 0o400 };
std::fs::Permissions::from_mode(perms.mode() | floor)
}
fn ok_status(id: u32) -> Status {
Status {
id,
status_code: StatusCode::Ok,
error_message: String::new(),
language_tag: String::from("en-US"),
}
}
/// Handles an `sftp` subsystem request on an SSH channel.
///
/// Looks up the target session via the `MINIMAL_SESSION_ID` env var the
/// client previously set on this channel, fetches its workspace, accepts the
/// subsystem request, and spawns `russh_sftp::server::run` to take over the
/// channel for the lifetime of the SFTP conversation.
pub(crate) async fn handle_sftp_subsystem(
s: ServerStateHandle,
c: ConnectionHandle,
id: ChannelId,
session: &mut Session,
) -> Result<(), ConnectionError> {
let mut conn_lock = c.lock().await;
let Some((channel, config)) = conn_lock.take(id) else {
session.channel_failure(id)?;
return Ok(());
};
drop(conn_lock);
let Some(session_id_str) = config.env_vars.get(MINIMAL_SESSION_ID_ENV) else {
tracing::warn!("sftp subsystem rejected on channel {id}: missing {MINIMAL_SESSION_ID_ENV}",);
session.channel_failure(id)?;
return Ok(());
};
let Ok(session_id) = SessionId::parse_str(session_id_str) else {
tracing::warn!(
value = %session_id_str,
"sftp subsystem rejected on channel {id}: {MINIMAL_SESSION_ID_ENV} is not a uuid",
);
session.channel_failure(id)?;
return Ok(());
};
// The subsystem span records whether the box was ended (BOX-017).
let span = tracing::info_span!(
"sftp.subsystem",
%session_id,
ended = tracing::field::Empty,
);
tracing::Instrument::instrument(serve_box_files(s, channel, id, session, session_id), span)
.await
}
/// Opens the SFTP conversation on `channel` against the directories of the
/// box `session_id`, under the caller's `sftp.subsystem` span.
///
/// A stopped or exited box is served read-only from its retained
/// directories, read from its record, with no actor started for it (BOX-017). Any other box
/// is served through its actor, which the lookup starts when it is idle.
async fn serve_box_files(
s: ServerStateHandle,
channel: russh::Channel<russh::server::Msg>,
id: ChannelId,
session: &mut Session,
session_id: SessionId,
) -> Result<(), ConnectionError> {
let mngr = s.sessions_manager().await;
let ended = match mngr.ended_box(session_id).await {
Ok(ended) => ended,
Err(e) => {
tracing::warn!(%session_id, error = %e, "sftp subsystem rejected: lookup failed");
session.channel_failure(id)?;
return Ok(());
}
};
tracing::Span::current().record("ended", ended.is_some());
let read_only = ended.is_some();
let paths = if let Some(ended) = ended {
tracing::info!(
%session_id,
state = ended.state.name(),
"sftp: serving the retained files of an ended box, read-only, with no actor"
);
ended.paths
} else {
let session_handle = match mngr.get_session(BoxKeyPredicate::Id(session_id)).await {
Ok(Some(h)) => h,
Ok(None) => {
tracing::warn!(%session_id, "sftp subsystem rejected: unknown session");
session.channel_failure(id)?;
return Ok(());
}
Err(e) => {
tracing::warn!(%session_id, error = %e, "sftp subsystem rejected: lookup failed");
session.channel_failure(id)?;
return Ok(());
}
};
match session_handle.paths().await {
Ok(paths) => paths,
// The actor died between resolve and this call (raced an
// abort/destroy) — to this channel the session no longer exists.
Err(e) => {
tracing::warn!(%session_id, error = %e, "sftp subsystem rejected: session is gone");
session.channel_failure(id)?;
return Ok(());
}
}
};
// Canonicalizing the session's two directories is the one filesystem
// touch before the channel is accepted: a session whose directories are
// gone cannot serve any request on this channel anyway.
let sftp = match SftpSession::new(paths.working, paths.home).await {
// An ended box is served for retrieval only: a write would change the
// state a later resume restarts from (BOX-017, BOX-025).
Ok(sftp) if read_only => sftp.read_only(),
Ok(sftp) => sftp,
Err(e) => {
tracing::warn!(%session_id, error = %e, "sftp subsystem rejected: session directories are unusable");
session.channel_failure(id)?;
return Ok(());
}
};
session.channel_success(id)?;
spawn(russh_sftp::server::run(channel.into_stream(), sftp));
Ok(())
}
#[cfg(test)]
mod tests {
use boxes::SessionId;
use russh_sftp::client::SftpSession as SftpClient;
use russh_sftp::client::error::Error as SftpClientError;
use russh_sftp::protocol::{OpenFlags, StatusCode};
use std::os::unix::fs::PermissionsExt;
use tokio::io::AsyncWriteExt;
use crate::box_actor::BoxPaths;
use crate::box_manager::BoxKeyPredicate;
use crate::env;
use crate::test_harness::TestServer;
/// Creates a fresh session through the public CreateSession RPC and
/// returns its uuid, mirroring how a real client would set things up
/// before opening an SFTP channel.
async fn fresh_session(client: &mut crate::test_harness::TestClient) -> SessionId {
crate::test_harness::create_configured_session(client, "sftp-test", "/tmp").await
}
/// The daemon-side directories behind a session, so a test can check
/// *where* a client's write landed rather than only that it round-trips.
async fn session_paths(server: &TestServer, id: SessionId) -> BoxPaths {
let mngr = server.state.sessions_manager().await;
mngr.get_session(BoxKeyPredicate::Id(id))
.await
.unwrap()
.expect("session was just created")
.paths()
.await
.unwrap()
}
/// Writes `payload` through the SFTP channel, failing the test on any
/// error — the escape tests are the ones interested in error paths.
async fn write(sftp: &SftpClient, path: &str, payload: &[u8]) {
let mut file = sftp.create(path).await.unwrap();
file.write_all(payload).await.unwrap();
file.shutdown().await.unwrap();
}
/// Asserts a request was refused with `SSH_FX_PERMISSION_DENIED`, which
/// is what every containment failure maps to on the wire.
fn assert_denied<T>(result: Result<T, SftpClientError>) {
match result {
Err(SftpClientError::Status(s)) => {
assert_eq!(s.status_code, StatusCode::PermissionDenied);
}
Err(e) => panic!("expected PermissionDenied, got error {e:?}"),
Ok(_) => panic!("expected PermissionDenied, but the request succeeded"),
}
}
#[tokio::test]
async fn sftp_write_then_read_round_trips() {
let server = TestServer::new().await;
let mut client = server.connect().await;
let session_id = fresh_session(&mut client).await;
let sftp = client.open_sftp(session_id).await;
let payload: &[u8] = b"hello from sftp";
write(&sftp, "hello.txt", payload).await;
let read_back = sftp.read("hello.txt").await.unwrap();
assert_eq!(read_back, payload);
// A relative path is the session's home, not its working tree: an
// SFTP client that never spells out a path is where `$HOME` is.
let paths = session_paths(&server, session_id).await;
let on_disk = tokio::fs::read(paths.home.sub_path_unchecked("hello.txt").as_str())
.await
.unwrap();
assert_eq!(on_disk, payload);
assert!(
!tokio::fs::try_exists(paths.working.sub_path_unchecked("hello.txt").as_str())
.await
.unwrap()
);
}
/// BOX-017: a stopped box keeps its files on disk, and a copy out of
/// them is served from the retained filesystem with no actor started.
#[tokio::test]
async fn stopped_box_filesystem_served_by_cp() {
use boxes::core::record::RecordState;
let server = TestServer::new().await;
let mut client = server.connect().await;
let session_id = fresh_session(&mut client).await;
let payload: &[u8] = b"kept after the stop";
{
let sftp = client.open_sftp(session_id).await;
write(&sftp, "kept.txt", payload).await;
write(&sftp, &format!("{}/tree.txt", env::WORKSPACE_ROOT), payload).await;
}
let mngr = server.state.sessions_manager().await;
mngr.stop_box_with_grace(session_id, false, std::time::Duration::from_secs(5))
.await
.expect("the stop succeeds");
// The actor evicts itself when the stop ends: no actor hosts a
// stopped box.
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10);
while mngr.running_count().await != 0 {
assert!(
tokio::time::Instant::now() < deadline,
"the stopped box's actor did not end"
);
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
let sftp = client.open_sftp(session_id).await;
assert_eq!(sftp.read("kept.txt").await.unwrap(), payload);
assert_eq!(
sftp.read(&format!("{}/tree.txt", env::WORKSPACE_ROOT))
.await
.unwrap(),
payload
);
let listed: Vec<String> = sftp
.read_dir(env::WORKSPACE_ROOT)
.await
.unwrap()
.map(|e| e.file_name())
.collect();
assert!(listed.contains(&"tree.txt".to_string()), "{listed:?}");
assert!(sftp.metadata("kept.txt").await.unwrap().is_regular());
// The retained files are for retrieval only: every mutating request
// is refused, and the file is left as the box left it.
assert_denied(sftp.create("kept.txt").await);
assert_denied(sftp.open_with_flags("kept.txt", OpenFlags::WRITE).await);
assert_denied(sftp.open_with_flags("kept.txt", OpenFlags::APPEND).await);
assert_denied(sftp.create("new.txt").await);
assert_denied(sftp.remove_file("kept.txt").await);
assert_denied(sftp.rename("kept.txt", "moved.txt").await);
assert_denied(sftp.create_dir("made").await);
assert_denied(sftp.remove_dir(env::WORKSPACE_ROOT).await);
assert_denied(sftp.symlink("link", "kept.txt").await);
let mut attrs = russh_sftp::protocol::FileAttributes::empty();
attrs.permissions = Some(0o600);
assert_denied(sftp.set_metadata("kept.txt", attrs).await);
assert_eq!(sftp.read("kept.txt").await.unwrap(), payload);
let paths = mngr
.ended_box(session_id)
.await
.unwrap()
.expect("the box is still ended")
.paths;
let on_disk = tokio::fs::read(paths.home.sub_path_unchecked("kept.txt").as_str())
.await
.unwrap();
assert_eq!(
on_disk, payload,
"the refused requests left the file unchanged"
);
for absent in ["new.txt", "moved.txt", "made", "link"] {