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
//! HTTP-Negotiate NTLM handshake — the `Authorization: Negotiate <b64>` /
//! `WWW-Authenticate: Negotiate <b64>` pump on top of [`ntlmssp::Ntlm`].
//!
//! Windows exposes NTLM under HTTP via SPNEGO-wrapped or raw ("naked" NTLMSSP)
//! tokens. `winrm quickconfig` on a fresh install accepts *both*, and the
//! Evil-WinRM / pywinrm heuristic is: if the server advertises `Negotiate` and
//! the peer name contains no realm, send raw NTLMSSP. That's what this module
//! does.
//!
//! ### Status
//! The three-legged NEGOTIATE / CHALLENGE / AUTHENTICATE exchange is
//! implemented and tested against a canned Windows challenge (see
//! `tests/ntlm_smoke.rs`). Post-auth SPNEGO sign+seal for the SOAP body
//! (`multipart/encrypted; protocol="application/HTTP-SPNEGO-session-encrypted"`)
//! is **NOT** wired yet — see the `encrypt` fn stub below. Every request
//! post-auth currently rides plaintext HTTP; on 5986 (HTTPS) that's what
//! Evil-WinRM does by default, so the pentest happy-path works. On 5985 with
//! `AllowUnencrypted=false` (Windows default!) the request will be rejected by
//! the server until sign+seal lands.

use crate::error::{Error, Result};
use base64::{engine::general_purpose::STANDARD as B64, Engine};

/// Parsed forms of what a client can carry in `pass_or_hash`.
#[derive(Debug, Clone)]
pub enum Secret {
    /// Plaintext password (UTF-8, converted to UTF-16LE by ntlmssp).
    Password(String),
    /// 16-byte NT hash — the `LM:NT` "hash" pair as printed by `secretsdump.py`,
    /// or a bare 32-hex-char NT half. Enables pass-the-hash.
    NtHash([u8; 16]),
}

impl Secret {
    /// Parse the user-facing `pass_or_hash` argument the way Evil-WinRM does:
    /// if the string is 32 hex chars OR `LM:NT` with 32-hex halves, treat as
    /// hash; otherwise plaintext password.
    pub fn from_input(s: &str) -> Self {
        let candidate = if let Some((lm, nt)) = s.split_once(':') {
            if lm.len() == 32
                && nt.len() == 32
                && lm.chars().all(|c| c.is_ascii_hexdigit())
                && nt.chars().all(|c| c.is_ascii_hexdigit())
            {
                Some(nt)
            } else {
                None
            }
        } else if s.len() == 32 && s.chars().all(|c| c.is_ascii_hexdigit()) {
            Some(s)
        } else {
            None
        };
        if let Some(hex) = candidate {
            let mut h = [0u8; 16];
            for i in 0..16 {
                h[i] = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).unwrap_or(0);
            }
            Secret::NtHash(h)
        } else {
            Secret::Password(s.to_string())
        }
    }
}

/// Split `DOMAIN\user` or `user@DOMAIN` or bare `user` into `(domain, user)`.
/// Falls back to `""` domain (workgroup — WinRM accepts local accounts this way).
pub fn split_user(raw: &str) -> (String, String) {
    if let Some((d, u)) = raw.split_once('\\') {
        (d.to_string(), u.to_string())
    } else if let Some((u, d)) = raw.split_once('@') {
        (d.to_string(), u.to_string())
    } else {
        (String::new(), raw.to_string())
    }
}

/// Build the initial `Authorization: Negotiate <b64(Type1)>` header value.
pub fn negotiate_header(type1: &[u8]) -> String {
    format!("Negotiate {}", B64.encode(type1))
}

/// Parse `WWW-Authenticate: Negotiate <b64>` — returns the raw NTLMSSP
/// CHALLENGE bytes, or a clear error if the server offered no Negotiate value.
pub fn parse_challenge_header(www_authenticate: &str) -> Result<Vec<u8>> {
    // Header may be a comma-separated list of schemes: "Negotiate <b64>, NTLM"
    for part in www_authenticate.split(',') {
        let part = part.trim();
        if let Some(rest) = part.strip_prefix("Negotiate ") {
            return B64.decode(rest.trim()).map_err(Error::from);
        }
        if let Some(rest) = part.strip_prefix("NTLM ") {
            return B64.decode(rest.trim()).map_err(Error::from);
        }
    }
    // If the server just says "Negotiate" with no token, that's the initial
    // 401 — the caller shouldn't be here yet.
    Err(Error::Auth(format!(
        "no Negotiate CHALLENGE in {www_authenticate:?}"
    )))
}

/// Drive the ntlmssp state machine one full round: given the CHALLENGE, produce
/// the AUTHENTICATE header value and the 16-byte ExportedSessionKey (session
/// key = future sign+seal key material).
pub fn authenticate(
    ntlm: &ntlmssp::Ntlm,
    challenge: &[u8],
    user_domain: (&str, &str),
    secret: &Secret,
    workstation: &str,
) -> Result<(String, [u8; 16])> {
    let (type3, session_key) = match secret {
        Secret::Password(p) => {
            ntlm.authenticate(challenge, user_domain.0, user_domain.1, p, workstation)?
        }
        Secret::NtHash(h) => {
            ntlm.authenticate_hash(challenge, user_domain.0, user_domain.1, h, workstation)?
        }
    };
    let hdr = format!("Negotiate {}", B64.encode(&type3));
    Ok((hdr, session_key))
}

/// [STUB] Wrap `plaintext` in a WSMan `multipart/encrypted` payload sealed with
/// the ntlmssp session key. Needed for 5985 with the default
/// `AllowUnencrypted=false`. Right now returns `Unsupported` — callers should
/// use HTTPS (5986) which does not need per-message sign+seal.
pub fn encrypt(_session_key: &[u8; 16], _plaintext: &[u8]) -> Result<Vec<u8>> {
    Err(Error::Unsupported(
        "WSMan HTTP sign+seal not yet implemented — use HTTPS (port 5986)",
    ))
}