| 1 |
"""Helpers for PowerShell's CLIXML data""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import base64 |
| 6 |
import re |
| 7 |
import xml.etree.ElementTree as ET |
| 8 |
|
| 9 |
# This is weird, we are matching on byte sequences that match the utf-16-be |
| 10 |
# matches for '_x(a-fA-F0-9){4}_'. The \x00 and {4} will match the hex sequence |
| 11 |
# when it is encoded as utf-16-be byte sequence. |
| 12 |
_STRING_DESERIAL_FIND = re.compile(rb"\x00_\x00x((?:\x00[a-fA-F0-9]){4})\x00_") |
| 13 |
|
| 14 |
# Finds _x in a case insensitive way, _x is the escape sequence for a CLIXML |
| 15 |
# str so needs to be escaped first. |
| 16 |
_STRING_SERIAL_ESCAPE_ESCAPE = re.compile("(?i)_(x)") |
| 17 |
|
| 18 |
# Finds C0, C1, and surrogate pairs in a unicode string for us to encode |
| 19 |
# according to the PSRP rules. |
| 20 |
_STRING_SERIAL_ESCAPE = re.compile("[\u0000-\u001f\u007f-\u009f\ud800-\ud8ff\udc00-\udfff\U00010000-\U0010ffff]") |
| 21 |
|
| 22 |
_VT_COLOR_PATTERN = re.compile(rb"\x1b\[[0-9;]*m") |
| 23 |
|
| 24 |
|
| 25 |
def replace_stderr_clixml(stderr: bytes) -> bytes: |
| 26 |
"""Replace CLIXML with stderr data. |
| 27 |
|
| 28 |
Tries to replace an embedded CLIXML string with the actual stderr data. If |
| 29 |
it fails to parse the CLIXML data, it will return the original data. This |
| 30 |
will replace any line inside the stderr string that contains a valid CLIXML |
| 31 |
sequence. |
| 32 |
|
| 33 |
:param bytes stderr: The stderr to try and decode. |
| 34 |
:returns: The stderr with the decoded CLIXML data or the original data. |
| 35 |
""" |
| 36 |
clixml_header = b"#< CLIXML" |
| 37 |
|
| 38 |
# Instead of checking both patterns we just see if the next char |
| 39 |
# is \r or \n to match both Windows and POSIX newline after the marker. |
| 40 |
clixml_idx = stderr.find(clixml_header) |
| 41 |
if clixml_idx == -1: |
| 42 |
return stderr |
| 43 |
|
| 44 |
newline_idx = clixml_idx + 9 |
| 45 |
if len(stderr) < (newline_idx + 1) or stderr[newline_idx] not in (ord(b'\r'), ord(b'\n')): |
| 46 |
return stderr |
| 47 |
|
| 48 |
lines: list[bytes] = [] |
| 49 |
is_clixml = False |
| 50 |
for line in stderr.splitlines(True): |
| 51 |
if is_clixml: |
| 52 |
is_clixml = False |
| 53 |
|
| 54 |
# If the line does not contain the closing CLIXML tag, we just |
| 55 |
# add the found header line and this line without trying to parse. |
| 56 |
end_idx = line.find(b"</Objs>") |
| 57 |
if end_idx == -1: |
| 58 |
lines.append(clixml_header) |
| 59 |
lines.append(line) |
| 60 |
continue |
| 61 |
|
| 62 |
clixml = line[: end_idx + 7] |
| 63 |
remaining = line[end_idx + 7 :] |
| 64 |
|
| 65 |
# While we expect the stderr to be UTF-8 encoded, we fallback to |
| 66 |
# the most common "ANSI" codepage used by Windows cp437 if it is |
| 67 |
# not valid UTF-8. |
| 68 |
try: |
| 69 |
clixml_text = clixml.decode("utf-8") |
| 70 |
except UnicodeDecodeError: |
| 71 |
clixml_text = clixml.decode("cp437") |
| 72 |
|
| 73 |
try: |
| 74 |
decoded_clixml = extract_clixml_strings(clixml_text, stream="Error") |
| 75 |
lines.append("".join(decoded_clixml).encode('utf-8', errors='surrogatepass')) |
| 76 |
if remaining: |
| 77 |
lines.append(remaining) |
| 78 |
|
| 79 |
except Exception: |
| 80 |
# Any errors and we just add the original CLIXML header and |
| 81 |
# line back in. |
| 82 |
lines.append(clixml_header) |
| 83 |
lines.append(line) |
| 84 |
|
| 85 |
elif line.startswith(clixml_header): |
| 86 |
# The next line should contain the full CLIXML data. |
| 87 |
clixml_header = line # Preserve original newlines value. |
| 88 |
is_clixml = True |
| 89 |
|
| 90 |
else: |
| 91 |
lines.append(line) |
| 92 |
|
| 93 |
# This should never happen but if there was a CLIXML header without a newline |
| 94 |
# following it, we need to add it back. |
| 95 |
if is_clixml: |
| 96 |
lines.append(clixml_header) |
| 97 |
|
| 98 |
# PowerShell 7 is not consistent at all with disabling VT color codes, |
| 99 |
# especially in the CLIXML stderr. Instead of trying to hack it in through |
| 100 |
# env vars that may or may not work we just strip it from the output. |
| 101 |
return _VT_COLOR_PATTERN.sub(b"", b"".join(lines)) |
| 102 |
|
| 103 |
|
| 104 |
def extract_clixml_strings( |
| 105 |
data: str, |
| 106 |
stream: str | None = None, |
| 107 |
) -> list[str]: |
| 108 |
""" |
| 109 |
Takes a string that contains a CLIXML <Objs> element and extracts any |
| 110 |
string elements within. This is a rudimentary extraction designed for |
| 111 |
stderr CLIXML and -EncodedArguments. |
| 112 |
|
| 113 |
:param data: The raw CLIXML string. |
| 114 |
:param stream: The optional string to extra the data for. |
| 115 |
:returns: A list of CLIXML strings encoded within the CLIXML string. |
| 116 |
""" |
| 117 |
lines: list[str] = [] |
| 118 |
|
| 119 |
# A serialized string will serialize control chars and surrogate pairs as |
| 120 |
# _xDDDD_ values where DDDD is the hex representation of a big endian |
| 121 |
# UTF-16 code unit. As a surrogate pair uses 2 UTF-16 code units, we need |
| 122 |
# to operate our text replacement on the utf-16-be byte encoding of the raw |
| 123 |
# text. This allows us to replace the _xDDDD_ values with the actual byte |
| 124 |
# values and then decode that back to a string from the utf-16-be bytes. |
| 125 |
def rplcr(matchobj: re.Match) -> bytes: |
| 126 |
match_hex = matchobj.group(1) |
| 127 |
hex_string = match_hex.decode("utf-16-be") |
| 128 |
return base64.b16decode(hex_string.upper()) |
| 129 |
|
| 130 |
# There are some scenarios where the stderr contains a nested CLIXML element like |
| 131 |
# '<# CLIXML\r\n<# CLIXML\r\n<Objs>...</Objs><Objs>...</Objs>'. |
| 132 |
# Parse each individual <Objs> element and add the error strings to our stderr list. |
| 133 |
# https://github.com/ansible/ansible/issues/69550 |
| 134 |
while data: |
| 135 |
start_idx = data.find("<Objs ") |
| 136 |
end_idx = data.find("</Objs>") |
| 137 |
if start_idx == -1 or end_idx == -1: |
| 138 |
break |
| 139 |
|
| 140 |
end_idx += 7 |
| 141 |
current_element = data[start_idx:end_idx] |
| 142 |
data = data[end_idx:] |
| 143 |
|
| 144 |
clixml = ET.fromstring(current_element) |
| 145 |
namespace_match = re.match(r'{(.*)}', clixml.tag) |
| 146 |
namespace = f"{{{namespace_match.group(1)}}}" if namespace_match else "" |
| 147 |
|
| 148 |
entries = clixml.findall(".//%sS" % namespace) |
| 149 |
if not entries: |
| 150 |
continue |
| 151 |
|
| 152 |
# If this is a new CLIXML element, add a newline to separate the messages. |
| 153 |
if lines: |
| 154 |
lines.append("\r\n") |
| 155 |
|
| 156 |
for string_entry in entries: |
| 157 |
actual_stream = string_entry.attrib.get('S', None) |
| 158 |
if actual_stream != stream: |
| 159 |
continue |
| 160 |
|
| 161 |
b_line = (string_entry.text or "").encode("utf-16-be") |
| 162 |
b_escaped = re.sub(_STRING_DESERIAL_FIND, rplcr, b_line) |
| 163 |
|
| 164 |
lines.append(b_escaped.decode("utf-16-be", errors="surrogatepass")) |
| 165 |
|
| 166 |
return lines |
| 167 |
|
| 168 |
|
| 169 |
def build_array_list_clixml( |
| 170 |
values: list[str], |
| 171 |
) -> str: |
| 172 |
"""Builds a CLIXML string representing a System.Collections.ArrayList of strings.""" |
| 173 |
|
| 174 |
def rplcr(matchobj: object) -> str: |
| 175 |
surrogate_char = matchobj.group(0) |
| 176 |
byte_char = surrogate_char.encode("utf-16-be", errors="surrogatepass") |
| 177 |
hex_char = base64.b16encode(byte_char).decode() |
| 178 |
hex_split = [hex_char[i : i + 4] for i in range(0, len(hex_char), 4)] |
| 179 |
|
| 180 |
return "".join([f"_x{i}_" for i in hex_split]) |
| 181 |
|
| 182 |
objs = ET.Element('Objs', xmlns="http://schemas.microsoft.com/powershell/2004/04", Version="1.1.0.1") |
| 183 |
obj = ET.SubElement(objs, 'Obj', RefId="0") |
| 184 |
|
| 185 |
tn = ET.SubElement(obj, 'TN', RefId="0") |
| 186 |
ET.SubElement(tn, 'T').text = "System.Collections.ArrayList" |
| 187 |
ET.SubElement(tn, 'T').text = "System.Object" |
| 188 |
|
| 189 |
lst = ET.SubElement(obj, 'LST') |
| 190 |
for v in values: |
| 191 |
# Before running the translation we need to make sure that '_x' is |
| 192 |
# escaped as '_x005F_x'. While MS-PSRP doesn't state this, the x is |
| 193 |
# case insensitive so we need to escape both '_x' and '_X'. |
| 194 |
v = re.sub(_STRING_SERIAL_ESCAPE_ESCAPE, r"_x005F_\1", v) |
| 195 |
|
| 196 |
# Escape any control or codepoints that are represented as a |
| 197 |
# surrogate pair in UTF-16. |
| 198 |
v = re.sub(_STRING_SERIAL_ESCAPE, rplcr, v) |
| 199 |
ET.SubElement(lst, 'S').text = v |
| 200 |
|
| 201 |
return ET.tostring(objs, encoding='unicode') |