Debian Codegraph @

lib/ansible/executor/powershell/module_manifest.py

raw
1 # (c) 2018 Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import annotations
5
6 import base64
7 import dataclasses
8 import errno
9 import json
10 import os
11 import pkgutil
12 import secrets
13 import re
14 import typing as t
15
16 from importlib import import_module
17
18 from ansible.module_utils.compat.version import LooseVersion
19
20 from ansible import constants as C
21
22 from ansible.module_utils.common.json import Direction, get_module_encoder
23 from ansible.errors import AnsibleError, AnsibleFileNotFound
24 from ansible.module_utils import secrets as _secrets
25 from ansible.module_utils.common.text.converters import to_bytes, to_text
26 from ansible.plugins.become import BecomeBase
27 from ansible.plugins.become.runas import BecomeModule as RunasBecomeModule
28 from ansible.plugins.loader import ps_module_utils_loader
29
30
31 GZIP_AVAILABLE = True
32 try:
33 import gzip
34 except ImportError:
35 GZIP_AVAILABLE = False
36
37
38 @dataclasses.dataclass(frozen=True)
39 class _ExecManifest:
40 scripts: dict[str, _ScriptInfo] = dataclasses.field(default_factory=dict)
41 actions: list[_ManifestAction] = dataclasses.field(default_factory=list)
42 signed_hashlist: list[str] = dataclasses.field(default_factory=list)
43
44
45 @dataclasses.dataclass(frozen=True, kw_only=True)
46 class _ScriptInfo:
47 content: dataclasses.InitVar[bytes]
48 path: str
49 script: str = dataclasses.field(init=False)
50
51 def __post_init__(self, content: bytes) -> None:
52 object.__setattr__(self, 'script', base64.b64encode(content).decode())
53
54
55 @dataclasses.dataclass(frozen=True, kw_only=True)
56 class _ManifestAction:
57 name: str
58 params: dict[str, object] = dataclasses.field(default_factory=dict)
59 secure_params: dict[str, object] = dataclasses.field(default_factory=dict)
60
61
62 class PSModuleDepFinder(object):
63
64 def __init__(self) -> None:
65 # This is also used by validate-modules to get a module's required utils in base and a collection.
66 self.scripts: dict[str, _ScriptInfo] = {}
67 self.signed_hashlist: set[str] = set()
68
69 if builtin_hashlist := _get_powershell_signed_hashlist():
70 self.signed_hashlist.add(builtin_hashlist.path)
71 self.scripts[builtin_hashlist.path] = builtin_hashlist
72
73 self._util_deps: dict[str, set[str]] = {}
74
75 self.ps_version: str | None = None
76 self.os_version: str | None = None
77 self.become = False
78
79 self._re_cs_module = [
80 # Reference C# module_util in another C# util, this must always be the fully qualified name.
81 # 'using ansible_collections.{namespace}.{collection}.plugins.module_utils.{name}'
82 re.compile(to_bytes(r'(?i)^using\s((Ansible\..+)|'
83 r'(ansible_collections\.\w+\.\w+\.plugins\.module_utils\.[\w\.]+));\s*$')),
84 ]
85
86 self._re_cs_in_ps_module = [
87 # Reference C# module_util in a PowerShell module
88 # '#AnsibleRequires -CSharpUtil Ansible.{name}'
89 # '#AnsibleRequires -CSharpUtil ansible_collections.{namespace}.{collection}.plugins.module_utils.{name}'
90 # '#AnsibleRequires -CSharpUtil ..module_utils.{name}'
91 # Can have '-Optional' at the end to denote the util is optional
92 re.compile(to_bytes(r'(?i)^#\s*ansiblerequires\s+-csharputil\s+((Ansible\.[\w\.]+)|'
93 r'(ansible_collections\.\w+\.\w+\.plugins\.module_utils\.[\w\.]+)|'
94 r'(\.[\w\.]+))(?P<optional>\s+-Optional){0,1}')),
95 ]
96
97 self._re_ps_module = [
98 # Original way of referencing a builtin module_util
99 # '#Requires -Module Ansible.ModuleUtils.{name}
100 re.compile(to_bytes(r'(?i)^#\s*requires\s+\-module(?:s?)\s*(Ansible\.ModuleUtils\..+)')),
101 # New way of referencing a builtin and collection module_util
102 # '#AnsibleRequires -PowerShell Ansible.ModuleUtils.{name}'
103 # '#AnsibleRequires -PowerShell ansible_collections.{namespace}.{collection}.plugins.module_utils.{name}'
104 # '#AnsibleRequires -PowerShell ..module_utils.{name}'
105 # Can have '-Optional' at the end to denote the util is optional
106 re.compile(to_bytes(r'(?i)^#\s*ansiblerequires\s+-powershell\s+((Ansible\.ModuleUtils\.[\w\.]+)|'
107 r'(ansible_collections\.\w+\.\w+\.plugins\.module_utils\.[\w\.]+)|'
108 r'(\.[\w\.]+))(?P<optional>\s+-Optional){0,1}')),
109 ]
110
111 self._re_ps_version = re.compile(to_bytes(r'(?i)^#requires\s+\-version\s+([0-9]+(\.[0-9]+){0,3})$'))
112 self._re_os_version = re.compile(to_bytes(r'(?i)^#ansiblerequires\s+\-osversion\s+([0-9]+(\.[0-9]+){0,3})$'))
113 self._re_become = re.compile(to_bytes(r'(?i)^#ansiblerequires\s+\-become$'))
114
115 def scan_exec_script(self, name: str) -> None:
116 # scans lib/ansible/executor/powershell for scripts used in the module
117 # exec side. It also scans these scripts for any dependencies
118 if name in self.scripts:
119 return
120
121 exec_code = _get_powershell_script(name)
122 self.scripts[name] = _ScriptInfo(
123 content=exec_code,
124 path=name,
125 )
126 self.scan_module(exec_code, powershell=True)
127
128 def scan_module(
129 self,
130 module_data: bytes,
131 fqn: str | None = None,
132 powershell: bool = True,
133 ) -> set[str]:
134 lines = module_data.split(b'\n')
135 module_utils: set[tuple[str, str, bool]] = set()
136
137 if fqn and fqn.startswith("ansible_collections."):
138 submodules = fqn.split('.')
139 collection_name = '.'.join(submodules[:3])
140
141 collection_hashlist = _get_powershell_signed_hashlist(collection_name)
142 if collection_hashlist and collection_hashlist.path not in self.signed_hashlist:
143 self.signed_hashlist.add(collection_hashlist.path)
144 self.scripts[collection_hashlist.path] = collection_hashlist
145
146 if powershell:
147 checks = [
148 # PS module contains '#Requires -Module Ansible.ModuleUtils.*'
149 # PS module contains '#AnsibleRequires -Powershell Ansible.*' (or collections module_utils ref)
150 (self._re_ps_module, ".psm1"),
151 # PS module contains '#AnsibleRequires -CSharpUtil Ansible.*' (or collections module_utils ref)
152 (self._re_cs_in_ps_module, ".cs"),
153 ]
154 else:
155 checks = [
156 # CS module contains 'using Ansible.*;' or 'using ansible_collections.ns.coll.plugins.module_utils.*;'
157 (self._re_cs_module, ".cs"),
158 ]
159
160 for line in lines:
161 for patterns, util_extension in checks:
162 for pattern in patterns:
163 match = pattern.match(line)
164 if match:
165 # tolerate windows line endings by stripping any remaining
166 # newline chars
167 module_util_name = to_text(match.group(1).rstrip())
168 match_dict = match.groupdict()
169 optional = match_dict.get('optional', None) is not None
170 module_utils.add((module_util_name, util_extension, optional))
171 break
172
173 if not powershell:
174 continue
175
176 if ps_version_match := self._re_ps_version.match(line):
177 self._parse_version_match(ps_version_match, "ps_version")
178
179 if os_version_match := self._re_os_version.match(line):
180 self._parse_version_match(os_version_match, "os_version")
181
182 # once become is set, no need to keep on checking recursively
183 if not self.become and self._re_become.match(line):
184 self.become = True
185
186 dependencies: set[str] = set()
187 for name, ext, optional in set(module_utils):
188 util_name = self._scan_module_util(name, ext, fqn, optional)
189 if util_name:
190 dependencies.add(util_name)
191 util_deps = self._util_deps[util_name]
192 dependencies.update(util_deps)
193
194 return dependencies
195
196 def _scan_module_util(
197 self,
198 name: str,
199 ext: str,
200 module_fqn: str | None,
201 optional: bool,
202 ) -> str | None:
203 util_name: str
204 util_path: str
205 util_data: bytes
206 util_fqn: str | None = None
207
208 if name.startswith("Ansible."):
209 # Builtin util, or the old role module_utils reference.
210 util_name = f"{name}{ext}"
211
212 if util_name in self._util_deps:
213 return util_name
214
215 util_path = ps_module_utils_loader.find_plugin(name, ext)
216 if not util_path or not os.path.exists(util_path):
217 if optional:
218 return None
219
220 raise AnsibleError(f"Could not find imported module util '{name}'")
221
222 with open(util_path, 'rb') as mu_file:
223 util_data = mu_file.read()
224
225 else:
226 # Collection util, load the package data based on the util import.
227 submodules = name.split(".")
228 if name.startswith('.'):
229 fqn_submodules = (module_fqn or "").split('.')
230 for submodule in submodules:
231 if submodule:
232 break
233 del fqn_submodules[-1]
234
235 submodules = fqn_submodules + [s for s in submodules if s]
236
237 util_package = '.'.join(submodules[:-1])
238 util_resource_name = f"{submodules[-1]}{ext}"
239 util_fqn = f"{util_package}.{submodules[-1]}"
240 util_name = f"{util_package}.{util_resource_name}"
241
242 if util_name in self._util_deps:
243 return util_name
244
245 try:
246 module_util = import_module(util_package)
247 util_code = pkgutil.get_data(util_package, util_resource_name)
248 if util_code is None:
249 raise ImportError("No package data found")
250 util_data = util_code
251
252 # Get the path of the util which is required for coverage collection.
253 resource_paths = list(module_util.__path__)
254 if len(resource_paths) != 1:
255 # This should never happen with a collection but we are just being defensive about it.
256 raise AnsibleError(f"Internal error: Referenced module_util package '{util_package}' contains 0 "
257 "or multiple import locations when we only expect 1.")
258
259 util_path = os.path.join(resource_paths[0], util_resource_name)
260 except (ImportError, OSError) as err:
261 if getattr(err, "errno", errno.ENOENT) == errno.ENOENT:
262 if optional:
263 return None
264
265 raise AnsibleError(f"Could not find collection imported module support code for '{name}'")
266
267 else:
268 raise
269
270 # This is important to be set before scan_module is called to avoid
271 # recursive dependencies.
272 self.scripts[util_name] = _ScriptInfo(
273 content=util_data,
274 path=util_path,
275 )
276
277 # It is important this is set before calling scan_module to ensure
278 # recursive dependencies don't result in an infinite loop.
279 dependencies = self._util_deps[util_name] = set()
280
281 util_deps = self.scan_module(util_data, fqn=util_fqn, powershell=(ext == ".psm1"))
282 dependencies.update(util_deps)
283 for dep in dependencies:
284 if dep_list := self._util_deps.get(dep):
285 dependencies.update(dep_list)
286
287 if ext == ".cs":
288 # Any C# code requires the AddType.psm1 module to load.
289 dependencies.add("Ansible.ModuleUtils.AddType.psm1")
290 self._scan_module_util("Ansible.ModuleUtils.AddType", ".psm1", None, False)
291
292 return util_name
293
294 def _parse_version_match(self, match: re.Match, attribute: str) -> None:
295 new_version = to_text(match.group(1)).rstrip()
296
297 # PowerShell cannot cast a string of "1" to Version, it must have at
298 # least the major.minor for it to be valid so we append 0
299 if match.group(2) is None:
300 new_version = f"{new_version}.0"
301
302 existing_version = getattr(self, attribute, None)
303 if existing_version is None:
304 setattr(self, attribute, new_version)
305 else:
306 # determine which is the latest version and set that
307 if LooseVersion(new_version) > LooseVersion(existing_version):
308 setattr(self, attribute, new_version)
309
310
311 def _bootstrap_powershell_script(
312 name: str,
313 parameters: dict[str, t.Any] | None = None,
314 *,
315 has_input: bool = False,
316 ) -> tuple[str, bytes]:
317 """Build bootstrap wrapper for specified script.
318
319 Builds the bootstrap wrapper and input needed to run the specified executor
320 PowerShell script specified.
321
322 :param name: The name of the PowerShell script to run.
323 :param parameters: The parameters to pass to the script.
324 :param has_input: The script will be provided with input data.
325 :return: The bootstrap wrapper and input to provide to it.
326 """
327 exec_manifest = _ExecManifest()
328
329 script = _get_powershell_script(name)
330 exec_manifest.scripts[name] = _ScriptInfo(
331 content=script,
332 path=name,
333 )
334
335 exec_manifest.actions.append(
336 _ManifestAction(
337 name=name,
338 params=parameters or {},
339 )
340 )
341
342 if hashlist := _get_powershell_signed_hashlist():
343 exec_manifest.signed_hashlist.append(hashlist.path)
344 exec_manifest.scripts[hashlist.path] = hashlist
345
346 bootstrap_wrapper = _get_powershell_script("bootstrap_wrapper.ps1")
347 bootstrap_input = _get_bootstrap_input(exec_manifest)
348 if has_input:
349 bootstrap_input += b"\n\0\0\0\0\n"
350
351 return bootstrap_wrapper.decode(), bootstrap_input
352
353
354 def _get_powershell_script(
355 name: str,
356 ) -> bytes:
357 """Get the requested PowerShell script.
358
359 Gets the script stored in the ansible.executore.powershell package.
360
361 :param name: The name of the PowerShell script to retrieve.
362 :return: The contents of the requested PowerShell script as a byte string.
363 """
364 package_name = 'ansible.executor.powershell'
365
366 code = pkgutil.get_data(package_name, name)
367 if code is None:
368 raise AnsibleFileNotFound(f"Could not find powershell script '{package_name}.{name}'")
369
370 if name == 'bootstrap_wrapper.ps1':
371 # bootstrap_wrapper is special in that it is never signed and we want
372 # it as small as possible for command line length limits.
373 code = _strip_comments_and_whitespace(code)
374 return code
375
376 try:
377 sig_data = pkgutil.get_data(package_name, f"{name}.authenticode")
378 except FileNotFoundError:
379 sig_data = None
380
381 if sig_data:
382 code = code + b"\r\n" + b"\r\n".join(sig_data.splitlines()) + b"\r\n"
383
384 return code
385
386
387 def _create_powershell_wrapper(
388 *,
389 name: str,
390 module_data: bytes,
391 module_path: str,
392 module_args: dict[t.Any, t.Any],
393 environment: dict[str, str],
394 async_timeout: int,
395 become_plugin: BecomeBase | None,
396 substyle: t.Literal["powershell", "script"],
397 task_vars: dict[str, t.Any],
398 profile: str,
399 pwsh_interpreter: str | None = None,
400 ) -> bytes:
401 """Creates module or script wrapper for PowerShell.
402
403 Creates the input data to provide to bootstrap_wrapper.ps1 when running a
404 PowerShell module or script.
405
406 :param name: The fully qualified name of the module or script filename (without extension).
407 :param module_data: The data of the module or script.
408 :param module_path: The path of the module or script.
409 :param module_args: The arguments to pass to the module or script.
410 :param environment: The environment variables to set when running the module or script.
411 :param async_timeout: The timeout to use for async execution or 0 for no async.
412 :param become_plugin: The become plugin to use for privilege escalation or None for no become.
413 :param substyle: The substyle of the module or script to run [powershell or script].
414 :param task_vars: The task variables used on the task.
415 :param pwsh_interpreter: The pwsh interpreter to use.
416
417 :return: The input data for bootstrap_wrapper.ps1 as a byte string.
418 """
419
420 actions: list[_ManifestAction] = []
421 finder = PSModuleDepFinder()
422 finder.scan_exec_script('module_wrapper.ps1')
423
424 ext = os.path.splitext(module_path)[1]
425 name_with_ext = f"{name}{ext}"
426 finder.scripts[name_with_ext] = _ScriptInfo(
427 content=module_data,
428 path=module_path,
429 )
430
431 module_params: dict[str, t.Any] = {
432 'Script': name_with_ext,
433 'Environment': environment,
434 }
435 secure_module_params: dict[str, t.Any] = {}
436
437 if substyle != 'script':
438 module_deps = finder.scan_module(
439 module_data,
440 fqn=name,
441 powershell=True,
442 )
443 cs_deps = []
444 ps_deps = []
445 for dep in module_deps:
446 if dep.endswith('.cs'):
447 cs_deps.append(dep)
448 else:
449 ps_deps.append(dep)
450
451 encoder = get_module_encoder(profile, Direction.CONTROLLER_TO_MODULE)
452 module_arg_json = json.dumps(module_args, cls=encoder)
453
454 module_params |= {
455 'ArgumentJSON': module_arg_json,
456 # FUTURE: Provide the profile to the module wrapper.
457 # 'ArgumentProfile': profile,
458 'CSharpModules': cs_deps,
459 'PowerShellModules': ps_deps,
460 'ForModule': True,
461 }
462
463 if 'Ansible.Secrets.cs' in cs_deps:
464 module_secrets = _secrets._secret_masker.secrets_in_json(module_arg_json)
465 secure_module_params['Secrets'] = list(module_secrets)
466
467 if become_plugin or finder.become:
468 become_script = 'become_wrapper.ps1'
469 become_params: dict[str, t.Any] = {
470 'BecomeUser': 'SYSTEM',
471 }
472 become_secure_params: dict[str, t.Any] = {}
473
474 if become_plugin:
475 if not isinstance(become_plugin, RunasBecomeModule):
476 msg = f"Become plugin {become_plugin.name} is not supported by the Windows exec wrapper. Make sure to set the become method to runas."
477 raise AnsibleError(msg)
478
479 become_script, become_params, become_secure_params = become_plugin._build_powershell_wrapper_action()
480
481 finder.scan_exec_script('exec_wrapper.ps1')
482 finder.scan_exec_script(become_script)
483 actions.append(
484 _ManifestAction(
485 name=become_script,
486 params=become_params,
487 secure_params=become_secure_params,
488 )
489 )
490
491 if async_timeout > 0:
492 finder.scan_exec_script('bootstrap_wrapper.ps1')
493 finder.scan_exec_script('exec_wrapper.ps1')
494
495 async_dir = environment.get('ANSIBLE_ASYNC_DIR', None)
496 if not async_dir:
497 raise AnsibleError("The environment variable 'ANSIBLE_ASYNC_DIR' is not set.")
498
499 finder.scan_exec_script('async_wrapper.ps1')
500 actions.append(
501 _ManifestAction(
502 name='async_wrapper.ps1',
503 params={
504 'AsyncDir': async_dir,
505 'AsyncJid': f'j{secrets.randbelow(999999999999)}',
506 'StartupTimeout': C.config.get_config_value("WIN_ASYNC_STARTUP_TIMEOUT", variables=task_vars),
507 },
508 )
509 )
510
511 finder.scan_exec_script('async_watchdog.ps1')
512 actions.append(
513 _ManifestAction(
514 name='async_watchdog.ps1',
515 params={
516 'Timeout': async_timeout,
517 },
518 )
519 )
520
521 coverage_output = C.config.get_config_value('COVERAGE_REMOTE_OUTPUT', variables=task_vars)
522 if coverage_output and substyle == 'powershell':
523 path_filter = C.config.get_config_value('COVERAGE_REMOTE_PATHS', variables=task_vars)
524
525 finder.scan_exec_script('coverage_wrapper.ps1')
526 actions.append(
527 _ManifestAction(
528 name='coverage_wrapper.ps1',
529 params={
530 'ModuleName': name_with_ext,
531 'OutputPath': coverage_output,
532 'PathFilter': path_filter,
533 },
534 )
535 )
536
537 actions.append(
538 _ManifestAction(
539 name='module_wrapper.ps1',
540 params=module_params,
541 secure_params=secure_module_params,
542 ),
543 )
544
545 temp_path: str | None = None
546 for temp_key in ['_ansible_tmpdir', '_ansible_remote_tmp']:
547 if temp_value := module_args.get(temp_key, None):
548 temp_path = temp_value
549 break
550
551 exec_manifest = _ExecManifest(
552 scripts=finder.scripts,
553 actions=actions,
554 signed_hashlist=list(finder.signed_hashlist),
555 )
556
557 return _get_bootstrap_input(
558 exec_manifest,
559 min_os_version=finder.os_version,
560 min_ps_version=finder.ps_version,
561 temp_path=temp_path,
562 pwsh_interpreter=pwsh_interpreter,
563 )
564
565
566 def _get_bootstrap_input(
567 manifest: _ExecManifest,
568 min_os_version: str | None = None,
569 min_ps_version: str | None = None,
570 temp_path: str | None = None,
571 pwsh_interpreter: str | None = None,
572 ) -> bytes:
573 """Gets the input for bootstrap_wrapper.ps1
574
575 Gets the input needed to send to bootstrap_wrapper.ps1 to run code through
576 exec_wrapper.ps1.
577
578 :param manifest: The exec wrapper manifest of scripts and actions to run.
579 :param min_os_version: The minimum OS version required to run the scripts.
580 :param min_ps_version: The minimum PowerShell version required to run the scripts.
581 :param temp_path: The temporary path to use for the scripts if needed.
582 :return: The input for bootstrap_wrapper.ps1 as a byte string.
583 """
584 decompress_input = False
585 exec_input = json.dumps(dataclasses.asdict(manifest)).encode()
586
587 # We provide an opt-out config option in case there are unforeseen issues
588 # with compression.
589 if GZIP_AVAILABLE and C.config.get_config_value("_ANSIBALLZ_PWSH_COMPRESSION", variables={}):
590 compressed_input = gzip.compress(exec_input)
591 compressed_b64 = base64.b64encode(compressed_input)
592 if len(compressed_b64) < len(exec_input):
593 exec_input = compressed_b64
594 decompress_input = True
595
596 bootstrap_manifest = {
597 'name': 'exec_wrapper',
598 'script': _get_powershell_script("exec_wrapper.ps1").decode(),
599 'params': {
600 'MinOSVersion': min_os_version,
601 'MinPSVersion': min_ps_version,
602 'TempPath': temp_path,
603 'PwshPath': pwsh_interpreter,
604 'DecompressInput': decompress_input,
605 },
606 }
607
608 bootstrap_input = json.dumps(bootstrap_manifest, ensure_ascii=True).encode()
609
610 return bootstrap_input + b"\n\0\0\0\0\n" + exec_input
611
612
613 def _get_powershell_signed_hashlist(
614 collection: str | None = None,
615 ) -> _ScriptInfo | None:
616 """Gets the signed hashlist script stored in either the Ansible package or for
617 the collection specified.
618
619 :param collection: The collection namespace to get the signed hashlist for or None for the builtin.
620 :return: The _ScriptInfo payload of the signed hashlist script if found, None if not.
621 """
622 resource = 'ansible.config' if collection is None else f"{collection}.meta"
623 signature_file = 'powershell_signatures.psd1'
624
625 try:
626 sig_data = pkgutil.get_data(resource, signature_file)
627 except FileNotFoundError:
628 sig_data = None
629
630 if sig_data:
631 resource_path = f"{resource}.{signature_file}"
632 return _ScriptInfo(content=sig_data, path=resource_path)
633
634 return None
635
636
637 def _strip_comments_and_whitespace(source: bytes) -> bytes:
638 """Removes comments and whitespace from the source string to save space."""
639 buf = []
640 for line in source.splitlines():
641 l = line.strip()
642 if l.startswith(b'#'):
643 line = b''
644 buf.append(line)
645
646 return b'\n'.join(buf)