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
//! CredSSP over WinRM auth pump — a thin state machine on top of the sibling
//! [`credssp`] crate.
//!
//! ## Wire
//! CredSSP over WinRM rides the HTTP auth negotiation just like NTLM: the
//! client posts to `/wsman` with `Authorization: CredSSP <b64(TSRequest)>`,
//! the server replies `401 Unauthorized` with
//! `WWW-Authenticate: CredSSP <b64(TSRequest)>` for intermediate legs and
//! `200 OK` when the delegated TSCredentials have been accepted.
//!
//! Three legs on the NTLM path (MS-CSSP §3.2.5):
//! 1. Client → Server: `TSRequest { negoTokens = NTLM NEGOTIATE }`
//! 2. Client → Server: `TSRequest { negoTokens = NTLM AUTHENTICATE,
//!                                 pubKeyAuth = seal(c2s binding),
//!                                 clientNonce }` (in response to server CHALLENGE)
//! 3. Client → Server: `TSRequest { authInfo = seal(TSCredentials) }`
//!    (in response to server sealed pubKeyAuth)
//!
//! Kerberos path is single-shot AP-REQ then sealed authInfo — the sibling
//! `credssp::CredSspClient::with_kerberos_ticket` drives that shape and
//! [`CredSspPump::kerberos`] wires it up here.
//!
//! ## TLS
//! Per spec CredSSP is *always* wrapped in TLS. This module does not enforce
//! TLS at the transport layer — that is the caller's responsibility (and the
//! whole `WinRmClient` grows a `tls` flag anyway). Running CredSSP over
//! plaintext HTTP leaks the delegated plaintext password. We accept it here
//! only so a mock test rig can drive the state machine end-to-end without
//! standing up a full TLS harness.

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

use credssp::{CredSspClient, CredSspStep, Credentials, ServiceTicket};

/// The HTTP auth scheme name. Windows targets accept `CredSSP` case-sensitively.
pub const CREDSSP_SCHEME: &str = "CredSSP";

/// One turn of the pump.
#[derive(Debug)]
pub enum PumpStep {
    /// Client should POST with `Authorization: CredSSP <b64(bytes)>` and a
    /// zero-length body. The server's reply (WWW-Authenticate on 401, or an
    /// empty 200) is fed back into the next [`CredSspPump::next`] call.
    Send(Vec<u8>),
    /// Handshake finished — no further tokens to send. The connection is now
    /// authenticated at the CredSSP layer; downstream SOAP goes over WSMV
    /// message encryption (not yet wired).
    Done,
}

/// State machine driving [`credssp::CredSspClient`] over the WinRM auth pump.
pub struct CredSspPump {
    inner: CredSspClient,
    done: bool,
}

impl CredSspPump {
    /// NTLM-driven CredSSP. `user` is the same `DOMAIN\user`, `user@REALM`, or
    /// bare `user` form the NTLM path accepts. `server_pubkey` is the raw DER
    /// SubjectPublicKeyInfo bytes lifted from the completed TLS handshake
    /// (rustls: `peer_certificates()[0]`). `target_spn` is informational for
    /// the NTLM path (e.g. `HOST/dc01.example.local`).
    pub fn ntlm(user: &str, pass: &str, target_spn: &str, server_pubkey: Vec<u8>) -> Self {
        let (domain, user) = crate::auth::split_user(user);
        let creds = Credentials::ntlm(&domain, &user, pass, "WORKSTATION");
        let inner = CredSspClient::new(creds, target_spn.to_string(), server_pubkey);
        Self { inner, done: false }
    }

    /// Kerberos-driven CredSSP — caller obtains a `ServiceTicket` for
    /// `target_spn` out of band (typically via TGS-REQ against the KDC; that
    /// transport lives in `ms-kile`, not this crate). Once landed, the
    /// exchange is a single AP-REQ / AP-REP round-trip followed by sealed
    /// authInfo (leg 3 collapses into leg 2 for Kerberos).
    pub fn kerberos(
        realm: &str,
        user: &str,
        target_spn: &str,
        server_pubkey: Vec<u8>,
        ticket: ServiceTicket,
    ) -> Self {
        let creds = Credentials::kerberos(realm, user, "WORKSTATION");
        let inner = CredSspClient::with_kerberos_ticket(
            creds,
            target_spn.to_string(),
            server_pubkey,
            ticket,
        );
        Self { inner, done: false }
    }

    /// Drive one leg. Pass `None` on the very first call; on later calls, pass
    /// the DER TSRequest bytes that were carried in the server's
    /// `WWW-Authenticate: CredSSP <b64>` header.
    pub fn next(&mut self, server_reply: Option<&[u8]>) -> Result<PumpStep> {
        if self.done {
            return Ok(PumpStep::Done);
        }
        match self.inner.step(server_reply) {
            CredSspStep::SendToken(bytes) => Ok(PumpStep::Send(bytes)),
            CredSspStep::Done => {
                self.done = true;
                Ok(PumpStep::Done)
            }
            CredSspStep::Error(msg) => Err(Error::CredSsp(msg)),
        }
    }

    /// Whether the state machine has reached `Done`.
    pub fn is_done(&self) -> bool {
        self.done
    }

    /// Escape hatch for tests: seed the Kerberos initiator subkey so a
    /// reference server side can build a matching GSS Wrap context.
    #[doc(hidden)]
    pub fn set_krb_subkey_for_testing(&mut self, key: [u8; 32]) {
        self.inner.set_krb_subkey_for_testing(key);
    }
}

/// Build an `Authorization: CredSSP <b64>` value from a DER-encoded TSRequest.
pub fn credssp_header(tsrequest: &[u8]) -> String {
    format!("{CREDSSP_SCHEME} {}", B64.encode(tsrequest))
}

/// Parse a `WWW-Authenticate` header string. Accepts a comma-separated list of
/// challenge schemes (e.g. `CredSSP <b64>, Negotiate`) and returns the raw
/// TSRequest DER carried on the `CredSSP` scheme. Returns an empty `Vec` when
/// the server sends bare `CredSSP` with no token — the initial "please start
/// CredSSP" 401 that some hardened stacks emit before the pump begins.
pub fn parse_credssp_header(www_authenticate: &str) -> Result<Vec<u8>> {
    for part in www_authenticate.split(',') {
        let part = part.trim();
        if let Some(rest) = part.strip_prefix(CREDSSP_SCHEME) {
            let rest = rest.trim();
            if rest.is_empty() {
                return Ok(Vec::new());
            }
            return B64.decode(rest).map_err(Error::from);
        }
    }
    Err(Error::Auth(format!(
        "no CredSSP token in {www_authenticate:?}"
    )))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn header_roundtrips_via_parse() {
        let bytes = b"\x30\x82\x00\x0Adummy-tsreq";
        let hdr = credssp_header(bytes);
        assert!(hdr.starts_with("CredSSP "));
        // The value after the scheme is our base64.
        let back = parse_credssp_header(&hdr).unwrap();
        assert_eq!(back, bytes);
    }

    #[test]
    fn parse_credssp_header_handles_multi_scheme() {
        let bytes = b"abcd";
        let hdr = format!("Negotiate, CredSSP {}", B64.encode(bytes));
        let back = parse_credssp_header(&hdr).unwrap();
        assert_eq!(back, bytes);
    }

    #[test]
    fn parse_credssp_header_bare_scheme_yields_empty() {
        // "please start CredSSP" — no token yet.
        let back = parse_credssp_header("CredSSP").unwrap();
        assert!(back.is_empty());
    }

    #[test]
    fn parse_credssp_header_rejects_missing_scheme() {
        assert!(parse_credssp_header("Negotiate xyz").is_err());
    }
}