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";
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";
}
#[derive(Debug, Clone, Copy, Default)]
pub struct CreateOptions {
pub max_envelope_kb: u32, pub timeout_ms: u32, pub locale: &'static str, pub codepage: u32, }
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 {
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
}
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,
&[],
);
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)
}
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)
}
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)
}
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)
}
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";
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("&"),
'<' => o.push_str("<"),
'>' => o.push_str(">"),
'"' => o.push_str("""),
'\'' => o.push_str("'"),
_ => o.push(c),
}
}
o
}
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")
}
pub fn parse_command_id(xml: &str) -> Option<String> {
find_element_text(xml, "CommandId")
}
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
}
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
}