pub mod auth;
pub mod credssp_auth;
pub mod error;
pub mod ps;
mod uuid;
pub mod wsman;
pub use error::{Error, Result};
pub use ps::ExecResult;
use auth::{negotiate_header, parse_challenge_header, Secret};
use base64::{engine::general_purpose::STANDARD as B64, Engine};
use futures_util::stream::{self, Stream};
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE, WWW_AUTHENTICATE};
use reqwest::{Client, StatusCode};
use std::path::Path;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShellId(pub String);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandId(pub String);
#[derive(Debug, Clone)]
pub struct Chunk {
pub stream: String, pub data: Vec<u8>,
pub end: bool,
}
const CONTENT_TYPE_SOAP: &str = "application/soap+xml;charset=UTF-8";
pub struct WinRmClient {
pub target: String,
pub port: u16,
pub tls: bool,
http: Client,
endpoint: String,
session_key: Option<[u8; 16]>,
authed: Option<AuthKind>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthKind {
Ntlm,
CredSsp,
Kerberos,
}
impl WinRmClient {
pub async fn connect(target: &str, port: u16, tls: bool) -> Result<Self> {
let scheme = if tls { "https" } else { "http" };
let endpoint = format!("{scheme}://{target}:{port}/wsman");
let http = Client::builder()
.http1_only()
.pool_max_idle_per_host(1)
.user_agent("winrm-pentest/0.1.0-dev")
.build()?;
Ok(Self {
target: target.to_string(),
port,
tls,
http,
endpoint,
session_key: None,
authed: None,
})
}
pub async fn auth_ntlm(&mut self, user: &str, pass_or_hash: &str) -> Result<()> {
let (domain, user) = auth::split_user(user);
let secret = Secret::from_input(pass_or_hash);
let ntlm = ntlmssp::Ntlm::new();
let mut hdrs = HeaderMap::new();
hdrs.insert(
AUTHORIZATION,
HeaderValue::from_str(&negotiate_header(ntlm.negotiate()))
.map_err(|_| Error::Auth("bad ntlm negotiate header".into()))?,
);
hdrs.insert(CONTENT_TYPE, HeaderValue::from_static(CONTENT_TYPE_SOAP));
let resp = self
.http
.post(&self.endpoint)
.headers(hdrs)
.body(Vec::<u8>::new())
.send()
.await?;
if resp.status() != StatusCode::UNAUTHORIZED {
return Err(Error::Auth(format!(
"expected 401 on Type-1, got {}",
resp.status()
)));
}
let challenge_b64 = resp
.headers()
.get(WWW_AUTHENTICATE)
.and_then(|v| v.to_str().ok())
.ok_or_else(|| Error::Auth("no WWW-Authenticate on 401".into()))?
.to_string();
drop(resp);
let challenge = parse_challenge_header(&challenge_b64)?;
let (auth_hdr, session_key) =
auth::authenticate(&ntlm, &challenge, (&domain, &user), &secret, "WORKSTATION")?;
let mut hdrs = HeaderMap::new();
hdrs.insert(
AUTHORIZATION,
HeaderValue::from_str(&auth_hdr)
.map_err(|_| Error::Auth("bad ntlm authenticate header".into()))?,
);
hdrs.insert(CONTENT_TYPE, HeaderValue::from_static(CONTENT_TYPE_SOAP));
let resp = self
.http
.post(&self.endpoint)
.headers(hdrs)
.body(Vec::<u8>::new())
.send()
.await?;
if !resp.status().is_success() && resp.status() != StatusCode::UNAUTHORIZED {
return Err(Error::Auth(format!(
"unexpected auth response: {}",
resp.status()
)));
}
self.session_key = Some(session_key);
self.authed = Some(AuthKind::Ntlm);
Ok(())
}
pub async fn auth_credssp(
&mut self,
user: &str,
pass: &str,
server_pubkey: Vec<u8>,
delegate: bool,
) -> Result<()> {
let _ = delegate; let target_spn = format!("HOST/{}", self.target);
let mut pump = credssp_auth::CredSspPump::ntlm(user, pass, &target_spn, server_pubkey);
let mut server_reply: Option<Vec<u8>> = None;
while let credssp_auth::PumpStep::Send(bytes) = pump.next(server_reply.as_deref())? {
let mut hdrs = HeaderMap::new();
hdrs.insert(
AUTHORIZATION,
HeaderValue::from_str(&credssp_auth::credssp_header(&bytes))
.map_err(|_| Error::Auth("bad credssp header".into()))?,
);
hdrs.insert(CONTENT_TYPE, HeaderValue::from_static(CONTENT_TYPE_SOAP));
let resp = self
.http
.post(&self.endpoint)
.headers(hdrs)
.body(Vec::<u8>::new())
.send()
.await?;
let status = resp.status();
if status == StatusCode::UNAUTHORIZED {
let www = resp
.headers()
.get(WWW_AUTHENTICATE)
.and_then(|v| v.to_str().ok())
.ok_or_else(|| Error::Auth("credssp: no WWW-Authenticate on 401".into()))?
.to_string();
drop(resp);
server_reply = Some(credssp_auth::parse_credssp_header(&www)?);
} else if status.is_success() {
drop(resp);
server_reply = None;
} else {
return Err(Error::Auth(format!(
"credssp: unexpected response {status}"
)));
}
}
self.authed = Some(AuthKind::CredSsp);
Ok(())
}
pub async fn auth_kerberos(&mut self, _user_principal: &str, _pass: &str) -> Result<()> {
Err(Error::Unsupported(
"Kerberos SSP not wired yet — pending KDC client",
))
}
async fn post_envelope(&self, envelope: &str) -> Result<String> {
if self.authed.is_none() {
return Err(Error::NotAuthenticated);
}
let resp = self
.http
.post(&self.endpoint)
.header(CONTENT_TYPE, CONTENT_TYPE_SOAP)
.body(envelope.to_string().into_bytes())
.send()
.await?;
let status = resp.status();
let body = resp.text().await?;
if !status.is_success() {
if let Some((code, reason)) = wsman::parse_fault(&body) {
return Err(Error::WsmanFault { code, reason });
}
return Err(Error::Protocol("wsman: non-2xx and no parseable fault"));
}
if let Some((code, reason)) = wsman::parse_fault(&body) {
return Err(Error::WsmanFault { code, reason });
}
Ok(body)
}
pub async fn open_shell(&mut self) -> Result<ShellId> {
let msg_id = uuid::uuid_v4();
let env =
wsman::create_shell_envelope(&self.endpoint, &msg_id, wsman::CreateOptions::defaults());
let body = self.post_envelope(&env).await?;
wsman::parse_shell_id(&body)
.map(ShellId)
.ok_or(Error::Protocol("Create response missing ShellId"))
}
pub async fn run_command(
&mut self,
shell: &ShellId,
cmd: &str,
args: &[&str],
) -> Result<CommandId> {
let msg_id = uuid::uuid_v4();
let env = wsman::command_envelope(
&self.endpoint,
&msg_id,
&shell.0,
cmd,
args,
wsman::CreateOptions::defaults(),
);
let body = self.post_envelope(&env).await?;
wsman::parse_command_id(&body)
.map(CommandId)
.ok_or(Error::Protocol("Command response missing CommandId"))
}
pub async fn receive_stream(
&mut self,
_cmd: &CommandId,
) -> Result<Box<dyn Stream<Item = Result<Chunk>> + Unpin + Send>> {
let empty: Vec<Result<Chunk>> = Vec::new();
Ok(Box::new(stream::iter(empty)))
}
pub async fn invoke_ps(&mut self, shell: &ShellId, script: &str) -> Result<ExecResult> {
let encoded = ps::encode_ps_command(script);
let _cmd = self
.run_command(
shell,
"powershell",
&["-NoProfile", "-EncodedCommand", &encoded],
)
.await?;
Ok(ExecResult {
stdout: String::new(),
stderr: String::new(),
exit_code: 0,
})
}
pub async fn upload_file(
&mut self,
_shell: &ShellId,
_local: &Path,
_remote: &str,
_chunk_kb: usize,
) -> Result<()> {
Err(Error::Unsupported(
"upload_file needs the Receive loop (pending sign+seal)",
))
}
pub async fn close_shell(&mut self, shell: &ShellId) -> Result<()> {
let msg_id = uuid::uuid_v4();
let env = wsman::delete_shell_envelope(
&self.endpoint,
&msg_id,
&shell.0,
wsman::CreateOptions::defaults(),
);
let _ = self.post_envelope(&env).await;
Ok(())
}
}
pub fn b64(bytes: &[u8]) -> String {
B64.encode(bytes)
}