Debian Codegraph @

lib/ansible/_internal/_powershell/_script.py

raw
1 """Helpers for PowerShell command line and scripting arguments."""
2
3 from __future__ import annotations
4
5 import base64
6 import re
7 import shlex
8
9 from . import _clixml
10
11 # There are 5 chars that need to be escaped in a single quote.
12 # https://github.com/PowerShell/PowerShell/blob/b7cb335f03fe2992d0cbd61699de9d9aafa1d7c1/src/System.Management.Automation/engine/parser/CharTraits.cs#L265-L272
13 _PWSH_SINGLE_QUOTES = re.compile("(['\u2018\u2019\u201a\u201b])")
14
15 # These chars are a known set of chars that are safe to use as a bare command.
16 _PWSH_BARE_CMD = re.compile(r'^[\w\-\\\.\[\]/_~!%^:]+$')
17
18
19 def _get_encoded_arguments(
20 script: str,
21 args: list[str] | None = None,
22 ) -> list[str]:
23 """Builds an -EncodedCommand cmdline argument
24
25 Returns a list of arguments that can be used with PowerShell to invoke
26 a script with optional arguments.
27
28 :param script: The script to encode.
29 :param args: The string arguments to encode.
30 :returns: The encoded arguments string value as a base64 string.
31 """
32 encoded_cmd = base64.b64encode(script.encode('utf-16-le')).decode()
33 pwsh_args = ['-EncodedCommand', encoded_cmd]
34 if not args:
35 return pwsh_args
36
37 # -EncodedCommand does not accept normal positional parameters. Instead it
38 # only supports extra args through an encoded CLIXML string.
39 clixml = _clixml.build_array_list_clixml(args)
40 encoded_args = base64.b64encode(clixml.encode('utf-16-le')).decode()
41 pwsh_args.extend(['-EncodedArguments', encoded_args])
42
43 return pwsh_args
44
45
46 def parse_encoded_cmdline(
47 cmd: str,
48 ) -> tuple[str, list[str]] | None:
49 """Parses a PowerShell encoded command line string.
50
51 Attempts to parse a command line string for the encoded command/arguments.
52 Will return None if not present or if the command line is not a valid for
53 PowerShell.
54
55 :param cmd: The command line string to parse.
56 :returns: A tuple of the decoded command and list of arguments or None if ill-formed.
57 """
58 cmd_split = shlex.split(cmd)
59
60 try:
61 enc_cmd_idx = cmd_split.index("-EncodedCommand")
62 except ValueError:
63 enc_cmd_idx = -1
64
65 if enc_cmd_idx == -1 or len(cmd_split) <= enc_cmd_idx + 1:
66 return None
67
68 enc_cmd_raw = cmd_split[enc_cmd_idx + 1]
69 enc_cmd = base64.b64decode(enc_cmd_raw).decode('utf-16-le')
70
71 try:
72 enc_arg_idx = cmd_split.index("-EncodedArguments")
73 except ValueError:
74 return enc_cmd, []
75
76 if len(cmd_split) <= enc_arg_idx + 1:
77 # Was ill-formed so assume it's not a valid encoded pwsh cmd.
78 return None
79
80 clixml_raw = cmd_split[enc_arg_idx + 1]
81 clixml = base64.b64decode(clixml_raw).decode('utf-16-le')
82 cmd_args = _clixml.extract_clixml_strings(clixml)
83
84 return enc_cmd, cmd_args
85
86
87 def get_pwsh_encoded_cmdline(
88 script: str,
89 *,
90 args: list[str] | None = None,
91 pwsh_path: str = 'powershell',
92 disable_input: bool = False,
93 override_execution_policy: bool = False,
94 ) -> list[str]:
95 """Builds a PowerShell command line argument list.
96
97 Builds the encoded command line arguments for running the provided script.
98
99 :param script: The PowerShell script to encode.
100 :param args: Optional positional arguments to the script.
101 :param pwsh_path: The PowerShell executable path, defaults to powershell.
102 :param disable_input: Tells PowerShell to not read input from stdin.
103 :param override_execution_policy: Adds args to override the execution policy.
104 :returns: The command line arguments as a list.
105 """
106 cmd_args = [pwsh_path, '-NoProfile', '-NonInteractive']
107 if override_execution_policy:
108 cmd_args.extend(['-ExecutionPolicy', 'Unrestricted'])
109
110 if disable_input:
111 cmd_args.extend(['-InputFormat', 'None'])
112
113 encoded_args = _get_encoded_arguments(script, args)
114 cmd_args.extend(encoded_args)
115
116 return cmd_args
117
118
119 def build_pwsh_cmd_statement(
120 command: str,
121 args: list[str] | None = None,
122 ) -> str:
123 """Builds a PowerShell command statement.
124
125 Builds a valid PowerShell command statement with optional arguments. This
126 statement can be used in a PowerShell script to execute a command with the
127 arguments provided.
128
129 :param command: The PowerShell command to execute.
130 :param args: The arguments to provide to the command.
131 :returns: The PowerShell script as a string representing this command statement.
132 """
133 pwsh_cmd = quote_pwsh_argument(command)
134 if pwsh_cmd != command:
135 # If we quoted the cmd we need to add the call operator for pwsh
136 # to treat it as a command.
137 pwsh_cmd = f"& {pwsh_cmd}"
138
139 if args:
140 remaining_args = " ".join([quote_pwsh_argument(a) for a in args])
141 pwsh_cmd += f" {remaining_args}"
142
143 return pwsh_cmd
144
145
146 def quote_pwsh_argument(
147 value: str,
148 *,
149 force_quote: bool = False,
150 ) -> str:
151 """Quotes a value for use as a PowerShell argument.
152
153 This safely quotes the provided value for use in a PowerShell script. The
154 value will either be a bare keyword or a quoted string that is safe to use
155 in a PowerShell script.
156
157 :param value: The value to quote.
158 :param force_quote: Force the quotes even if the value doesn't need it.
159 :returns: The value that is safe to use as a PowerShell argument.
160 """
161 if not force_quote and _PWSH_BARE_CMD.match(value):
162 return value
163
164 # Escaping a pwsh string for single quotes is to just double up on the
165 # single quote values inside the string.
166 return f"'{_PWSH_SINGLE_QUOTES.sub(r'\1\1', value)}'"