How to serve a basic shell #2
Closed this issue · 10 comments
You need to tokio::spawn
both copy tasks instead of joining them, otherwise channel_open_session
never completes.
Ideally you also want to hold on to the Channel
first and wait until you see a Handler::shell_request
for it as the client might not be ready to receive output until then.
For tokio::spawn, the channel lifetime is too short. Any way to prevent this?
You need to move your cin
into the closure
tokio::spawn(async move {
let cin = cin;
tokio::io::copy...
}});
Sorry, I can't help with generic Rust issues. You can post your entire code instead of a screenshot and maybe I or somebody else could check it out later.
here is my code:
use std::collections::HashMap;
use std::sync::Arc;
use async_trait::async_trait;
use russh::server::{Msg, Server as _, Session};
use russh::*;
use russh_keys::*;
use tokio::sync::Mutex;
use std::fs::File;
use std::io::Read;
use tokio::net::TcpListener;
use tokio::process::Command;
use std::process::Stdio;
#[tokio::main]
async fn main() {
env_logger::builder()
.filter_level(log::LevelFilter::Debug)
.init();
// let skey = russh_keys::key::KeyPair::generate_ed25519().unwrap();
// let mut buffer = File::create("id_ed25519").unwrap();
// encode_pkcs8_pem(&skey, buffer).unwrap();
let mut buffer = File::open("id_ed25519").unwrap();
let mut file_content = String::new();
buffer.read_to_string(&mut file_content).unwrap();
let skey = decode_secret_key(file_content.as_mut_str(), None).unwrap();
let config = russh::server::Config {
inactivity_timeout: Some(std::time::Duration::from_secs(3600)),
auth_rejection_time: std::time::Duration::from_secs(3),
auth_rejection_time_initial: Some(std::time::Duration::from_secs(0)),
keys: vec![skey],
..Default::default()
};
let config = Arc::new(config);
let mut sh = Server {
clients: Arc::new(Mutex::new(HashMap::new())),
id: 0,
};
// sh.run_on_address(config, ("127.0.0.1", 2222)).await.unwrap();
let socket = TcpListener::bind(("127.0.0.1", 2222)).await.unwrap();
sh.run_on_socket(config, &socket).await.unwrap()
}
#[derive(Clone)]
struct Server {
clients: Arc<Mutex<HashMap<(usize, ChannelId), russh::server::Handle>>>,
id: usize,
}
impl Server {
async fn post(&mut self, data: CryptoVec) {
let mut clients = self.clients.lock().await;
for ((id, channel), ref mut s) in clients.iter_mut() {
if *id != self.id {
let _ = s.data(*channel, data.clone()).await;
}
}
}
}
impl server::Server for Server {
type Handler = Self;
fn new_client(&mut self, _: Option<std::net::SocketAddr>) -> Self {
let s = self.clone();
self.id += 1;
s
}
}
#[async_trait]
impl server::Handler for Server {
type Error = anyhow::Error;
async fn channel_open_session(
&mut self,
mut channel: Channel<Msg>,
session: &mut Session,
) -> Result<bool, Self::Error> {
self.shell_request(channel.id(), session).await.unwrap();
let cin = channel.make_writer();
let cout = channel.make_reader();
let cmd = Command::new("/bin/sh").stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().unwrap();
tokio::spawn(async {
let mut cin = cin;
let mut stdout = cmd.stdout.unwrap();
tokio::io::copy(&mut stdout, &mut cin).await.unwrap();
});
tokio::spawn(async {
let mut cout = cout;
let mut stdin = cmd.stdin.unwrap();
tokio::io::copy(&mut cout, &mut stdin).await.unwrap();
});
Ok(true)
}
async fn auth_publickey(
&mut self,
_: &str,
_: &key::PublicKey,
) -> Result<server::Auth, Self::Error> {
Ok(server::Auth::Accept)
}
async fn data(
&mut self,
channel: ChannelId,
data: &[u8],
session: &mut Session,
) -> Result<(), Self::Error> {
let data = CryptoVec::from(format!("Got data: {}\r\n", String::from_utf8_lossy(data)));
self.post(data.clone()).await;
session.data(channel, data);
Ok(())
}
async fn tcpip_forward(
&mut self,
address: &str,
port: &mut u32,
session: &mut Session,
) -> Result<bool, Self::Error> {
let handle = session.handle();
let address = address.to_string();
let port = *port;
tokio::spawn(async move {
let channel = handle
.channel_open_forwarded_tcpip(address, port, "1.2.3.4", 1234)
.await
.unwrap();
let _ = channel.data(&b"Hello from a forwarded port"[..]).await;
let _ = channel.eof().await;
});
Ok(true)
}
}
Sorry, I can't help with generic Rust issues. You can post your entire code instead of a screenshot and maybe I or somebody else could check it out later.
is there somewhere and example where it is working, is there documentation on how some would do that?
It is indeed tricky to get the lifetimes to work right in your case - in particular because the return value of make_reader
implicitly references Channel
.
This works though because the lifetime of the Reader is scoped to the lifetime of the Channel here:
async fn channel_open_session(
&mut self,
channel: Channel<Msg>,
session: &mut Session,
) -> Result<bool, Self::Error> {
self.shell_request(channel.id(), session).await.unwrap();
let cmd = Command::new("/bin/sh")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.unwrap();
let mut stdin = cmd.stdin.unwrap();
let mut stdout = cmd.stdout.unwrap();
let mut channel = channel;
let mut cin = channel.make_writer();
tokio::spawn(async move {
tokio::io::copy(&mut stdout, &mut cin).await.unwrap();
});
tokio::spawn(async move {
let mut cout = channel.make_reader();
tokio::io::copy(&mut cout, &mut stdin).await.unwrap();
});
Ok(true)
}
GREAT! It works, thanks a lot.