Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Add ClientInfo type to ListeningSocket #61

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 61 additions & 24 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ thiserror = "1.0.58"
#uuid = { version = "1.8.0", features = ["v4"] }
subtle = { version = "2", default-features = false }

[target.'cfg(windows)'.dependencies.windows]
version = "0.54"
features = [
"Win32_Foundation",
"Win32_System_Pipes",
]

[features]
default = ["agent"]
codec = ["tokio-util"]
Expand Down
11 changes: 9 additions & 2 deletions examples/key_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use rsa::BigUint;
use sha1::Sha1;
#[cfg(windows)]
use ssh_agent_lib::agent::NamedPipeListener as Listener;
use ssh_agent_lib::agent::Session;
use ssh_agent_lib::agent::{ListeningSocket, Session};
use ssh_agent_lib::error::AgentError;
use ssh_agent_lib::proto::extension::{QueryResponse, RestrictDestination, SessionBind};
use ssh_agent_lib::proto::{
Expand Down Expand Up @@ -235,7 +235,14 @@ impl KeyStorageAgent {
}

impl Agent for KeyStorageAgent {
fn new_session(&mut self) -> impl Session {
fn new_session<S>(&mut self, socket: &S::Stream) -> impl Session
where
S: ListeningSocket + std::fmt::Debug + Send,
{
if let Ok(client_info) = S::client_info(socket) {
println!("New connection from client: {:?}", client_info);
}

KeyStorage {
identities: Arc::clone(&self.identities),
}
Expand Down
81 changes: 13 additions & 68 deletions src/agent.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
//! Traits for implementing custom SSH agents

pub mod listener;

use std::fmt;
use std::io;

use async_trait::async_trait;
use futures::{SinkExt, TryStreamExt};
use ssh_key::Signature;
use tokio::io::{AsyncRead, AsyncWrite};
#[cfg(windows)]
use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions};
use tokio::net::{TcpListener, TcpStream};
use tokio::net::TcpListener;
#[cfg(unix)]
use tokio::net::{UnixListener, UnixStream};
use tokio::net::UnixListener;
use tokio_util::codec::Framed;

pub use self::listener::*;
use super::error::AgentError;
use super::proto::message::{Request, Response};
use crate::codec::Codec;
Expand All @@ -27,65 +26,6 @@ use crate::proto::RemoveIdentity;
use crate::proto::SignRequest;
use crate::proto::SmartcardKey;

/// Type representing a socket that asynchronously returns a list of streams.
#[async_trait]
pub trait ListeningSocket {
/// Stream type that represents an accepted socket.
type Stream: fmt::Debug + AsyncRead + AsyncWrite + Send + Unpin + 'static;

/// Waits until a client connects and returns connected stream.
async fn accept(&mut self) -> io::Result<Self::Stream>;
}

#[cfg(unix)]
#[async_trait]
impl ListeningSocket for UnixListener {
type Stream = UnixStream;
async fn accept(&mut self) -> io::Result<Self::Stream> {
UnixListener::accept(self).await.map(|(s, _addr)| s)
}
}

#[async_trait]
impl ListeningSocket for TcpListener {
type Stream = TcpStream;
async fn accept(&mut self) -> io::Result<Self::Stream> {
TcpListener::accept(self).await.map(|(s, _addr)| s)
}
}

/// Listener for Windows Named Pipes.
#[cfg(windows)]
#[derive(Debug)]
pub struct NamedPipeListener(NamedPipeServer, std::ffi::OsString);

#[cfg(windows)]
impl NamedPipeListener {
/// Bind to a pipe path.
pub fn bind(pipe: impl Into<std::ffi::OsString>) -> std::io::Result<Self> {
let pipe = pipe.into();
Ok(NamedPipeListener(
ServerOptions::new()
.first_pipe_instance(true)
.create(&pipe)?,
pipe,
))
}
}

#[cfg(windows)]
#[async_trait]
impl ListeningSocket for NamedPipeListener {
type Stream = NamedPipeServer;
async fn accept(&mut self) -> io::Result<Self::Stream> {
self.0.connect().await?;
Ok(std::mem::replace(
&mut self.0,
ServerOptions::new().create(&self.1)?,
))
}
}

/// Represents one active SSH connection.
///
/// This type is implemented by agents that want to handle incoming SSH agent
Expand Down Expand Up @@ -253,7 +193,9 @@ where
#[async_trait]
pub trait Agent: 'static + Sync + Send + Sized {
/// Create new session object when a new socket is accepted.
fn new_session(&mut self) -> impl Session;
fn new_session<S>(&mut self, socket: &S::Stream) -> impl Session
where
S: ListeningSocket + fmt::Debug + Send;

/// Listen on a socket waiting for client connections.
async fn listen<S>(mut self, mut socket: S) -> Result<(), AgentError>
Expand All @@ -264,7 +206,7 @@ pub trait Agent: 'static + Sync + Send + Sized {
loop {
match socket.accept().await {
Ok(socket) => {
let session = self.new_session();
let session = self.new_session::<S>(&socket);
tokio::spawn(async move {
let adapter = Framed::new(socket, Codec::<Request, Response>::default());
if let Err(e) = handle_socket::<S>(session, adapter).await {
Expand Down Expand Up @@ -306,7 +248,10 @@ impl<T> Agent for T
where
T: Default + Session,
{
fn new_session(&mut self) -> impl Session {
fn new_session<S>(&mut self, _socket: &S::Stream) -> impl Session
where
S: ListeningSocket + fmt::Debug + Send,
{
Self::default()
}
}
Loading
Loading