Medlar/crates/core/tests/ftp/sshd.rs
2026-11-25 07:45:25 -06:00

233 lines
8.8 KiB
Rust

//! A small SFTP server with faults, on loopback.
use russh::keys::ssh_key::private::{Ed25519Keypair, KeypairData};
use russh::keys::{PrivateKey, PublicKey};
use russh::server::{Auth, ChannelOpenHandle, Msg, Response, Session, VerifiedPublicKey};
use russh::{Channel, ChannelId, MethodKind, MethodSet};
use russh_sftp::protocol::{self, FileAttributes, OpenFlags, SftpHandle, SftpString, Status, StatusCode};
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::net::TcpListener;
#[derive(Clone)]
pub struct Knobs {
pub files: HashMap<Vec<u8>, Arc<Vec<u8>>>,
pub mtime: u32,
pub password: String,
/// Asks for the password as a question only.
pub asks: bool,
pub key: Option<PublicKey>,
/// Gives at most so much in one go.
pub most: usize,
pub pause: Duration,
/// So many connections are dropped after so many reads.
pub cuts: usize,
pub cut_after: usize,
}
pub struct Sshd {
pub addr: SocketAddr,
pub state: Arc<Inner>,
}
pub struct Inner {
pub knobs: Mutex<Knobs>,
host: Mutex<PrivateKey>,
pub sent: AtomicU64,
pub connections: AtomicUsize,
/// That came here.
pub passwords: Mutex<Vec<String>>,
}
pub fn key(seed: u8) -> PrivateKey {
PrivateKey::new(KeypairData::Ed25519(Ed25519Keypair::from_seed(&[seed; 32])), "").unwrap()
}
impl Sshd {
pub async fn start(data: &[u8]) -> Sshd {
let knobs = Knobs {
files: HashMap::from([(b"/pub/f.bin".to_vec(), Arc::new(data.to_vec()))]),
mtime: 1_700_000_000,
password: "right".into(),
asks: false,
key: None,
most: usize::MAX,
pause: Duration::ZERO,
cuts: 0,
cut_after: 0,
};
let state = Arc::new(Inner {
knobs: Mutex::new(knobs),
host: Mutex::new(key(1)),
sent: AtomicU64::new(0),
connections: AtomicUsize::new(0),
passwords: Mutex::default(),
});
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let (addr, inner) = (listener.local_addr().unwrap(), state.clone());
tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
inner.connections.fetch_add(1, SeqCst);
let config = russh::server::Config {
keys: vec![inner.host.lock().unwrap().clone()],
auth_rejection_time: Duration::ZERO,
..Default::default()
};
let ssh = Ssh { inner: inner.clone(), channels: HashMap::new() };
tokio::spawn(async move {
if let Ok(session) = russh::server::run_stream(Arc::new(config), stream, ssh).await {
let _ = session.await;
}
});
}
});
Sshd { addr, state }
}
pub fn set(&self, change: impl FnOnce(&mut Knobs)) {
change(&mut self.state.knobs.lock().unwrap());
}
pub fn set_host_key(&self, seed: u8) {
*self.state.host.lock().unwrap() = key(seed);
}
pub fn sent(&self) -> u64 {
self.state.sent.load(SeqCst)
}
}
struct Ssh {
inner: Arc<Inner>,
channels: HashMap<ChannelId, Channel<Msg>>,
}
fn no(method: MethodKind) -> Auth {
Auth::Reject { proceed_with_methods: Some(MethodSet::from(&[method][..])), partial_success: false }
}
impl russh::server::Handler for Ssh {
type Error = russh::Error;
async fn auth_password(&mut self, _: &str, password: &str) -> Result<Auth, russh::Error> {
self.inner.passwords.lock().unwrap().push(password.into());
let k = self.inner.knobs.lock().unwrap().clone();
if k.asks {
return Ok(no(MethodKind::KeyboardInteractive));
}
Ok(if k.password == password { Auth::Accept } else { no(MethodKind::Password) })
}
async fn auth_keyboard_interactive<'a>(&'a mut self, _: &str, _: &str, response: Option<Response<'a>>) -> Result<Auth, russh::Error> {
let Some(mut response) = response else {
let prompts = vec![("Password: ".into(), false)].into();
return Ok(Auth::Partial { name: "".into(), instructions: "".into(), prompts });
};
let k = self.inner.knobs.lock().unwrap().clone();
let fits = response.next().is_some_and(|r| &r[..] == k.password.as_bytes());
Ok(if fits { Auth::Accept } else { no(MethodKind::Password) })
}
async fn auth_publickey(&mut self, _: &str, key: VerifiedPublicKey<'_>) -> Result<Auth, russh::Error> {
let k = self.inner.knobs.lock().unwrap().clone();
let fits = k.key.is_some_and(|k| k.key_data() == key.public_key.key_data());
Ok(if fits { Auth::Accept } else { no(MethodKind::Password) })
}
async fn channel_open_session(&mut self, channel: Channel<Msg>, reply: ChannelOpenHandle, _: &mut Session) -> Result<(), russh::Error> {
self.channels.insert(channel.id(), channel);
reply.accept().await;
Ok(())
}
async fn subsystem_request(&mut self, id: ChannelId, name: &str, session: &mut Session) -> Result<(), russh::Error> {
assert_eq!(name, "sftp");
session.channel_success(id)?;
let channel = self.channels.remove(&id).unwrap();
russh_sftp::server::run(channel.into_stream(), Files { inner: self.inner.clone(), handle: session.handle(), reads: 0, listed: false }).await;
Ok(())
}
}
struct Files {
inner: Arc<Inner>,
handle: russh::server::Handle,
reads: usize,
listed: bool,
}
impl Files {
fn attrs(&self, path: &[u8]) -> Result<FileAttributes, StatusCode> {
let k = self.inner.knobs.lock().unwrap();
let size = k.files.get(path).map(|f| f.len() as u64);
let mode = match (path, size) {
(b"/pub", _) => 0o040755,
(_, Some(_)) => 0o100644,
_ => return Err(StatusCode::NoSuchFile),
};
Ok(FileAttributes { size, permissions: Some(mode), mtime: Some(k.mtime), atime: Some(k.mtime), ..FileAttributes::empty() })
}
}
impl russh_sftp::server::Handler for Files {
type Error = StatusCode;
fn unimplemented(&self) -> StatusCode {
StatusCode::OpUnsupported
}
async fn stat(&mut self, id: u32, path: SftpString) -> Result<protocol::Attrs, StatusCode> {
Ok(protocol::Attrs { id, attrs: self.attrs(&path)? })
}
async fn open(&mut self, id: u32, path: SftpString, _: OpenFlags, _: FileAttributes) -> Result<protocol::Handle, StatusCode> {
if path.ends_with(b"secret") {
return Err(StatusCode::PermissionDenied);
}
self.attrs(&path)?;
Ok(protocol::Handle { id, handle: path.into() })
}
async fn close(&mut self, id: u32, _: SftpHandle) -> Result<Status, StatusCode> {
Ok(Status { id, status_code: StatusCode::Ok, error_message: String::new(), language_tag: String::new() })
}
async fn read(&mut self, id: u32, handle: SftpHandle, at: u64, len: u32) -> Result<protocol::Data, StatusCode> {
self.reads += 1;
let k = self.inner.knobs.lock().unwrap().clone();
if k.cuts > 0 && self.reads == k.cut_after {
self.inner.knobs.lock().unwrap().cuts -= 1;
let _ = self.handle.disconnect(russh::Disconnect::ByApplication, String::new(), String::new()).await;
return Err(StatusCode::ConnectionLost);
}
tokio::time::sleep(k.pause).await;
let file = k.files.get(handle.as_bytes()).ok_or(StatusCode::NoSuchFile)?;
if at >= file.len() as u64 {
return Err(StatusCode::Eof);
}
let rest = &file[at as usize..];
let data = rest[..rest.len().min(len as usize).min(k.most)].to_vec();
self.inner.sent.fetch_add(data.len() as u64, SeqCst);
Ok(protocol::Data { id, data })
}
async fn opendir(&mut self, id: u32, path: SftpString) -> Result<protocol::Handle, StatusCode> {
self.listed = false;
if &path[..] == b"/pub" || &path[..] == b"/pub/" { Ok(protocol::Handle { id, handle: path.into() }) } else { Err(StatusCode::NoSuchFile) }
}
async fn readdir(&mut self, id: u32, _: SftpHandle) -> Result<protocol::Name, StatusCode> {
if std::mem::replace(&mut self.listed, true) {
return Err(StatusCode::Eof);
}
let file = |name: &[u8], mode: u32, size| {
let attrs = FileAttributes { size: Some(size), permissions: Some(mode), mtime: Some(1000), ..FileAttributes::empty() };
protocol::File::new(name.to_vec(), attrs)
};
let files = vec![file(b".", 0o040755, 0), file(b"f.bin", 0o100644, 9), file(b"caf\xe9", 0o040755, 4096), file(b"l", 0o120777, 1)];
Ok(protocol::Name { id, files })
}
}