winrm-pentest 0.1.0

Async WinRM 2.0 (WS-Management) client for offensive security — NTLM/Kerberos/CredSSP auth, remote PowerShell, encoded-command exec, SMB-free file upload. Cross-platform. Pre-alpha
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! `winrm-pentest` — async WinRM 2.0 (WS-Management) client aimed at
//! offensive-security workflows: NTLM/CredSSP auth, remote PowerShell shell
//! creation, `-EncodedCommand` execution, streaming stdout, and SMB-free file
//! upload via base64-chunked `<rsp:Send>`.
//!
//! # Status
//!
//! **Pre-alpha (0.1.0-dev).** Compile-clean skeleton with:
//! * Byte-deterministic WSMan envelope builders for
//!   Create / Command / Send / Receive / Signal / Delete
//!   (see [`wsman`] — round-trip tested).
//! * Full NTLM Negotiate/Challenge/Authenticate driver over HTTP
//!   (via `ntlmssp` — no FFI, includes pass-the-hash), tested against a
//!   canned Windows challenge.
//! * PowerShell `-EncodedCommand` helpers, including a deflate-then-b64
//!   payload for scripts that overflow the 512 KB envelope cap.
//! * Public API surface for the whole client ([`WinRmClient`]) with
//!   partial-impl bodies. Everything compiles; the pieces that need a live DC
//!   for iteration return a clear `Error::Unsupported` rather than panicking.
//!
//! # NOT YET wired
//!
//! * HTTP sign+seal (`multipart/encrypted; protocol="application/HTTP-SPNEGO-session-encrypted"`).
//!   Blocks WinRM over plaintext 5985 with the default `AllowUnencrypted=false`.
//!   Use HTTPS (5986) meanwhile.
//! * CredSSP transport — [`WinRmClient::auth_credssp`] drives the sibling
//!   `credssp` crate's `CredSspClient` state machine over the HTTP auth pump
//!   (`Authorization: CredSSP <b64(TSRequest)>` / `WWW-Authenticate: CredSSP …`).
//!   NTLM path is wired end-to-end and tested against a mock listener. The
//!   Kerberos SspKind is exposed via [`credssp_auth::CredSspPump::kerberos`] —
//!   caller supplies a `ServiceTicket`; that same pump then feeds
//!   `WinRmClient::auth_credssp`-style HTTP pumping (a top-level
//!   `auth_kerberos_credssp` wrapper lands with the KDC transport in ms-kile).
//!   WSMV message encryption over the sealed CredSSP channel is still open —
//!   post-auth SOAP against a `AllowUnencrypted=false` target is rejected
//!   until it lands.
//! * Kerberos — same story, wire up via a picky-krb-based path later.
//! * `receive_stream` returns an immediately-`Done` empty stream (real
//!   streaming needs the sign+seal layer above). `upload_file` is currently
//!   `Unsupported` for the same reason.
//!
//! # Minimal usage
//!
//! ```no_run
//! # async fn demo() -> winrm_pentest::Result<()> {
//! use winrm_pentest::WinRmClient;
//!
//! let mut cli = WinRmClient::connect("dc01.lab.local", 5986, true).await?;
//! cli.auth_ntlm("LAB\\Administrator", "P@ssw0rd!").await?;
//! let sh = cli.open_shell().await?;
//! let cmd = cli.run_command(&sh, "whoami", &[]).await?;
//! let _ = cli.receive_stream(&cmd).await?; // stub for now
//! # Ok(()) }
//! ```

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;

/// Opaque WSMan `ShellId` (UUID string as reported by the server, without the
/// `uuid:` prefix).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShellId(pub String);

/// Opaque WSMan `CommandId` — bound to a specific [`ShellId`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandId(pub String);

/// One decoded chunk pulled from a Receive response.
#[derive(Debug, Clone)]
pub struct Chunk {
    pub stream: String, // "stdout" | "stderr"
    pub data: Vec<u8>,
    /// True on the final chunk (server-signaled EndOfStream).
    pub end: bool,
}

const CONTENT_TYPE_SOAP: &str = "application/soap+xml;charset=UTF-8";

/// Async WinRM 2.0 client. One instance = one target + one HTTP-Keep-Alive
/// connection (NTLM binds to the connection, so we cannot share it).
pub struct WinRmClient {
    /// FQDN or IP of the WinRM listener.
    pub target: String,
    /// Port — 5985 for HTTP, 5986 for HTTPS by Windows default.
    pub port: u16,
    /// TLS on/off. When `true`, sends to `https://…`.
    pub tls: bool,

    /// The persistent HTTP client (NTLM is connection-bound — pool size = 1).
    http: Client,
    /// Full endpoint URL (`http[s]://target:port/wsman`).
    endpoint: String,
    /// Ephemeral session key from the NTLM handshake — 16 bytes of key
    /// material for the future sign+seal path. `None` until `auth_*` succeeds.
    session_key: Option<[u8; 16]>,
    /// Which auth kind was last successful (informational).
    authed: Option<AuthKind>,
}

/// Which SSP the client last authenticated with.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthKind {
    Ntlm,
    /// CredSSP over WinRM auth pump — MS-CSSP NTLM or Kerberos path.
    /// Set once [`WinRmClient::auth_credssp`] returns Ok.
    CredSsp,
    /// Kerberos AP-REQ inside SPNEGO — call still returns `Unsupported`
    /// until the KDC transport (ms-kile) lands.
    Kerberos,
}

impl WinRmClient {
    /// Open a keep-alive HTTP(S) connection to the WinRM listener. Does not
    /// authenticate — call [`auth_ntlm`](Self::auth_ntlm) next.
    ///
    /// `tls=false` implies port 5985 (plaintext); `tls=true` implies 5986.
    /// TLS uses rustls with the platform verifier (via reqwest's rustls-tls
    /// feature). Self-signed certs on lab DCs will FAIL — feed those a
    /// hand-built client (or set `danger_accept_invalid_certs=true` in a
    /// later builder API).
    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");
        // Pool-max-per-host = 1 because NTLM is connection-bound.
        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,
        })
    }

    /// Perform the HTTP-Negotiate NTLM handshake (three-legged: empty POST →
    /// 401 with challenge → POST with AUTHENTICATE header). `pass_or_hash` is
    /// auto-detected as either a plaintext password or a 32-hex NT-hash / an
    /// `LM:NT` secretsdump pair (pass-the-hash).
    ///
    /// Post-handshake the connection is authenticated at the HTTP layer;
    /// subsequent requests reuse the same TCP connection carrying the same
    /// NTLM security context.
    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();

        // Leg 1: send NEGOTIATE, expect 401 with CHALLENGE.
        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 the response body — its Content-Length is 0 anyway.
        drop(resp);
        let challenge = parse_challenge_header(&challenge_b64)?;

        // Leg 2: send AUTHENTICATE. Server responds 200 (with an empty SOAP
        // body — the auth 200 is just a handshake ACK).
        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 {
            // A hardened server returns 401 on empty-body AUTH+content-length-0
            // instead of 200. Treat that as "handshake completed, waiting on
            // real SOAP" — pywinrm handles it the same way.
            return Err(Error::Auth(format!(
                "unexpected auth response: {}",
                resp.status()
            )));
        }
        self.session_key = Some(session_key);
        self.authed = Some(AuthKind::Ntlm);
        Ok(())
    }

    /// Drive the CredSSP over WinRM auth pump against the target listener,
    /// carrying [`credssp::CredSspClient`] tokens inside the `Authorization: CredSSP`
    /// header per MS-CSSP §3.2.5 (three legs for NTLM). `server_pubkey` is the
    /// DER SubjectPublicKeyInfo lifted from the completed TLS handshake — the
    /// caller is responsible for supplying it (reqwest does not expose peer
    /// cert bytes out of the box; use a hand-built rustls handshake or lift it
    /// from a pre-recorded probe). `delegate` is reserved for later use —
    /// today CredSSP always ships pass-through TSCredentials.
    ///
    /// Post-handshake the connection is authenticated at the CredSSP layer but
    /// subsequent WSMV SOAP requests still need message encryption
    /// (`multipart/encrypted; protocol="application/HTTP-CredSSP-session-encrypted"`,
    /// MS-WSMV §3.1.4.1.31). That layer is the next round; today `open_shell`
    /// against a hardened target will 500 until it lands.
    pub async fn auth_credssp(
        &mut self,
        user: &str,
        pass: &str,
        server_pubkey: Vec<u8>,
        delegate: bool,
    ) -> Result<()> {
        let _ = delegate; // reserved knob — CredSSP TSCredentials always carry full password
        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 accepted the last leg — drain the pump one more
                // step, which should transition to Done without emitting.
                server_reply = None;
            } else {
                return Err(Error::Auth(format!(
                    "credssp: unexpected response {status}"
                )));
            }
        }
        self.authed = Some(AuthKind::CredSsp);
        Ok(())
    }

    /// Reserved — Kerberos path (SPNEGO with a Kerberos AP-REQ) requires a
    /// picky-krb-style client. Returns [`Error::Unsupported`] today.
    pub async fn auth_kerberos(&mut self, _user_principal: &str, _pass: &str) -> Result<()> {
        Err(Error::Unsupported(
            "Kerberos SSP not wired yet — pending KDC client",
        ))
    }

    /// Send the pre-built envelope to the WSMan endpoint and return the raw
    /// response body. Fails if not authenticated or if the server returns a
    /// SOAP `s:Fault`.
    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)
    }

    /// Create a remote cmd.exe pipe. Returns the server-assigned
    /// [`ShellId`], which every subsequent Command/Receive/Send/Signal call
    /// pins itself to.
    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"))
    }

    /// Launch a program inside the shell. Returns a fresh [`CommandId`]; feed
    /// it to [`receive_stream`](Self::receive_stream) to drain stdout.
    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"))
    }

    /// Drain stdout/stderr chunks for a running command. TODAY this returns an
    /// empty stream — real streaming requires the HTTP sign+seal layer that is
    /// still open (see the module-level status note). Callers get a valid,
    /// empty `Stream` so consumer code can be written against the final API.
    pub async fn receive_stream(
        &mut self,
        _cmd: &CommandId,
    ) -> Result<Box<dyn Stream<Item = Result<Chunk>> + Unpin + Send>> {
        // [STUB] returns an empty stream. Do NOT panic — the caller may loop
        // over this and we want the loop to fall through cleanly. Wire up
        // real receive-loop after sign+seal lands.
        let empty: Vec<Result<Chunk>> = Vec::new();
        Ok(Box::new(stream::iter(empty)))
    }

    /// PowerShell one-shot. Wraps `script` in `-EncodedCommand` (UTF-16LE
    /// base64) and blocks until the command completes.
    ///
    /// TODAY returns an empty [`ExecResult`] because the receive loop is
    /// stubbed. Once sign+seal lands, this will loop Receive until
    /// `CommandState = Done` and populate stdout/stderr/exit_code.
    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?;
        // [STUB] real drain needs receive_stream to work.
        Ok(ExecResult {
            stdout: String::new(),
            stderr: String::new(),
            exit_code: 0,
        })
    }

    /// SMB-free file upload — reads `local` in `chunk_kb`-sized chunks, base64
    /// encodes each chunk, and appends it to `remote` on the target via a
    /// PowerShell one-liner per chunk.
    ///
    /// TODAY returns [`Error::Unsupported`] — the upload happy-path needs the
    /// Send/Receive loop to be functional (feedback from `[System.IO.File]::AppendAllText`
    /// PowerShell exit code). API is stable; body is behind a real receive loop.
    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)",
        ))
    }

    /// Best-effort close of a remote shell. Ignores WSMan faults — a shell that
    /// times out server-side is already gone.
    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(())
    }
}

/// One-shot base64-encode helper — public because the `upload_file`
/// choreography (once implemented) calls this from PS one-liner assembly.
pub fn b64(bytes: &[u8]) -> String {
    B64.encode(bytes)
}