-
-
Notifications
You must be signed in to change notification settings - Fork 142
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
Pageant: Implement NamedPipes-based stream #472
Open
amtelekom
wants to merge
1
commit into
Eugeny:main
Choose a base branch
from
amtelekom:pageant-namedpipes
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,174 @@ | ||
use std::io::IoSlice; | ||
use std::pin::Pin; | ||
use std::task::{Context, Poll}; | ||
use std::time::Duration; | ||
|
||
use delegate::delegate; | ||
use log::debug; | ||
use sha2::{Digest, Sha256}; | ||
use thiserror::Error; | ||
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; | ||
use tokio::net::windows::named_pipe::{ClientOptions, NamedPipeClient}; | ||
use windows::Win32::Foundation::ERROR_PIPE_BUSY; | ||
use windows::Win32::Security::Authentication::Identity::{GetUserNameExA, NameUserPrincipal}; | ||
use windows::Win32::Security::Cryptography::{ | ||
CryptProtectMemory, CRYPTPROTECTMEMORY_BLOCK_SIZE, CRYPTPROTECTMEMORY_CROSS_PROCESS, | ||
}; | ||
use windows_strings::PSTR; | ||
|
||
#[derive(Error, Debug)] | ||
pub enum Error { | ||
#[error("Pageant not found")] | ||
NotFound, | ||
|
||
#[error("Buffer overflow")] | ||
Overflow, | ||
|
||
#[error("No response from Pageant")] | ||
NoResponse, | ||
|
||
#[error("Invalid Username")] | ||
InvalidUsername, | ||
|
||
#[error(transparent)] | ||
WindowsError(#[from] windows::core::Error), | ||
|
||
#[error(transparent)] | ||
IoError(#[from] std::io::Error), | ||
} | ||
|
||
impl Error { | ||
fn from_win32() -> Self { | ||
Self::WindowsError(windows::core::Error::from_win32()) | ||
} | ||
} | ||
|
||
/// Pageant transport stream. Implements [AsyncRead] and [AsyncWrite]. | ||
pub struct PageantStream { | ||
stream: NamedPipeClient, | ||
} | ||
|
||
impl PageantStream { | ||
pub async fn new() -> Result<Self, Error> { | ||
let pipe_name = Self::determine_pipe_name()?; | ||
debug!("Opening pipe '{}'", pipe_name); | ||
let stream = loop { | ||
match ClientOptions::new().open(&pipe_name) { | ||
Ok(client) => break client, | ||
Err(e) if e.raw_os_error() == Some(ERROR_PIPE_BUSY.0 as i32) => (), | ||
Err(e) => return Err(e.into()), | ||
} | ||
|
||
tokio::time::sleep(Duration::from_millis(50)).await; | ||
}; | ||
|
||
Ok(Self { stream }) | ||
} | ||
|
||
fn determine_pipe_name() -> Result<String, Error> { | ||
let username = Self::get_username()?; | ||
let suffix = Self::capi_obfuscate_string("Pageant")?; | ||
Ok(format!("\\\\.\\pipe\\pageant.{username}.{suffix}")) | ||
} | ||
|
||
fn get_username() -> Result<String, Error> { | ||
unsafe { | ||
let mut name_length = 0; | ||
|
||
// don't check result on this, always returns ERROR_MORE_DATA | ||
GetUserNameExA(NameUserPrincipal, None, &mut name_length); | ||
|
||
let mut name_buf = vec![0u8; name_length as usize]; | ||
|
||
if !GetUserNameExA( | ||
NameUserPrincipal, | ||
Some(PSTR(name_buf.as_mut_ptr())), | ||
&mut name_length, | ||
) { | ||
// Pageant falls back to GetUserNameA here, | ||
// but as far as I can tell, all Versions of Windows supported by Rust today | ||
// should be able to answer the UserNameEx request - the comments in Pageant source | ||
// point to Windows XP and earlier compatibility... | ||
return Err(Error::from_win32()); | ||
} | ||
|
||
//remove terminating null | ||
if let Some(0) = name_buf.pop() { | ||
let mut name = String::from_utf8(name_buf).map_err(|_| Error::InvalidUsername)?; | ||
if let Some(at_index) = name.find('@') { | ||
name.drain(at_index..); | ||
} | ||
Ok(name) | ||
} else { | ||
Err(Error::InvalidUsername) | ||
} | ||
} | ||
} | ||
|
||
fn capi_obfuscate_string(input: &str) -> Result<String, Error> { | ||
let mut cryptlen = input.len() + 1; | ||
cryptlen = cryptlen.next_multiple_of(CRYPTPROTECTMEMORY_BLOCK_SIZE as usize); | ||
let mut cryptdata = vec![0u8; cryptlen]; | ||
|
||
// copy cleartext into crypt buffer: | ||
cryptdata | ||
.iter_mut() | ||
.zip(input.as_bytes()) | ||
.for_each(|(c, i)| *c = *i); | ||
// (since the buffer is initialized to 0 and always at least 1 longer than the input, | ||
// we don't need to worry about terminating the string) | ||
|
||
unsafe { | ||
// Errors are explicitly ignored: | ||
let _ = CryptProtectMemory( | ||
cryptdata.as_mut_ptr() as *mut _, | ||
cryptlen as u32, | ||
CRYPTPROTECTMEMORY_CROSS_PROCESS, | ||
); | ||
} | ||
|
||
let mut hasher = Sha256::new(); | ||
hasher.update((cryptdata.len() as u32).to_be_bytes()); | ||
hasher.update(&cryptdata); | ||
Ok(format!("{:x}", hasher.finalize())) | ||
} | ||
} | ||
|
||
impl AsyncRead for PageantStream { | ||
delegate! { | ||
to Pin::new(&mut self.stream) { | ||
fn poll_read( | ||
mut self: Pin<&mut Self>, | ||
cx: &mut Context<'_>, | ||
buf: &mut ReadBuf<'_>, | ||
) -> Poll<Result<(), std::io::Error>>; | ||
|
||
} | ||
} | ||
} | ||
|
||
impl AsyncWrite for PageantStream { | ||
delegate! { | ||
to Pin::new(&mut self.stream) { | ||
fn poll_write( | ||
mut self: Pin<&mut Self>, | ||
cx: &mut Context<'_>, | ||
buf: &[u8], | ||
) -> Poll<Result<usize, std::io::Error>>; | ||
|
||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), std::io::Error>>; | ||
|
||
fn poll_write_vectored( | ||
mut self: Pin<&mut Self>, | ||
cx: &mut Context<'_>, | ||
bufs: &[IoSlice<'_>], | ||
) -> Poll<Result<usize, std::io::Error>>; | ||
|
||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), std::io::Error>>; | ||
} | ||
|
||
to Pin::new(&self.stream) { | ||
fn is_write_vectored(&self) -> bool; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks a lot!
The two implementations should definitely not be mutually exclusive. They could be both exported together, with neither being a "default", e.g.:
I'd really like to see a common trait for both of them since it would be weird to have to choose a specific implementation at compile time unless you know exactly which PuTTY version to expect in advance
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is a cost to maintaining both and why would one want to run an old pre-2020 Putty Pageant with potential security bugs in 2025? I think a compile time decision is good enough, and I would even evaluate to eventually remove the WM_COPYDATA method to simplify maintenance.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Because in reality, when you're writing an SSH client, you don't control what version of Putty the user might have installed.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P.S. I don't mind doing it myself, it will just take a bit until I have time to work on it.