Skip to main content

winrm_pentest/
lib.rs

1//! `winrm-pentest` — async WinRM 2.0 (WS-Management) client aimed at
2//! offensive-security workflows: NTLM/CredSSP auth, remote PowerShell shell
3//! creation, `-EncodedCommand` execution, streaming stdout, and SMB-free file
4//! upload via base64-chunked `<rsp:Send>`.
5//!
6//! # Status
7//!
8//! **Pre-alpha (0.1.0-dev).** Compile-clean skeleton with:
9//! * Byte-deterministic WSMan envelope builders for
10//!   Create / Command / Send / Receive / Signal / Delete
11//!   (see [`wsman`] — round-trip tested).
12//! * Full NTLM Negotiate/Challenge/Authenticate driver over HTTP
13//!   (via `ntlmssp` — no FFI, includes pass-the-hash), tested against a
14//!   canned Windows challenge.
15//! * PowerShell `-EncodedCommand` helpers, including a deflate-then-b64
16//!   payload for scripts that overflow the 512 KB envelope cap.
17//! * Public API surface for the whole client ([`WinRmClient`]) with
18//!   partial-impl bodies. Everything compiles; the pieces that need a live DC
19//!   for iteration return a clear `Error::Unsupported` rather than panicking.
20//!
21//! # NOT YET wired
22//!
23//! * HTTP sign+seal (`multipart/encrypted; protocol="application/HTTP-SPNEGO-session-encrypted"`).
24//!   Blocks WinRM over plaintext 5985 with the default `AllowUnencrypted=false`.
25//!   Use HTTPS (5986) meanwhile.
26//! * CredSSP transport — [`WinRmClient::auth_credssp`] drives the sibling
27//!   `credssp` crate's `CredSspClient` state machine over the HTTP auth pump
28//!   (`Authorization: CredSSP <b64(TSRequest)>` / `WWW-Authenticate: CredSSP …`).
29//!   NTLM path is wired end-to-end and tested against a mock listener. The
30//!   Kerberos SspKind is exposed via [`credssp_auth::CredSspPump::kerberos`] —
31//!   caller supplies a `ServiceTicket`; that same pump then feeds
32//!   `WinRmClient::auth_credssp`-style HTTP pumping (a top-level
33//!   `auth_kerberos_credssp` wrapper lands with the KDC transport in ms-kile).
34//!   WSMV message encryption over the sealed CredSSP channel is still open —
35//!   post-auth SOAP against a `AllowUnencrypted=false` target is rejected
36//!   until it lands.
37//! * Kerberos — same story, wire up via a picky-krb-based path later.
38//! * `receive_stream` returns an immediately-`Done` empty stream (real
39//!   streaming needs the sign+seal layer above). `upload_file` is currently
40//!   `Unsupported` for the same reason.
41//!
42//! # Minimal usage
43//!
44//! ```no_run
45//! # async fn demo() -> winrm_pentest::Result<()> {
46//! use winrm_pentest::WinRmClient;
47//!
48//! let mut cli = WinRmClient::connect("dc01.lab.local", 5986, true).await?;
49//! cli.auth_ntlm("LAB\\Administrator", "P@ssw0rd!").await?;
50//! let sh = cli.open_shell().await?;
51//! let cmd = cli.run_command(&sh, "whoami", &[]).await?;
52//! let _ = cli.receive_stream(&cmd).await?; // stub for now
53//! # Ok(()) }
54//! ```
55
56pub mod auth;
57pub mod credssp_auth;
58pub mod error;
59pub mod ps;
60mod uuid;
61pub mod wsman;
62
63pub use error::{Error, Result};
64pub use ps::ExecResult;
65
66use auth::{negotiate_header, parse_challenge_header, Secret};
67use base64::{engine::general_purpose::STANDARD as B64, Engine};
68use futures_util::stream::{self, Stream};
69use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE, WWW_AUTHENTICATE};
70use reqwest::{Client, StatusCode};
71use std::path::Path;
72
73/// Opaque WSMan `ShellId` (UUID string as reported by the server, without the
74/// `uuid:` prefix).
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct ShellId(pub String);
77
78/// Opaque WSMan `CommandId` — bound to a specific [`ShellId`].
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct CommandId(pub String);
81
82/// One decoded chunk pulled from a Receive response.
83#[derive(Debug, Clone)]
84pub struct Chunk {
85    pub stream: String, // "stdout" | "stderr"
86    pub data: Vec<u8>,
87    /// True on the final chunk (server-signaled EndOfStream).
88    pub end: bool,
89}
90
91const CONTENT_TYPE_SOAP: &str = "application/soap+xml;charset=UTF-8";
92
93/// Async WinRM 2.0 client. One instance = one target + one HTTP-Keep-Alive
94/// connection (NTLM binds to the connection, so we cannot share it).
95pub struct WinRmClient {
96    /// FQDN or IP of the WinRM listener.
97    pub target: String,
98    /// Port — 5985 for HTTP, 5986 for HTTPS by Windows default.
99    pub port: u16,
100    /// TLS on/off. When `true`, sends to `https://…`.
101    pub tls: bool,
102
103    /// The persistent HTTP client (NTLM is connection-bound — pool size = 1).
104    http: Client,
105    /// Full endpoint URL (`http[s]://target:port/wsman`).
106    endpoint: String,
107    /// Ephemeral session key from the NTLM handshake — 16 bytes of key
108    /// material for the future sign+seal path. `None` until `auth_*` succeeds.
109    session_key: Option<[u8; 16]>,
110    /// Which auth kind was last successful (informational).
111    authed: Option<AuthKind>,
112}
113
114/// Which SSP the client last authenticated with.
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub enum AuthKind {
117    Ntlm,
118    /// CredSSP over WinRM auth pump — MS-CSSP NTLM or Kerberos path.
119    /// Set once [`WinRmClient::auth_credssp`] returns Ok.
120    CredSsp,
121    /// Kerberos AP-REQ inside SPNEGO — call still returns `Unsupported`
122    /// until the KDC transport (ms-kile) lands.
123    Kerberos,
124}
125
126impl WinRmClient {
127    /// Open a keep-alive HTTP(S) connection to the WinRM listener. Does not
128    /// authenticate — call [`auth_ntlm`](Self::auth_ntlm) next.
129    ///
130    /// `tls=false` implies port 5985 (plaintext); `tls=true` implies 5986.
131    /// TLS uses rustls with the platform verifier (via reqwest's rustls-tls
132    /// feature). Self-signed certs on lab DCs will FAIL — feed those a
133    /// hand-built client (or set `danger_accept_invalid_certs=true` in a
134    /// later builder API).
135    pub async fn connect(target: &str, port: u16, tls: bool) -> Result<Self> {
136        let scheme = if tls { "https" } else { "http" };
137        let endpoint = format!("{scheme}://{target}:{port}/wsman");
138        // Pool-max-per-host = 1 because NTLM is connection-bound.
139        let http = Client::builder()
140            .http1_only()
141            .pool_max_idle_per_host(1)
142            .user_agent("winrm-pentest/0.1.0-dev")
143            .build()?;
144        Ok(Self {
145            target: target.to_string(),
146            port,
147            tls,
148            http,
149            endpoint,
150            session_key: None,
151            authed: None,
152        })
153    }
154
155    /// Perform the HTTP-Negotiate NTLM handshake (three-legged: empty POST →
156    /// 401 with challenge → POST with AUTHENTICATE header). `pass_or_hash` is
157    /// auto-detected as either a plaintext password or a 32-hex NT-hash / an
158    /// `LM:NT` secretsdump pair (pass-the-hash).
159    ///
160    /// Post-handshake the connection is authenticated at the HTTP layer;
161    /// subsequent requests reuse the same TCP connection carrying the same
162    /// NTLM security context.
163    pub async fn auth_ntlm(&mut self, user: &str, pass_or_hash: &str) -> Result<()> {
164        let (domain, user) = auth::split_user(user);
165        let secret = Secret::from_input(pass_or_hash);
166        let ntlm = ntlmssp::Ntlm::new();
167
168        // Leg 1: send NEGOTIATE, expect 401 with CHALLENGE.
169        let mut hdrs = HeaderMap::new();
170        hdrs.insert(
171            AUTHORIZATION,
172            HeaderValue::from_str(&negotiate_header(ntlm.negotiate()))
173                .map_err(|_| Error::Auth("bad ntlm negotiate header".into()))?,
174        );
175        hdrs.insert(CONTENT_TYPE, HeaderValue::from_static(CONTENT_TYPE_SOAP));
176        let resp = self
177            .http
178            .post(&self.endpoint)
179            .headers(hdrs)
180            .body(Vec::<u8>::new())
181            .send()
182            .await?;
183        if resp.status() != StatusCode::UNAUTHORIZED {
184            return Err(Error::Auth(format!(
185                "expected 401 on Type-1, got {}",
186                resp.status()
187            )));
188        }
189        let challenge_b64 = resp
190            .headers()
191            .get(WWW_AUTHENTICATE)
192            .and_then(|v| v.to_str().ok())
193            .ok_or_else(|| Error::Auth("no WWW-Authenticate on 401".into()))?
194            .to_string();
195        // Drop the response body — its Content-Length is 0 anyway.
196        drop(resp);
197        let challenge = parse_challenge_header(&challenge_b64)?;
198
199        // Leg 2: send AUTHENTICATE. Server responds 200 (with an empty SOAP
200        // body — the auth 200 is just a handshake ACK).
201        let (auth_hdr, session_key) =
202            auth::authenticate(&ntlm, &challenge, (&domain, &user), &secret, "WORKSTATION")?;
203        let mut hdrs = HeaderMap::new();
204        hdrs.insert(
205            AUTHORIZATION,
206            HeaderValue::from_str(&auth_hdr)
207                .map_err(|_| Error::Auth("bad ntlm authenticate header".into()))?,
208        );
209        hdrs.insert(CONTENT_TYPE, HeaderValue::from_static(CONTENT_TYPE_SOAP));
210        let resp = self
211            .http
212            .post(&self.endpoint)
213            .headers(hdrs)
214            .body(Vec::<u8>::new())
215            .send()
216            .await?;
217        if !resp.status().is_success() && resp.status() != StatusCode::UNAUTHORIZED {
218            // A hardened server returns 401 on empty-body AUTH+content-length-0
219            // instead of 200. Treat that as "handshake completed, waiting on
220            // real SOAP" — pywinrm handles it the same way.
221            return Err(Error::Auth(format!(
222                "unexpected auth response: {}",
223                resp.status()
224            )));
225        }
226        self.session_key = Some(session_key);
227        self.authed = Some(AuthKind::Ntlm);
228        Ok(())
229    }
230
231    /// Drive the CredSSP over WinRM auth pump against the target listener,
232    /// carrying [`credssp::CredSspClient`] tokens inside the `Authorization: CredSSP`
233    /// header per MS-CSSP §3.2.5 (three legs for NTLM). `server_pubkey` is the
234    /// DER SubjectPublicKeyInfo lifted from the completed TLS handshake — the
235    /// caller is responsible for supplying it (reqwest does not expose peer
236    /// cert bytes out of the box; use a hand-built rustls handshake or lift it
237    /// from a pre-recorded probe). `delegate` is reserved for later use —
238    /// today CredSSP always ships pass-through TSCredentials.
239    ///
240    /// Post-handshake the connection is authenticated at the CredSSP layer but
241    /// subsequent WSMV SOAP requests still need message encryption
242    /// (`multipart/encrypted; protocol="application/HTTP-CredSSP-session-encrypted"`,
243    /// MS-WSMV §3.1.4.1.31). That layer is the next round; today `open_shell`
244    /// against a hardened target will 500 until it lands.
245    pub async fn auth_credssp(
246        &mut self,
247        user: &str,
248        pass: &str,
249        server_pubkey: Vec<u8>,
250        delegate: bool,
251    ) -> Result<()> {
252        let _ = delegate; // reserved knob — CredSSP TSCredentials always carry full password
253        let target_spn = format!("HOST/{}", self.target);
254        let mut pump = credssp_auth::CredSspPump::ntlm(user, pass, &target_spn, server_pubkey);
255        let mut server_reply: Option<Vec<u8>> = None;
256        while let credssp_auth::PumpStep::Send(bytes) = pump.next(server_reply.as_deref())? {
257            let mut hdrs = HeaderMap::new();
258            hdrs.insert(
259                AUTHORIZATION,
260                HeaderValue::from_str(&credssp_auth::credssp_header(&bytes))
261                    .map_err(|_| Error::Auth("bad credssp header".into()))?,
262            );
263            hdrs.insert(CONTENT_TYPE, HeaderValue::from_static(CONTENT_TYPE_SOAP));
264            let resp = self
265                .http
266                .post(&self.endpoint)
267                .headers(hdrs)
268                .body(Vec::<u8>::new())
269                .send()
270                .await?;
271            let status = resp.status();
272            if status == StatusCode::UNAUTHORIZED {
273                let www = resp
274                    .headers()
275                    .get(WWW_AUTHENTICATE)
276                    .and_then(|v| v.to_str().ok())
277                    .ok_or_else(|| Error::Auth("credssp: no WWW-Authenticate on 401".into()))?
278                    .to_string();
279                drop(resp);
280                server_reply = Some(credssp_auth::parse_credssp_header(&www)?);
281            } else if status.is_success() {
282                drop(resp);
283                // Server accepted the last leg — drain the pump one more
284                // step, which should transition to Done without emitting.
285                server_reply = None;
286            } else {
287                return Err(Error::Auth(format!(
288                    "credssp: unexpected response {status}"
289                )));
290            }
291        }
292        self.authed = Some(AuthKind::CredSsp);
293        Ok(())
294    }
295
296    /// Reserved — Kerberos path (SPNEGO with a Kerberos AP-REQ) requires a
297    /// picky-krb-style client. Returns [`Error::Unsupported`] today.
298    pub async fn auth_kerberos(&mut self, _user_principal: &str, _pass: &str) -> Result<()> {
299        Err(Error::Unsupported(
300            "Kerberos SSP not wired yet — pending KDC client",
301        ))
302    }
303
304    /// Send the pre-built envelope to the WSMan endpoint and return the raw
305    /// response body. Fails if not authenticated or if the server returns a
306    /// SOAP `s:Fault`.
307    async fn post_envelope(&self, envelope: &str) -> Result<String> {
308        if self.authed.is_none() {
309            return Err(Error::NotAuthenticated);
310        }
311        let resp = self
312            .http
313            .post(&self.endpoint)
314            .header(CONTENT_TYPE, CONTENT_TYPE_SOAP)
315            .body(envelope.to_string().into_bytes())
316            .send()
317            .await?;
318        let status = resp.status();
319        let body = resp.text().await?;
320        if !status.is_success() {
321            if let Some((code, reason)) = wsman::parse_fault(&body) {
322                return Err(Error::WsmanFault { code, reason });
323            }
324            return Err(Error::Protocol("wsman: non-2xx and no parseable fault"));
325        }
326        if let Some((code, reason)) = wsman::parse_fault(&body) {
327            return Err(Error::WsmanFault { code, reason });
328        }
329        Ok(body)
330    }
331
332    /// Create a remote cmd.exe pipe. Returns the server-assigned
333    /// [`ShellId`], which every subsequent Command/Receive/Send/Signal call
334    /// pins itself to.
335    pub async fn open_shell(&mut self) -> Result<ShellId> {
336        let msg_id = uuid::uuid_v4();
337        let env =
338            wsman::create_shell_envelope(&self.endpoint, &msg_id, wsman::CreateOptions::defaults());
339        let body = self.post_envelope(&env).await?;
340        wsman::parse_shell_id(&body)
341            .map(ShellId)
342            .ok_or(Error::Protocol("Create response missing ShellId"))
343    }
344
345    /// Launch a program inside the shell. Returns a fresh [`CommandId`]; feed
346    /// it to [`receive_stream`](Self::receive_stream) to drain stdout.
347    pub async fn run_command(
348        &mut self,
349        shell: &ShellId,
350        cmd: &str,
351        args: &[&str],
352    ) -> Result<CommandId> {
353        let msg_id = uuid::uuid_v4();
354        let env = wsman::command_envelope(
355            &self.endpoint,
356            &msg_id,
357            &shell.0,
358            cmd,
359            args,
360            wsman::CreateOptions::defaults(),
361        );
362        let body = self.post_envelope(&env).await?;
363        wsman::parse_command_id(&body)
364            .map(CommandId)
365            .ok_or(Error::Protocol("Command response missing CommandId"))
366    }
367
368    /// Drain stdout/stderr chunks for a running command. TODAY this returns an
369    /// empty stream — real streaming requires the HTTP sign+seal layer that is
370    /// still open (see the module-level status note). Callers get a valid,
371    /// empty `Stream` so consumer code can be written against the final API.
372    pub async fn receive_stream(
373        &mut self,
374        _cmd: &CommandId,
375    ) -> Result<Box<dyn Stream<Item = Result<Chunk>> + Unpin + Send>> {
376        // [STUB] returns an empty stream. Do NOT panic — the caller may loop
377        // over this and we want the loop to fall through cleanly. Wire up
378        // real receive-loop after sign+seal lands.
379        let empty: Vec<Result<Chunk>> = Vec::new();
380        Ok(Box::new(stream::iter(empty)))
381    }
382
383    /// PowerShell one-shot. Wraps `script` in `-EncodedCommand` (UTF-16LE
384    /// base64) and blocks until the command completes.
385    ///
386    /// TODAY returns an empty [`ExecResult`] because the receive loop is
387    /// stubbed. Once sign+seal lands, this will loop Receive until
388    /// `CommandState = Done` and populate stdout/stderr/exit_code.
389    pub async fn invoke_ps(&mut self, shell: &ShellId, script: &str) -> Result<ExecResult> {
390        let encoded = ps::encode_ps_command(script);
391        let _cmd = self
392            .run_command(
393                shell,
394                "powershell",
395                &["-NoProfile", "-EncodedCommand", &encoded],
396            )
397            .await?;
398        // [STUB] real drain needs receive_stream to work.
399        Ok(ExecResult {
400            stdout: String::new(),
401            stderr: String::new(),
402            exit_code: 0,
403        })
404    }
405
406    /// SMB-free file upload — reads `local` in `chunk_kb`-sized chunks, base64
407    /// encodes each chunk, and appends it to `remote` on the target via a
408    /// PowerShell one-liner per chunk.
409    ///
410    /// TODAY returns [`Error::Unsupported`] — the upload happy-path needs the
411    /// Send/Receive loop to be functional (feedback from `[System.IO.File]::AppendAllText`
412    /// PowerShell exit code). API is stable; body is behind a real receive loop.
413    pub async fn upload_file(
414        &mut self,
415        _shell: &ShellId,
416        _local: &Path,
417        _remote: &str,
418        _chunk_kb: usize,
419    ) -> Result<()> {
420        Err(Error::Unsupported(
421            "upload_file needs the Receive loop (pending sign+seal)",
422        ))
423    }
424
425    /// Best-effort close of a remote shell. Ignores WSMan faults — a shell that
426    /// times out server-side is already gone.
427    pub async fn close_shell(&mut self, shell: &ShellId) -> Result<()> {
428        let msg_id = uuid::uuid_v4();
429        let env = wsman::delete_shell_envelope(
430            &self.endpoint,
431            &msg_id,
432            &shell.0,
433            wsman::CreateOptions::defaults(),
434        );
435        let _ = self.post_envelope(&env).await;
436        Ok(())
437    }
438}
439
440/// One-shot base64-encode helper — public because the `upload_file`
441/// choreography (once implemented) calls this from PS one-liner assembly.
442pub fn b64(bytes: &[u8]) -> String {
443    B64.encode(bytes)
444}