forked from lablup/bssh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsftp.rs
More file actions
1948 lines (1696 loc) · 65.8 KB
/
sftp.rs
File metadata and controls
1948 lines (1696 loc) · 65.8 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.
//! SFTP server handler implementation.
//!
//! This module provides the SFTP subsystem handler for the bssh server,
//! implementing the `russh_sftp::server::Handler` trait.
//!
//! # Security
//!
//! The handler implements path traversal prevention to ensure clients
//! cannot access files outside their designated root directory.
//!
//! # Example
//!
//! ```no_run
//! use bssh::server::sftp::SftpHandler;
//! use bssh::shared::auth_types::UserInfo;
//! use std::path::PathBuf;
//!
//! let user = UserInfo::new("testuser");
//! // Without chroot (OpenSSH-compatible behavior):
//! let handler = SftpHandler::new(user.clone(), None, PathBuf::from("/home/testuser"));
//!
//! // With chroot:
//! let handler = SftpHandler::new(
//! user,
//! Some(PathBuf::from("/srv/sftp")),
//! PathBuf::from("/home/testuser"),
//! );
//! ```
use std::collections::HashMap;
use std::io::SeekFrom;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use russh_sftp::protocol::{
Attrs, Data, FileAttributes, Handle, Name, OpenFlags, Status, StatusCode, Version,
};
use tokio::fs::{self, File, OpenOptions};
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
use tokio::sync::Mutex;
use crate::shared::auth_types::UserInfo;
/// Error type for SFTP operations.
///
/// This wrapper type converts to `StatusCode` for the SFTP handler trait.
#[derive(Debug, Clone)]
pub struct SftpError {
/// The status code for the error.
pub code: StatusCode,
/// Human-readable error message.
pub message: String,
}
impl SftpError {
/// Create a new SFTP error.
pub fn new(code: StatusCode, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
}
}
/// Create an "operation not supported" error.
pub fn not_supported() -> Self {
Self::new(StatusCode::OpUnsupported, "Operation not supported")
}
/// Create a "no such file" error.
pub fn no_such_file(path: &Path) -> Self {
Self::new(
StatusCode::NoSuchFile,
format!("No such file: {}", path.display()),
)
}
/// Create a "permission denied" error.
pub fn permission_denied(message: impl Into<String>) -> Self {
Self::new(StatusCode::PermissionDenied, message)
}
/// Create an "invalid handle" error.
pub fn invalid_handle() -> Self {
Self::new(StatusCode::Failure, "Invalid handle")
}
/// Create a generic failure error.
#[allow(dead_code)]
pub fn failure(message: impl Into<String>) -> Self {
Self::new(StatusCode::Failure, message)
}
/// Create an EOF error.
pub fn eof() -> Self {
Self::new(StatusCode::Eof, "End of file")
}
}
impl std::fmt::Display for SftpError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.code, self.message)
}
}
impl std::error::Error for SftpError {}
impl From<std::io::Error> for SftpError {
fn from(err: std::io::Error) -> Self {
use std::io::ErrorKind;
let code = match err.kind() {
ErrorKind::NotFound => StatusCode::NoSuchFile,
ErrorKind::PermissionDenied => StatusCode::PermissionDenied,
ErrorKind::UnexpectedEof => StatusCode::Eof,
_ => StatusCode::Failure,
};
Self::new(code, err.to_string())
}
}
impl From<SftpError> for StatusCode {
fn from(err: SftpError) -> Self {
err.code
}
}
/// An open file or directory handle.
enum OpenHandle {
/// An open file.
File {
file: File,
path: PathBuf,
#[allow(dead_code)]
flags: OpenFlags,
},
/// An open directory listing.
Dir {
path: PathBuf,
entries: Vec<DirEntryInfo>,
position: usize,
},
}
/// Directory entry information for readdir.
struct DirEntryInfo {
filename: String,
attrs: FileAttributes,
}
/// Maximum number of open handles per session to prevent resource exhaustion.
const MAX_HANDLES: usize = 1000;
/// Maximum read buffer size per request. Matches the SFTP standard
/// `MAX_READ_LENGTH` (255 KiB) used by `bssh-russh-sftp` and OpenSSH
/// `sftp-server`. The previous 64 KiB cap silently truncated client `READ`
/// requests for 256 KiB chunks down to 64 KiB, multiplying request count 4×
/// for the same byte stream and dragging down sustained download throughput.
/// Memory exposure remains bounded because handles are capped at
/// [`MAX_HANDLES`] per session and each in-flight read uses a single
/// per-request buffer of this size.
const MAX_READ_SIZE: u32 = 261120;
/// Normalize a path's `..` and `.` components without touching the filesystem.
///
/// This is a logical normalization that does not follow symlinks. Used as
/// a building block for both chrooted and non-chrooted resolution.
fn normalize_components(path: &Path) -> PathBuf {
use std::path::Component;
let mut out = PathBuf::new();
for component in path.components() {
match component {
Component::Normal(c) => out.push(c),
Component::CurDir => {}
Component::ParentDir => {
// Pop only normal components; never above the root prefix.
if !out.pop() {
out.push("..");
}
}
Component::RootDir => out.push("/"),
Component::Prefix(p) => out.push(p.as_os_str()),
}
}
out
}
/// Resolve a client-supplied path against a chroot root.
///
/// - Plain `/` (the chroot's pseudo-root in the client's view, also returned
/// by `realpath`) maps to `root`.
/// - Absolute paths inside `root` are honored as-is (no doubling).
/// - Absolute paths outside `root` are rejected.
/// - Relative paths are joined with `root` and normalized.
/// - `..` traversal is clamped to `root`.
fn resolve_chroot(requested: &Path, root: &Path) -> Result<PathBuf, SftpError> {
use std::path::Component;
// Treat empty path the same as "." to keep parity with no-chroot mode.
let requested = if requested.as_os_str().is_empty() {
Path::new(".")
} else {
requested
};
if requested.is_absolute() {
// Plain "/" is the client's view of the chroot root (returned by
// `realpath`). Map it back to the actual chroot directory so the
// realpath-roundtrip stays consistent.
if requested == Path::new("/") {
return Ok(root.to_path_buf());
}
// Absolute paths inside the chroot are honored verbatim. Anything
// outside is rejected so the chroot enforces a containment boundary
// rather than silently re-rooting the path.
let normalized = normalize_components(requested);
if normalized == root || normalized.starts_with(root) {
tracing::trace!(
requested = %requested.display(),
resolved = %normalized.display(),
"Resolved absolute path inside chroot"
);
return Ok(normalized);
}
tracing::warn!(
event = "chroot_escape_blocked",
requested = %requested.display(),
root = %root.display(),
"Absolute path outside chroot rejected"
);
return Err(SftpError::permission_denied(
"Access denied: path outside root",
));
}
// Relative path: join with root, then walk components clamping `..`
// so traversal cannot escape the chroot. This preserves the original
// security guarantee.
let mut resolved = root.to_path_buf();
for component in requested.components() {
match component {
Component::Normal(c) => resolved.push(c),
Component::CurDir => {}
Component::ParentDir => {
// Refuse to pop past the chroot root so traversal cannot
// escape. `resolved` is always rooted at `root` (initialized
// to `root`, only extended via `Normal` pushes), so popping
// when `resolved != root` always stays inside or at `root`.
if resolved != root {
resolved.pop();
}
}
// Relative paths shouldn't carry these, but ignore safely.
Component::RootDir | Component::Prefix(_) => {}
}
}
if !resolved.starts_with(root) {
tracing::warn!(
event = "path_traversal_blocked",
requested = %requested.display(),
resolved = %resolved.display(),
root = %root.display(),
"Resolved path escaped chroot"
);
return Err(SftpError::permission_denied(
"Access denied: path outside root",
));
}
tracing::trace!(
requested = %requested.display(),
resolved = %resolved.display(),
"Resolved relative path under chroot"
);
Ok(resolved)
}
/// Find the closest existing ancestor of `path` and return both the ancestor
/// and its canonicalized form.
///
/// Walks up `path` (popping one component at a time) until a path that exists
/// on the filesystem is found, then canonicalizes it. Used by chroot
/// resolution to detect intermediate-directory symlinks pointing outside the
/// chroot — without this check, `open(...)` / `create_dir(...)` etc. on a
/// non-existent final path would happily follow a parent-symlink and operate
/// outside the chroot.
///
/// Returns `None` when no ancestor exists or canonicalization fails for every
/// candidate.
fn closest_existing_canonical(path: &Path) -> Option<(PathBuf, PathBuf)> {
let mut cur = path.to_path_buf();
loop {
if cur.exists() {
if let Ok(canonical) = std::fs::canonicalize(&cur) {
return Some((cur, canonical));
}
return None;
}
if !cur.pop() {
return None;
}
}
}
/// Resolve a client-supplied path without a chroot.
///
/// - Absolute paths are used verbatim, after normalizing `.` and `..`.
/// - Relative paths join with `cwd` (the user's home directory by default)
/// and are normalized the same way.
///
/// This matches OpenSSH `sftp-server` semantics: filesystem permissions are
/// the only access boundary.
fn resolve_no_chroot(requested: &Path, cwd: &Path) -> PathBuf {
let requested = if requested.as_os_str().is_empty() {
Path::new(".")
} else {
requested
};
let joined = if requested.is_absolute() {
requested.to_path_buf()
} else {
cwd.join(requested)
};
let normalized = normalize_components(&joined);
tracing::trace!(
requested = %requested.display(),
resolved = %normalized.display(),
"Resolved path (no chroot)"
);
normalized
}
/// SFTP server handler.
///
/// Implements the SFTP protocol for file transfer operations with
/// security controls to prevent path traversal attacks.
pub struct SftpHandler {
/// Current user information.
user_info: UserInfo,
/// Optional chroot root for SFTP operations.
///
/// When `Some(path)`, all client paths are confined to this directory.
/// When `None`, the handler runs without chroot (OpenSSH-compatible),
/// using `cwd` as the base for relative paths and honoring absolute
/// client paths verbatim.
root_dir: Option<PathBuf>,
/// Base directory for resolving relative client paths.
///
/// When `root_dir` is `Some(_)`, this is set to the chroot root.
/// When `root_dir` is `None`, this is the user's home directory and
/// matches OpenSSH's `chdir` behavior on session start.
cwd: PathBuf,
/// Open file and directory handles (shared for async access).
handles: Arc<Mutex<HashMap<String, OpenHandle>>>,
/// Counter for generating unique handle IDs.
handle_counter: u64,
}
impl SftpHandler {
/// Create a new SFTP handler.
///
/// # Arguments
///
/// * `user_info` - Information about the authenticated user
/// * `root_dir` - Optional chroot root. When `None`, no chroot is applied.
/// * `home_dir` - The user's home directory; used as the base for relative
/// paths when chroot is disabled.
pub fn new(user_info: UserInfo, root_dir: Option<PathBuf>, home_dir: PathBuf) -> Self {
let cwd = root_dir.clone().unwrap_or_else(|| home_dir.clone());
tracing::debug!(
user = %user_info.username,
chroot = ?root_dir.as_ref().map(|p| p.display().to_string()),
cwd = %cwd.display(),
"Creating SFTP handler"
);
Self {
user_info,
root_dir,
cwd,
handles: Arc::new(Mutex::new(HashMap::new())),
handle_counter: 0,
}
}
/// Generate a new unique handle ID.
fn new_handle(&mut self) -> String {
self.handle_counter += 1;
format!("h{}", self.handle_counter)
}
/// Resolve a client path to an absolute filesystem path.
///
/// Behavior depends on whether a chroot `root_dir` is configured.
///
/// ## With chroot (`root_dir = Some(root)`):
/// - Absolute client paths inside `root` are honored as-is.
/// - Absolute client paths outside `root` are rejected with
/// `permission_denied` (matching OpenSSH `ChrootDirectory` semantics).
/// - Relative paths are joined with `root`.
/// - `..` traversal is clamped to `root` (cannot escape).
///
/// ## Without chroot (`root_dir = None`):
/// - Absolute paths are used verbatim.
/// - Relative paths are joined with `cwd` (the user's home directory).
/// - `..` traversal is normalized but not clamped (filesystem permissions
/// remain the access boundary, matching OpenSSH).
fn resolve_path_static(
path: &str,
root_dir: Option<&Path>,
cwd: &Path,
) -> Result<PathBuf, SftpError> {
let requested = Path::new(path);
let resolved = match root_dir {
Some(root) => resolve_chroot(requested, root)?,
None => return Ok(resolve_no_chroot(requested, cwd)),
};
// Chroot mode: also verify the closest existing ancestor canonicalizes
// inside the chroot. This catches intermediate-directory symlinks
// pointing outside the chroot. Without this, a chroot-internal symlink
// such as `chroot/escape -> /etc` would let a client target
// `chroot/escape/passwd` and have `open(...)` follow the symlink to
// write `/etc/passwd`. Lexical `starts_with(root)` alone cannot
// detect this; we need filesystem-level canonicalization.
//
// Compare canonical-vs-canonical: an unresolved root might itself
// contain symlinks, so we canonicalize both sides. If the chroot
// root does not exist on disk, the operator config is bad and we
// can only fall back to the lexical check (skip enforcement here).
let root = root_dir.expect("chroot branch implies Some(root)");
if let Some(canonical_root) = std::fs::canonicalize(root).ok()
&& let Some((ancestor, canonical_ancestor)) = closest_existing_canonical(&resolved)
&& !canonical_ancestor.starts_with(&canonical_root)
{
tracing::warn!(
event = "symlink_escape_attempt",
requested = %path,
resolved = %resolved.display(),
ancestor = %ancestor.display(),
canonical_ancestor = %canonical_ancestor.display(),
canonical_root = %canonical_root.display(),
"Security: parent-directory symlink escape blocked"
);
return Err(SftpError::permission_denied(
"Access denied: path outside root",
));
}
Ok(resolved)
}
/// Resolve a client path to an absolute filesystem path.
///
/// See [`Self::resolve_path_static`] for the full semantics. This is the
/// instance-method wrapper used throughout the handler trait impl.
pub fn resolve_path(&self, path: &str) -> Result<PathBuf, SftpError> {
Self::resolve_path_static(path, self.root_dir.as_deref(), &self.cwd)
}
/// Validate that a symlink's resolved target stays inside the chroot, if
/// chroot is enabled.
///
/// Returns `Ok(())` when:
/// - chroot is disabled (no enforcement applies), or
/// - the resolved target lives under `root_dir`.
///
/// Returns `permission_denied` when the target escapes a configured chroot.
fn ensure_target_in_root(
root_dir: Option<&Path>,
resolved_target: &Path,
) -> Result<(), SftpError> {
match root_dir {
Some(root) if !resolved_target.starts_with(root) => Err(SftpError::permission_denied(
"Symlink target outside allowed directory",
)),
_ => Ok(()),
}
}
/// Convert file metadata to SFTP FileAttributes.
fn metadata_to_attrs(metadata: &std::fs::Metadata) -> FileAttributes {
FileAttributes {
size: Some(metadata.len()),
uid: Some(metadata.uid()),
user: None,
gid: Some(metadata.gid()),
group: None,
permissions: Some(metadata.permissions().mode()),
atime: Some(
metadata
.accessed()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs() as u32)
.unwrap_or(0),
),
mtime: Some(
metadata
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs() as u32)
.unwrap_or(0),
),
}
}
/// Build a long name string for directory listing (like "ls -l").
fn build_longname(filename: &str, attrs: &FileAttributes) -> String {
let perms = attrs.permissions.unwrap_or(0);
let is_dir = (perms & 0o40000) != 0;
let is_link = (perms & 0o120000) == 0o120000;
let file_type = if is_link {
'l'
} else if is_dir {
'd'
} else {
'-'
};
let perm_str = format!(
"{}{}{}{}{}{}{}{}{}",
if perms & 0o400 != 0 { 'r' } else { '-' },
if perms & 0o200 != 0 { 'w' } else { '-' },
if perms & 0o100 != 0 { 'x' } else { '-' },
if perms & 0o040 != 0 { 'r' } else { '-' },
if perms & 0o020 != 0 { 'w' } else { '-' },
if perms & 0o010 != 0 { 'x' } else { '-' },
if perms & 0o004 != 0 { 'r' } else { '-' },
if perms & 0o002 != 0 { 'w' } else { '-' },
if perms & 0o001 != 0 { 'x' } else { '-' },
);
let size = attrs.size.unwrap_or(0);
let uid = attrs.uid.unwrap_or(0);
let gid = attrs.gid.unwrap_or(0);
format!("{file_type}{perm_str} 1 {uid:5} {gid:5} {size:10} Jan 1 00:00 {filename}")
}
}
impl russh_sftp::server::Handler for SftpHandler {
type Error = SftpError;
fn unimplemented(&self) -> Self::Error {
SftpError::not_supported()
}
/// Handle SFTP version negotiation.
fn init(
&mut self,
version: u32,
_extensions: HashMap<String, String>,
) -> impl std::future::Future<Output = Result<Version, Self::Error>> + Send {
tracing::info!(
user = %self.user_info.username,
version = version,
"SFTP session initialized"
);
async move { Ok(Version::new()) }
}
/// Open a file.
fn open(
&mut self,
id: u32,
filename: String,
pflags: OpenFlags,
_attrs: FileAttributes,
) -> impl std::future::Future<Output = Result<Handle, Self::Error>> + Send {
let path_result = self.resolve_path(&filename);
let handle_id = self.new_handle();
let handles = Arc::clone(&self.handles);
let root_dir = self.root_dir.clone();
let cwd = self.cwd.clone();
tracing::debug!(
user = %self.user_info.username,
path = %filename,
flags = ?pflags,
handle = %handle_id,
"Opening file"
);
async move {
// Check handle limit before acquiring lock
{
let handles_guard = handles.lock().await;
if handles_guard.len() >= MAX_HANDLES {
return Err(SftpError::new(StatusCode::Failure, "Too many open handles"));
}
}
let path = path_result?;
// Check if the path is a symlink and validate the target
let metadata = fs::symlink_metadata(&path).await;
if let Ok(meta) = metadata
&& meta.is_symlink()
{
// Follow the symlink and ensure target is within root (if any)
let target = fs::read_link(&path).await?;
let resolved_target = if target.is_absolute() {
target
} else {
// Resolve relative symlink from the symlink's directory.
// Fall back to cwd when the parent isn't accessible.
let base = path.parent().unwrap_or(&cwd);
let joined = base.join(&target);
// Use tokio's canonicalize for async operation
tokio::fs::canonicalize(&joined).await.unwrap_or(target)
};
if let Err(e) =
SftpHandler::ensure_target_in_root(root_dir.as_deref(), &resolved_target)
{
tracing::warn!(
path = %path.display(),
target = %resolved_target.display(),
"Symlink target outside root directory"
);
return Err(e);
}
}
// Build open options from flags
let mut opts = OpenOptions::new();
if pflags.contains(OpenFlags::READ) {
opts.read(true);
}
if pflags.contains(OpenFlags::WRITE) {
opts.write(true);
}
if pflags.contains(OpenFlags::CREATE) {
opts.create(true);
}
if pflags.contains(OpenFlags::TRUNCATE) {
opts.truncate(true);
}
if pflags.contains(OpenFlags::APPEND) {
opts.append(true);
}
if pflags.contains(OpenFlags::EXCLUDE) {
opts.create_new(true);
}
let file = opts.open(&path).await?;
// Store the handle
handles.lock().await.insert(
handle_id.clone(),
OpenHandle::File {
file,
path,
flags: pflags,
},
);
Ok(Handle {
id,
handle: handle_id,
})
}
}
/// Read data from an open file.
fn read(
&mut self,
id: u32,
handle: String,
offset: u64,
len: u32,
) -> impl std::future::Future<Output = Result<Data, Self::Error>> + Send {
let handles = Arc::clone(&self.handles);
async move {
// Cap read size to prevent memory exhaustion
let capped_len = len.min(MAX_READ_SIZE);
if len > MAX_READ_SIZE {
tracing::warn!(
handle = %handle,
requested = len,
capped = capped_len,
"Read size exceeds maximum, capping to MAX_READ_SIZE"
);
}
let mut handles_guard = handles.lock().await;
let handle_entry = handles_guard.get_mut(&handle);
let file = match handle_entry {
Some(OpenHandle::File { file, .. }) => file,
_ => return Err(SftpError::invalid_handle()),
};
// Seek to offset
file.seek(SeekFrom::Start(offset)).await?;
// Read data
let mut buffer = vec![0u8; capped_len as usize];
let bytes_read = file.read(&mut buffer).await?;
if bytes_read == 0 {
return Err(SftpError::eof());
}
buffer.truncate(bytes_read);
tracing::trace!(
handle = %handle,
offset = offset,
requested = len,
read = bytes_read,
"Read data from file"
);
Ok(Data { id, data: buffer })
}
}
/// Write data to an open file.
fn write(
&mut self,
id: u32,
handle: String,
offset: u64,
data: Vec<u8>,
) -> impl std::future::Future<Output = Result<Status, Self::Error>> + Send {
let handles = Arc::clone(&self.handles);
let data_len = data.len();
async move {
let mut handles_guard = handles.lock().await;
let handle_entry = handles_guard.get_mut(&handle);
let file = match handle_entry {
Some(OpenHandle::File { file, .. }) => file,
_ => return Err(SftpError::invalid_handle()),
};
// Seek to offset
file.seek(SeekFrom::Start(offset)).await?;
// Write data
file.write_all(&data).await?;
tracing::trace!(
handle = %handle,
offset = offset,
written = data_len,
"Wrote data to file"
);
Ok(Status {
id,
status_code: StatusCode::Ok,
error_message: String::new(),
language_tag: "en".to_string(),
})
}
}
/// Close an open file or directory handle.
fn close(
&mut self,
id: u32,
handle: String,
) -> impl std::future::Future<Output = Result<Status, Self::Error>> + Send {
let handles = Arc::clone(&self.handles);
let user = self.user_info.username.clone();
tracing::debug!(
user = %user,
handle = %handle,
"Closing handle"
);
async move {
let removed = handles.lock().await.remove(&handle);
match removed {
Some(_) => Ok(Status {
id,
status_code: StatusCode::Ok,
error_message: String::new(),
language_tag: "en".to_string(),
}),
None => Err(SftpError::invalid_handle()),
}
}
}
/// Open a directory for listing.
fn opendir(
&mut self,
id: u32,
path: String,
) -> impl std::future::Future<Output = Result<Handle, Self::Error>> + Send {
let resolved = self.resolve_path(&path);
let handle_id = self.new_handle();
let handles = Arc::clone(&self.handles);
let root_dir = self.root_dir.clone();
tracing::debug!(
user = %self.user_info.username,
path = %path,
handle = %handle_id,
"Opening directory"
);
async move {
// Check handle limit before acquiring lock
{
let handles_guard = handles.lock().await;
if handles_guard.len() >= MAX_HANDLES {
return Err(SftpError::new(StatusCode::Failure, "Too many open handles"));
}
}
let resolved_path = resolved?;
// Read directory entries
let mut entries = Vec::new();
let mut read_dir = fs::read_dir(&resolved_path).await?;
// Add "." entry
if let Ok(meta) = fs::symlink_metadata(&resolved_path).await {
entries.push(DirEntryInfo {
filename: ".".to_string(),
attrs: SftpHandler::metadata_to_attrs(&meta),
});
}
// Add ".." entry. With chroot, only include the parent if it
// remains inside the chroot; otherwise reuse the directory's own
// metadata so the listing doesn't leak the chroot boundary.
// Without chroot, fall back to ordinary parent semantics.
if let Some(parent) = resolved_path.parent() {
let parent_inside_root = root_dir
.as_ref()
.map(|root| parent.starts_with(root))
.unwrap_or(true);
let at_root_boundary = root_dir
.as_ref()
.map(|root| resolved_path == *root)
.unwrap_or(false);
if parent_inside_root {
if let Ok(meta) = fs::symlink_metadata(parent).await {
entries.push(DirEntryInfo {
filename: "..".to_string(),
attrs: SftpHandler::metadata_to_attrs(&meta),
});
}
} else if at_root_boundary {
// At chroot boundary, mirror the directory's own metadata.
if let Ok(meta) = fs::symlink_metadata(&resolved_path).await {
entries.push(DirEntryInfo {
filename: "..".to_string(),
attrs: SftpHandler::metadata_to_attrs(&meta),
});
}
}
}
// Read actual entries
while let Ok(Some(entry)) = read_dir.next_entry().await {
if let Ok(meta) = entry.metadata().await {
entries.push(DirEntryInfo {
filename: entry.file_name().to_string_lossy().to_string(),
attrs: SftpHandler::metadata_to_attrs(&meta),
});
}
}
// Store the directory handle
handles.lock().await.insert(
handle_id.clone(),
OpenHandle::Dir {
path: resolved_path,
entries,
position: 0,
},
);
Ok(Handle {
id,
handle: handle_id,
})
}
}
/// Read entries from an open directory.
fn readdir(
&mut self,
id: u32,
handle: String,
) -> impl std::future::Future<Output = Result<Name, Self::Error>> + Send {
let handles = Arc::clone(&self.handles);
async move {
let mut handles_guard = handles.lock().await;
let handle_entry = handles_guard.get_mut(&handle);
let (entries, position) = match handle_entry {
Some(OpenHandle::Dir {
entries, position, ..
}) => (entries, position),
_ => return Err(SftpError::invalid_handle()),
};
// Check if we've read all entries
if *position >= entries.len() {
return Err(SftpError::eof());
}
// Return a batch of entries (up to 100 at a time)
const BATCH_SIZE: usize = 100;
let end = (*position + BATCH_SIZE).min(entries.len());
let files: Vec<_> = entries[*position..end]
.iter()
.map(|e| {
let longname = SftpHandler::build_longname(&e.filename, &e.attrs);
russh_sftp::protocol::File {
filename: e.filename.clone(),
longname,
attrs: e.attrs.clone(),
}
})
.collect();
let remaining = entries.len() - end;
*position = end;
tracing::trace!(
handle = %handle,
returned = files.len(),
remaining = remaining,
"Read directory entries"
);
Ok(Name { id, files })
}
}
/// Get file attributes by path (follows symlinks).
fn stat(
&mut self,
id: u32,
path: String,
) -> impl std::future::Future<Output = Result<Attrs, Self::Error>> + Send {
let resolved = self.resolve_path(&path);
let root_dir = self.root_dir.clone();
let cwd = self.cwd.clone();
async move {
let path = resolved?;
// Use symlink_metadata first to check if it's a symlink
let symlink_meta = fs::symlink_metadata(&path).await?;
if symlink_meta.is_symlink() {
// Follow the symlink and validate the target is within root
// (when chroot is enabled).
let target = fs::read_link(&path).await?;
let resolved_target = if target.is_absolute() {
target
} else {
let base = path.parent().unwrap_or(&cwd);
let joined = base.join(&target);
tokio::fs::canonicalize(&joined).await.unwrap_or(target)
};