Skip to main content

ms_scmr/
lib.rs

1//! # ms-scmr — MS-SCMR (Service Control Manager Remote), pure-Rust client
2//!
3//! Open the remote SCM over an authenticated `\PIPE\svcctl` SMB pipe, create a transient
4//! service whose binary path is an arbitrary command, start it (runs as LocalSystem), delete
5//! the service, and — for `exec()` — read the command's captured output off `C$`. The
6//! canonical Windows admin-remote-execution primitive, without a Windows runtime.
7//!
8//! Layered over the `dcerpc` crate: this crate owns the SCMR wire (opnums, NDR encoders/
9//! decoders, handles, access masks), `dcerpc` provides the SMB-transport pipe + NDR helpers
10//! + `RpcError`/`Syntax` types.
11//!
12//! ## Dual-use rationale
13//!
14//! SVCCTL is a defensive/DFIR/admin primitive as much as an attacker one: fleet-wide service
15//! inventory, remote debugger start/stop, IR containment (`stop wuauserv`), routine
16//! automation — anywhere a Windows admin drops to `sc.exe` today, a Rust process can do the
17//! same over a signed SMB session. That's the extraction rule at play here.
18//!
19//! ## Status
20//!
21//! v0.1.0 — CreateService → Start → Delete cycle for command execution, plus the
22//! `exec()` output-capture wrapper. Query/enum service state, `RControlService`, and the
23//! richer service-config surface are follow-ups on the 0.1 line (additive).
24//!
25//! ## Example
26//!
27//! ```no_run
28//! # async fn demo(client: &mut smb2_client::SmbClient) -> Result<(), Box<dyn std::error::Error>> {
29//! let res = ms_scmr::exec(client, "10.0.0.10", "whoami /all").await?;
30//! println!("ran as LocalSystem: {}", res.ran);
31//! if let Some(out) = res.output { println!("{out}"); }
32//! # Ok(()) }
33//! ```
34
35#![doc(html_root_url = "https://docs.rs/ms-scmr/0.1.0")]
36
37use dcerpc::ndr::{NdrDecoder, NdrEncoder};
38use dcerpc::transport::SmbPipe;
39use dcerpc::{Result, RpcError, Syntax};
40use smb2_client::SmbClient;
41
42/// The Service Control Manager Remote interface (v2.0).
43pub fn svcctl_syntax() -> Syntax {
44    Syntax::new("367abb81-9844-35f1-ad32-98f038001003", 2, 0)
45}
46
47pub mod opnum {
48    pub const CLOSE_SERVICE_HANDLE: u16 = 0;
49    pub const DELETE_SERVICE: u16 = 2;
50    pub const CREATE_SERVICE_W: u16 = 12;
51    pub const OPEN_SC_MANAGER_W: u16 = 15;
52    pub const START_SERVICE_W: u16 = 19;
53}
54
55// Access masks and service parameters (MS-SCMR §2.2 / winsvc.h).
56const SC_MANAGER_ALL_ACCESS: u32 = 0x000F_003F;
57const SERVICE_ALL_ACCESS: u32 = 0x000F_01FF;
58const SERVICE_WIN32_OWN_PROCESS: u32 = 0x0000_0010;
59const SERVICE_DEMAND_START: u32 = 0x0000_0003;
60const SERVICE_ERROR_IGNORE: u32 = 0x0000_0000;
61
62// Win32 error codes we treat as "the command ran" — the SCM never sees a real service.
63const ERROR_SERVICE_REQUEST_TIMEOUT: u32 = 1053;
64const ERROR_SERVICE_NO_THREAD: u32 = 1054;
65const ERROR_EXCEPTION_IN_SERVICE: u32 = 1064;
66const ERROR_PROCESS_ABORTED: u32 = 1067;
67
68/// A 20-byte SC_RPC_HANDLE (attributes u32 + 16-byte context uuid).
69#[derive(Clone, Copy, Debug, Default)]
70pub struct ScHandle(pub [u8; 20]);
71
72impl ScHandle {
73    fn decode(d: &mut NdrDecoder) -> Result<Self> {
74        let attrs = d.u32()?;
75        let uuid = d.uuid()?;
76        let mut h = [0u8; 20];
77        h[..4].copy_from_slice(&attrs.to_le_bytes());
78        h[4..].copy_from_slice(&uuid);
79        Ok(ScHandle(h))
80    }
81    fn encode(&self, e: &mut NdrEncoder) {
82        e.bytes(&self.0);
83    }
84    fn is_null(&self) -> bool {
85        self.0 == [0u8; 20]
86    }
87}
88
89/// ROpenSCManagerW(NULL machine, NULL database, access) → SCM handle.
90fn encode_open_scm(access: u32) -> Vec<u8> {
91    let mut e = NdrEncoder::new();
92    e.null_ptr(); // lpMachineName (local)
93    e.null_ptr(); // lpDatabaseName (defaults to ServicesActive)
94    e.u32(access);
95    e.into_bytes()
96}
97
98/// RCreateServiceW: create a WIN32_OWN_PROCESS demand-start service whose binary is `binpath`.
99/// All optional pointers (display name, tag id, dependencies, account, password) are NULL, so
100/// the service runs as LocalSystem.
101///
102/// The two mandatory strings (`lpServiceName`, `lpBinaryPathName`) are `[string] wchar_t*` and
103/// marshal as inline conformant-varying `WSTR`s — no referent ID, no deferral. The optional
104/// pointers (`LPWSTR`/`LPDWORD`/`LPBYTE`) are unique pointers → a referent ID (0 here = NULL),
105/// with no deferred pointee since all are NULL. So the whole stub is one inline stream.
106fn encode_create_service(scm: &ScHandle, name: &str, binpath: &str) -> Vec<u8> {
107    let mut e = NdrEncoder::new();
108    scm.encode(&mut e); // hSCManager (context handle, 20 bytes)
109    e.conformant_varying_wstr(name); // lpServiceName (inline WSTR)
110    e.align(4);
111    e.null_ptr(); // lpDisplayName    (NULL)
112    e.u32(SERVICE_ALL_ACCESS); // dwDesiredAccess
113    e.u32(SERVICE_WIN32_OWN_PROCESS); // dwServiceType
114    e.u32(SERVICE_DEMAND_START); // dwStartType
115    e.u32(SERVICE_ERROR_IGNORE); // dwErrorControl
116    e.conformant_varying_wstr(binpath); // lpBinaryPathName (inline WSTR)
117    e.align(4);
118    e.null_ptr(); // lpLoadOrderGroup (NULL)
119    e.null_ptr(); // lpdwTagId        (NULL)
120    e.null_ptr(); // lpDependencies   (NULL)
121    e.u32(0); // dwDependSize
122    e.null_ptr(); // lpServiceStartName (NULL → LocalSystem)
123    e.null_ptr(); // lpPassword       (NULL)
124    e.u32(0); // dwPwSize
125    e.into_bytes()
126}
127
128/// RStartServiceW(handle, argc=0, argv=NULL).
129fn encode_start_service(svc: &ScHandle) -> Vec<u8> {
130    let mut e = NdrEncoder::new();
131    svc.encode(&mut e);
132    e.u32(0); // argc
133    e.null_ptr(); // argv
134    e.into_bytes()
135}
136
137fn encode_handle_only(h: &ScHandle) -> Vec<u8> {
138    let mut e = NdrEncoder::new();
139    h.encode(&mut e);
140    e.into_bytes()
141}
142
143/// The trailing NDR return value (a Win32 error) of an SCM call.
144fn tail_return(stub: &[u8]) -> u32 {
145    if stub.len() < 4 {
146        return u32::MAX;
147    }
148    u32::from_le_bytes(stub[stub.len() - 4..].try_into().unwrap())
149}
150
151/// High-level SVCCTL client bound over an SMB `\PIPE\svcctl`.
152pub struct SvcctlClient<'a> {
153    pipe: SmbPipe<'a>,
154}
155
156impl<'a> SvcctlClient<'a> {
157    pub async fn bind(client: &'a mut SmbClient, file_id: [u8; 16]) -> Result<Self> {
158        let mut pipe = SmbPipe::new(client, file_id);
159        pipe.bind(svcctl_syntax()).await?;
160        Ok(SvcctlClient { pipe })
161    }
162
163    async fn open_scm(&mut self) -> Result<ScHandle> {
164        let resp = self
165            .pipe
166            .call(
167                opnum::OPEN_SC_MANAGER_W,
168                &encode_open_scm(SC_MANAGER_ALL_ACCESS),
169            )
170            .await?;
171        let mut d = NdrDecoder::new(&resp);
172        let handle = ScHandle::decode(&mut d)?;
173        let ret = d.u32().unwrap_or(u32::MAX);
174        if ret != 0 || handle.is_null() {
175            return Err(RpcError::Protocol(format!(
176                "ROpenSCManagerW failed (win32 {ret})"
177            )));
178        }
179        Ok(handle)
180    }
181
182    async fn create_service(
183        &mut self,
184        scm: &ScHandle,
185        name: &str,
186        binpath: &str,
187    ) -> Result<ScHandle> {
188        let resp = self
189            .pipe
190            .call(
191                opnum::CREATE_SERVICE_W,
192                &encode_create_service(scm, name, binpath),
193            )
194            .await?;
195        let ret = tail_return(&resp);
196        if ret != 0 {
197            return Err(RpcError::Protocol(format!(
198                "RCreateServiceW failed (win32 {ret})"
199            )));
200        }
201        // [out] lpdwTagId (unique) then [out] lpServiceHandle (20) then return. Skip the tag.
202        let mut d = NdrDecoder::new(&resp);
203        let tag_ref = d.u32()?;
204        if tag_ref != 0 {
205            let _ = d.u32(); // tag value
206        }
207        ScHandle::decode(&mut d)
208    }
209
210    /// Start the service (the command executes); SCM start-timeout/exception = command ran.
211    async fn start_service(&mut self, svc: &ScHandle) -> Result<u32> {
212        let resp = self
213            .pipe
214            .call(opnum::START_SERVICE_W, &encode_start_service(svc))
215            .await?;
216        Ok(tail_return(&resp))
217    }
218
219    async fn delete_service(&mut self, svc: &ScHandle) -> Result<u32> {
220        let resp = self
221            .pipe
222            .call(opnum::DELETE_SERVICE, &encode_handle_only(svc))
223            .await?;
224        Ok(tail_return(&resp))
225    }
226
227    async fn close_handle(&mut self, h: &ScHandle) {
228        let _ = self
229            .pipe
230            .call(opnum::CLOSE_SERVICE_HANDLE, &encode_handle_only(h))
231            .await;
232    }
233}
234
235/// The result of a remote exec: the SCM outcome plus captured stdout/stderr (if any).
236pub struct ExecResult {
237    pub service: String,
238    pub start_win32: u32,
239    pub ran: bool,
240    pub cleaned: bool,
241    pub output: Option<String>,
242}
243
244/// psexec-style command execution over SVCCTL. Creates a service whose binary detaches the real
245/// work (`start "" /b`, so it survives the SCM tearing the service down), redirects its output
246/// to a temp file on the target, starts it as LocalSystem, deletes the service, then reads the
247/// output back over `C$` (delete-on-close). The service and temp file are always cleaned up.
248///
249/// `host` is the target used for the `\\host\C$` output read.
250pub async fn exec(client: &mut SmbClient, host: &str, command: &str) -> Result<ExecResult> {
251    let tag = std::time::SystemTime::now()
252        .duration_since(std::time::UNIX_EPOCH)
253        .map(|d| d.subsec_nanos())
254        .unwrap_or(0);
255    let name = format!("ADh{tag:08x}");
256    let out_rel = format!("Windows\\Temp\\ADh{tag:08x}.out"); // relative to C$ root
257    let out_win = format!("C:\\{out_rel}"); // absolute path for the redirect
258                                            // Detach the real work so it outlives the SCM teardown; redirect stdout+stderr to the file.
259    let full = format!("{command} > {out_win} 2>&1");
260    let binpath = format!("%COMSPEC% /Q /c start \"\" /b %COMSPEC% /Q /c \"{full}\"");
261
262    // --- create/start/delete the service over \svcctl (IPC$) ---
263    let start_ret = create_start_delete(client, &name, &binpath).await?;
264    let cleaned = true;
265    let ran = matches!(
266        start_ret,
267        0 | ERROR_SERVICE_REQUEST_TIMEOUT
268            | ERROR_SERVICE_NO_THREAD
269            | ERROR_EXCEPTION_IN_SERVICE
270            | ERROR_PROCESS_ABORTED
271    );
272
273    // --- read the captured output off C$ (retries while the async child writes) ---
274    let output = if ran {
275        match client.tree_connect(&format!("\\\\{host}\\C$")).await {
276            Ok(()) => match client.read_file_delete(&out_rel).await {
277                Ok(bytes) if !bytes.is_empty() => Some(
278                    String::from_utf8_lossy(&bytes)
279                        .replace('\r', "")
280                        .trim_end()
281                        .to_string(),
282                ),
283                Ok(_) => Some(String::new()),
284                Err(e) => {
285                    tracing::warn!("output read failed: {e}");
286                    None
287                }
288            },
289            Err(e) => {
290                tracing::warn!("C$ tree-connect failed: {e}");
291                None
292            }
293        }
294    } else {
295        None
296    };
297
298    Ok(ExecResult {
299        service: name,
300        start_win32: start_ret,
301        ran,
302        cleaned,
303        output,
304    })
305}
306
307/// Run a command as LocalSystem over SVCCTL without capturing output — for side-effect commands
308/// (e.g. `reg save`) whose result is a file the caller reads separately. Returns the SCM start
309/// code. Requires the client to be tree-connected to IPC$. Detaches via `start "" /b`.
310pub async fn run(client: &mut SmbClient, command: &str) -> Result<u32> {
311    let tag = std::time::SystemTime::now()
312        .duration_since(std::time::UNIX_EPOCH)
313        .map(|d| d.subsec_nanos())
314        .unwrap_or(0);
315    let name = format!("ADh{tag:08x}");
316    let binpath = format!("%COMSPEC% /Q /c start \"\" /b %COMSPEC% /Q /c \"{command}\"");
317    create_start_delete(client, &name, &binpath).await
318}
319
320/// Create → start → delete a transient service with the given binary path; returns the start code.
321async fn create_start_delete(client: &mut SmbClient, name: &str, binpath: &str) -> Result<u32> {
322    let file_id = client
323        .open_pipe("svcctl")
324        .await
325        .map_err(|e| RpcError::Protocol(format!("open \\svcctl: {e}")))?;
326    let mut scm = SvcctlClient::bind(client, file_id).await?;
327    let scm_handle = scm.open_scm().await?;
328    let svc = scm.create_service(&scm_handle, name, binpath).await?;
329    let start_ret = scm.start_service(&svc).await?;
330    let del_ret = scm.delete_service(&svc).await?;
331    scm.close_handle(&svc).await;
332    scm.close_handle(&scm_handle).await;
333    if del_ret != 0 {
334        tracing::warn!("RDeleteService returned win32 {del_ret}");
335    }
336    Ok(start_ret)
337}
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342
343    #[test]
344    fn create_service_stub_shape() {
345        // handle(20) + inline WSTR("X\0": max/off/act + 2 wchars = 16) then the scalar block.
346        let scm = ScHandle([0x11; 20]);
347        let stub = encode_create_service(&scm, "X", "cmd /c whoami");
348        assert_eq!(&stub[..20], &[0x11u8; 20]);
349        let d = |o: usize| u32::from_le_bytes(stub[o..o + 4].try_into().unwrap());
350        assert_eq!(d(20), 2, "lpServiceName WSTR max_count = 2 (X\\0)");
351        assert_eq!(d(24), 0, "offset = 0");
352        assert_eq!(d(28), 2, "actual_count = 2");
353        // chars at 32..36 ('X',0), then lpDisplayName NULL at 36, then the access dwords.
354        assert_eq!(d(36), 0, "lpDisplayName must be NULL");
355        assert_eq!(d(40), SERVICE_ALL_ACCESS);
356        assert_eq!(d(44), SERVICE_WIN32_OWN_PROCESS);
357        assert_eq!(d(48), SERVICE_DEMAND_START);
358        assert_eq!(d(52), SERVICE_ERROR_IGNORE);
359        assert_eq!(
360            d(56),
361            13 + 1,
362            "lpBinaryPathName WSTR max_count = 14 (cmd /c whoami\\0)"
363        );
364    }
365
366    #[test]
367    fn open_scm_stub_is_two_nulls_plus_access() {
368        let stub = encode_open_scm(SC_MANAGER_ALL_ACCESS);
369        assert_eq!(stub, vec![0, 0, 0, 0, 0, 0, 0, 0, 0x3f, 0x00, 0x0f, 0x00]);
370    }
371}