1#![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
42pub 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
55const 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
62const 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#[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
89fn encode_open_scm(access: u32) -> Vec<u8> {
91 let mut e = NdrEncoder::new();
92 e.null_ptr(); e.null_ptr(); e.u32(access);
95 e.into_bytes()
96}
97
98fn encode_create_service(scm: &ScHandle, name: &str, binpath: &str) -> Vec<u8> {
107 let mut e = NdrEncoder::new();
108 scm.encode(&mut e); e.conformant_varying_wstr(name); e.align(4);
111 e.null_ptr(); e.u32(SERVICE_ALL_ACCESS); e.u32(SERVICE_WIN32_OWN_PROCESS); e.u32(SERVICE_DEMAND_START); e.u32(SERVICE_ERROR_IGNORE); e.conformant_varying_wstr(binpath); e.align(4);
118 e.null_ptr(); e.null_ptr(); e.null_ptr(); e.u32(0); e.null_ptr(); e.null_ptr(); e.u32(0); e.into_bytes()
126}
127
128fn encode_start_service(svc: &ScHandle) -> Vec<u8> {
130 let mut e = NdrEncoder::new();
131 svc.encode(&mut e);
132 e.u32(0); e.null_ptr(); 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
143fn 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
151pub 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 let mut d = NdrDecoder::new(&resp);
203 let tag_ref = d.u32()?;
204 if tag_ref != 0 {
205 let _ = d.u32(); }
207 ScHandle::decode(&mut d)
208 }
209
210 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
235pub 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
244pub 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"); let out_win = format!("C:\\{out_rel}"); let full = format!("{command} > {out_win} 2>&1");
260 let binpath = format!("%COMSPEC% /Q /c start \"\" /b %COMSPEC% /Q /c \"{full}\"");
261
262 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 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
307pub 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
320async 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 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 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}