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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! WS-Management SOAP envelope builder — hand-rolled so `MessageID` and
//! `SelectorSet` land in byte-deterministic positions (unit-testable).
//!
//! We target WSMan 2.0 (Microsoft variant, DSP0226-compat) which is what
//! Windows Remote Management 3.0 speaks on 5985/5986. Envelope skeletons follow
//! the exact URIs Windows uses (`schemas.microsoft.com/wbem/wsman/1`, etc.), so
//! a real Windows target accepts them without special-casing.
//!
//! Reference: [MS-WSMV] §3.1.4 and [DSP0226] §5.
//!
//! ### Status
//! Envelope builders for **Create / Command / Send / Receive / Signal / Delete**
//! are implemented byte-for-byte and covered by the `wsman_envelope_bytes`
//! round-trip test. Response parsing pulls `ShellId` / `CommandId` /
//! `wst:Selector[@Name='ShellId']` and Base64 `<rsp:Stream>` chunks; wsa:Fault
//! extraction is best-effort (Reason text only). Advanced knobs (locale,
//! codepage, custom `<w:OptionSet>` for interactive PS) are deferred — every
//! shipped envelope hard-codes the Evil-WinRM defaults.

use quick_xml::events::Event;
use quick_xml::reader::Reader;

const NS_ENV: &str = "http://www.w3.org/2003/05/soap-envelope";
const NS_ADDR: &str = "http://schemas.xmlsoap.org/ws/2004/08/addressing";
const NS_WSMAN: &str = "http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd";
const NS_WSMV: &str = "http://schemas.microsoft.com/wbem/wsman/1/wsman.xsd";
const NS_TRANSFER: &str = "http://schemas.xmlsoap.org/ws/2004/09/transfer";
const NS_RSP: &str = "http://schemas.microsoft.com/wbem/wsman/1/windows/shell";

const RESOURCE_CMD: &str = "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd";
pub const ANONYMOUS_TO: &str = "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous";

/// WSMan action URIs (`wsa:Action`).
pub mod action {
    pub const CREATE: &str = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Create";
    pub const DELETE: &str = "http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete";
    pub const COMMAND: &str = "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command";
    pub const SEND: &str = "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Send";
    pub const RECEIVE: &str = "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Receive";
    pub const SIGNAL: &str = "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Signal";
}

/// Common `<w:OptionSet>` values driven by the client wrapper.
#[derive(Debug, Clone, Copy, Default)]
pub struct CreateOptions {
    pub max_envelope_kb: u32, // default 512
    pub timeout_ms: u32,      // default 60_000
    pub locale: &'static str, // default "en-US"
    pub codepage: u32,        // default 437
}

impl CreateOptions {
    pub fn defaults() -> Self {
        Self {
            max_envelope_kb: 512,
            timeout_ms: 60_000,
            locale: "en-US",
            codepage: 437,
        }
    }
}

fn header_common(
    action: &str,
    to: &str,
    resource: &str,
    msg_id: &str,
    max_envelope_kb: u32,
    timeout_ms: u32,
    locale: &str,
    selectors: &[(&str, &str)],
) -> String {
    // NB: MessageID MUST be `uuid:` — Windows rejects a bare UUID (S_FALSE on
    // WSManPluginReceive if you feed it a naked hex string). Matches Evil-WinRM.
    let mut s = String::new();
    s.push_str("<s:Header>");
    s.push_str(&format!("<wsa:To>{}</wsa:To>", xml_escape(to)));
    s.push_str(&format!(
        "<wsman:ResourceURI s:mustUnderstand=\"true\">{}</wsman:ResourceURI>",
        xml_escape(resource)
    ));
    s.push_str("<wsa:ReplyTo><wsa:Address s:mustUnderstand=\"true\">");
    s.push_str(ANONYMOUS_TO);
    s.push_str("</wsa:Address></wsa:ReplyTo>");
    s.push_str(&format!(
        "<wsa:Action s:mustUnderstand=\"true\">{}</wsa:Action>",
        action
    ));
    s.push_str(&format!(
        "<wsman:MaxEnvelopeSize s:mustUnderstand=\"true\">{}</wsman:MaxEnvelopeSize>",
        max_envelope_kb as u64 * 1024
    ));
    s.push_str(&format!("<wsa:MessageID>uuid:{}</wsa:MessageID>", msg_id));
    s.push_str(&format!(
        "<wsman:Locale xml:lang=\"{}\" s:mustUnderstand=\"false\"/>",
        xml_escape(locale)
    ));
    s.push_str(&format!(
        "<wsmv:DataLocale xml:lang=\"{}\" s:mustUnderstand=\"false\"/>",
        xml_escape(locale)
    ));
    s.push_str(&format!(
        "<wsman:OperationTimeout>PT{}.{:03}S</wsman:OperationTimeout>",
        timeout_ms / 1000,
        timeout_ms % 1000
    ));
    if !selectors.is_empty() {
        s.push_str("<wsman:SelectorSet>");
        for (name, val) in selectors {
            s.push_str(&format!(
                "<wsman:Selector Name=\"{}\">{}</wsman:Selector>",
                xml_escape(name),
                xml_escape(val)
            ));
        }
        s.push_str("</wsman:SelectorSet>");
    }
    s.push_str("</s:Header>");
    s
}

fn envelope(header: String, body: &str) -> String {
    let mut s = String::with_capacity(header.len() + body.len() + 512);
    s.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    s.push_str("<s:Envelope");
    s.push_str(&format!(" xmlns:s=\"{}\"", NS_ENV));
    s.push_str(&format!(" xmlns:wsa=\"{}\"", NS_ADDR));
    s.push_str(&format!(" xmlns:wsman=\"{}\"", NS_WSMAN));
    s.push_str(&format!(" xmlns:wsmv=\"{}\"", NS_WSMV));
    s.push_str(&format!(" xmlns:rsp=\"{}\"", NS_RSP));
    s.push_str(&format!(" xmlns:wst=\"{}\"", NS_TRANSFER));
    s.push('>');
    s.push_str(&header);
    s.push_str("<s:Body>");
    s.push_str(body);
    s.push_str("</s:Body>");
    s.push_str("</s:Envelope>");
    s
}

/// Build the `wst:Create` envelope that opens a WinRM Shell (cmd.exe pipe).
/// `msg_id` is the raw UUID (no `uuid:` prefix — the header prepends it).
pub fn create_shell_envelope(to: &str, msg_id: &str, opts: CreateOptions) -> String {
    let header = header_common(
        action::CREATE,
        to,
        RESOURCE_CMD,
        msg_id,
        opts.max_envelope_kb,
        opts.timeout_ms,
        opts.locale,
        &[],
    );
    // <w:OptionSet> matches Evil-WinRM / Get-WSManInstance: WINRS_NOPROFILE=FALSE,
    // WINRS_CODEPAGE=437 by default. Not strictly required but the DC records it.
    let mut body = String::new();
    body.push_str("<wsman:OptionSet>");
    body.push_str("<wsman:Option Name=\"WINRS_NOPROFILE\">FALSE</wsman:Option>");
    body.push_str(&format!(
        "<wsman:Option Name=\"WINRS_CODEPAGE\">{}</wsman:Option>",
        opts.codepage
    ));
    body.push_str("</wsman:OptionSet>");
    body.push_str("<rsp:Shell>");
    body.push_str("<rsp:InputStreams>stdin</rsp:InputStreams>");
    body.push_str("<rsp:OutputStreams>stdout stderr</rsp:OutputStreams>");
    body.push_str("</rsp:Shell>");
    envelope(header, &body)
}

/// `rsp:CommandLine` — run a program with arguments in the given shell.
pub fn command_envelope(
    to: &str,
    msg_id: &str,
    shell_id: &str,
    cmd: &str,
    args: &[&str],
    opts: CreateOptions,
) -> String {
    let header = header_common(
        action::COMMAND,
        to,
        RESOURCE_CMD,
        msg_id,
        opts.max_envelope_kb,
        opts.timeout_ms,
        opts.locale,
        &[("ShellId", shell_id)],
    );
    let mut body = String::new();
    body.push_str("<rsp:CommandLine>");
    body.push_str(&format!("<rsp:Command>{}</rsp:Command>", xml_escape(cmd)));
    for a in args {
        body.push_str(&format!("<rsp:Arguments>{}</rsp:Arguments>", xml_escape(a)));
    }
    body.push_str("</rsp:CommandLine>");
    envelope(header, &body)
}

/// `rsp:Receive` — pull the next stdout/stderr chunk for a running command.
pub fn receive_envelope(
    to: &str,
    msg_id: &str,
    shell_id: &str,
    command_id: &str,
    opts: CreateOptions,
) -> String {
    let header = header_common(
        action::RECEIVE,
        to,
        RESOURCE_CMD,
        msg_id,
        opts.max_envelope_kb,
        opts.timeout_ms,
        opts.locale,
        &[("ShellId", shell_id)],
    );
    let mut body = String::new();
    body.push_str("<rsp:Receive>");
    body.push_str(&format!(
        "<rsp:DesiredStream CommandId=\"{}\">stdout stderr</rsp:DesiredStream>",
        xml_escape(command_id)
    ));
    body.push_str("</rsp:Receive>");
    envelope(header, &body)
}

/// `rsp:Send` — push one chunk of stdin (base64) at the command.
pub fn send_envelope(
    to: &str,
    msg_id: &str,
    shell_id: &str,
    command_id: &str,
    stdin_b64: &str,
    end: bool,
    opts: CreateOptions,
) -> String {
    let header = header_common(
        action::SEND,
        to,
        RESOURCE_CMD,
        msg_id,
        opts.max_envelope_kb,
        opts.timeout_ms,
        opts.locale,
        &[("ShellId", shell_id)],
    );
    let mut body = String::new();
    body.push_str("<rsp:Send>");
    body.push_str(&format!(
        "<rsp:Stream Name=\"stdin\" CommandId=\"{}\" End=\"{}\">{}</rsp:Stream>",
        xml_escape(command_id),
        if end { "true" } else { "false" },
        stdin_b64
    ));
    body.push_str("</rsp:Send>");
    envelope(header, &body)
}

/// `rsp:Signal` with the "terminate" code (default) or a caller-provided one
/// (see MS-WSMV §2.2.4.38 for CTRL_C / CTRL_BREAK / TERMINATE).
pub fn signal_envelope(
    to: &str,
    msg_id: &str,
    shell_id: &str,
    command_id: &str,
    signal_code: &str,
    opts: CreateOptions,
) -> String {
    let header = header_common(
        action::SIGNAL,
        to,
        RESOURCE_CMD,
        msg_id,
        opts.max_envelope_kb,
        opts.timeout_ms,
        opts.locale,
        &[("ShellId", shell_id)],
    );
    let mut body = String::new();
    body.push_str(&format!(
        "<rsp:Signal CommandId=\"{}\">",
        xml_escape(command_id)
    ));
    body.push_str(&format!("<rsp:Code>{}</rsp:Code>", xml_escape(signal_code)));
    body.push_str("</rsp:Signal>");
    envelope(header, &body)
}

pub const SIGNAL_TERMINATE: &str =
    "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/signal/terminate";
pub const SIGNAL_CTRL_C: &str =
    "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/signal/ctrl_c";

/// `wst:Delete` on the ShellId — closes the remote shell.
pub fn delete_shell_envelope(
    to: &str,
    msg_id: &str,
    shell_id: &str,
    opts: CreateOptions,
) -> String {
    let header = header_common(
        action::DELETE,
        to,
        RESOURCE_CMD,
        msg_id,
        opts.max_envelope_kb,
        opts.timeout_ms,
        opts.locale,
        &[("ShellId", shell_id)],
    );
    envelope(header, "")
}

fn xml_escape(s: &str) -> String {
    let mut o = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => o.push_str("&amp;"),
            '<' => o.push_str("&lt;"),
            '>' => o.push_str("&gt;"),
            '"' => o.push_str("&quot;"),
            '\'' => o.push_str("&apos;"),
            _ => o.push(c),
        }
    }
    o
}

// ---- response parsing ------------------------------------------------------

/// Best-effort extractor: pull the `ShellId` (from `<wst:Selector Name="ShellId">`
/// in the Create response, or from `<rsp:Shell>/<rsp:ShellId>`).
pub fn parse_shell_id(xml: &str) -> Option<String> {
    if let Some(v) = find_selector_value(xml, "ShellId") {
        return Some(v);
    }
    find_element_text(xml, "ShellId")
}

/// Extract the `CommandId` attribute from a Command response
/// (`<rsp:CommandResponse><rsp:CommandId>UUID</rsp:CommandId>`).
pub fn parse_command_id(xml: &str) -> Option<String> {
    find_element_text(xml, "CommandId")
}

/// Extract every `<rsp:Stream>` payload from a Receive response, keyed by
/// stream name (typically `stdout`, `stderr`). Payloads are the raw base64
/// strings as sent by the server — decode with base64::STANDARD downstream.
pub fn parse_receive_streams(xml: &str) -> Vec<(String, String)> {
    let mut out = Vec::new();
    let mut r = Reader::from_str(xml);
    r.config_mut().trim_text(true);
    let mut buf = Vec::new();
    let mut current: Option<(String, String)> = None;
    loop {
        match r.read_event_into(&mut buf) {
            Ok(Event::Start(e)) => {
                if local_name_eq(e.name().as_ref(), b"Stream") {
                    let mut name = String::new();
                    for a in e.attributes().flatten() {
                        if a.key.as_ref() == b"Name" {
                            if let Ok(v) = a.unescape_value() {
                                name = v.into_owned();
                            }
                        }
                    }
                    current = Some((name, String::new()));
                }
            }
            Ok(Event::Text(t)) => {
                if let Some((_, ref mut acc)) = current {
                    if let Ok(v) = t.unescape() {
                        acc.push_str(&v);
                    }
                }
            }
            Ok(Event::End(e)) => {
                if local_name_eq(e.name().as_ref(), b"Stream") {
                    if let Some(pair) = current.take() {
                        out.push(pair);
                    }
                }
            }
            Ok(Event::Eof) => break,
            Ok(_) => {}
            Err(_) => break,
        }
        buf.clear();
    }
    out
}

/// Return `Some((code, reason))` if the response is a SOAP `s:Fault`. Code is
/// the `wsa:Fault/s:Code/s:Value` text, reason the concatenated `s:Text` runs.
pub fn parse_fault(xml: &str) -> Option<(String, String)> {
    if !xml.contains(":Fault") {
        return None;
    }
    let code = find_element_text(xml, "Value").unwrap_or_default();
    let reason = find_element_text(xml, "Text").unwrap_or_default();
    if code.is_empty() && reason.is_empty() {
        None
    } else {
        Some((code, reason))
    }
}

fn local_name_eq(qname: &[u8], local: &[u8]) -> bool {
    match qname.iter().rposition(|&b| b == b':') {
        Some(i) => &qname[i + 1..] == local,
        None => qname == local,
    }
}

fn find_element_text(xml: &str, local: &str) -> Option<String> {
    let target = local.as_bytes();
    let mut r = Reader::from_str(xml);
    r.config_mut().trim_text(true);
    let mut buf = Vec::new();
    let mut depth: Option<usize> = None;
    let mut current_depth = 0usize;
    let mut out = String::new();
    loop {
        match r.read_event_into(&mut buf) {
            Ok(Event::Start(e)) => {
                current_depth += 1;
                if depth.is_none() && local_name_eq(e.name().as_ref(), target) {
                    depth = Some(current_depth);
                }
            }
            Ok(Event::Text(t)) => {
                if depth.is_some() {
                    if let Ok(v) = t.unescape() {
                        out.push_str(&v);
                    }
                }
            }
            Ok(Event::End(e)) => {
                if let Some(d) = depth {
                    if current_depth == d && local_name_eq(e.name().as_ref(), target) {
                        return Some(out);
                    }
                }
                current_depth = current_depth.saturating_sub(1);
            }
            Ok(Event::Empty(_)) => {}
            Ok(Event::Eof) => break,
            Ok(_) => {}
            Err(_) => break,
        }
        buf.clear();
    }
    None
}

fn find_selector_value(xml: &str, name: &str) -> Option<String> {
    let mut r = Reader::from_str(xml);
    r.config_mut().trim_text(true);
    let mut buf = Vec::new();
    let mut in_match = false;
    let mut out = String::new();
    loop {
        match r.read_event_into(&mut buf) {
            Ok(Event::Start(e)) => {
                if local_name_eq(e.name().as_ref(), b"Selector") {
                    for a in e.attributes().flatten() {
                        if a.key.as_ref() == b"Name" {
                            if let Ok(v) = a.unescape_value() {
                                if v == name {
                                    in_match = true;
                                }
                            }
                        }
                    }
                }
            }
            Ok(Event::Text(t)) => {
                if in_match {
                    if let Ok(v) = t.unescape() {
                        out.push_str(&v);
                    }
                }
            }
            Ok(Event::End(e)) => {
                if in_match && local_name_eq(e.name().as_ref(), b"Selector") {
                    return Some(out);
                }
            }
            Ok(Event::Eof) => break,
            Ok(_) => {}
            Err(_) => break,
        }
        buf.clear();
    }
    None
}