| 1 |
# Copyright (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 |
DOCUMENTATION = """ |
| 7 |
author: Ansible Core Team |
| 8 |
name: psrp |
| 9 |
short_description: Run tasks over Microsoft PowerShell Remoting Protocol |
| 10 |
description: |
| 11 |
- Run commands or put/fetch on a target via PSRP (WinRM plugin) |
| 12 |
- This is similar to the P(ansible.builtin.winrm#connection) connection plugin which uses the same |
| 13 |
underlying transport but instead runs in a PowerShell interpreter. |
| 14 |
version_added: "2.7" |
| 15 |
requirements: |
| 16 |
- pypsrp>=0.4.0, <1.0.0 (Python library) |
| 17 |
extends_documentation_fragment: |
| 18 |
- connection_pipelining |
| 19 |
options: |
| 20 |
# transport options |
| 21 |
remote_addr: |
| 22 |
description: |
| 23 |
- The hostname or IP address of the remote host. |
| 24 |
default: inventory_hostname |
| 25 |
type: str |
| 26 |
vars: |
| 27 |
- name: inventory_hostname |
| 28 |
- name: ansible_host |
| 29 |
- name: ansible_psrp_host |
| 30 |
remote_user: |
| 31 |
description: |
| 32 |
- The user to log in as. |
| 33 |
type: str |
| 34 |
vars: |
| 35 |
- name: ansible_user |
| 36 |
- name: ansible_psrp_user |
| 37 |
keyword: |
| 38 |
- name: remote_user |
| 39 |
remote_password: |
| 40 |
description: Authentication password for the O(remote_user). Can be supplied as CLI option. |
| 41 |
type: str |
| 42 |
vars: |
| 43 |
- name: ansible_password |
| 44 |
- name: ansible_winrm_pass |
| 45 |
- name: ansible_winrm_password |
| 46 |
aliases: |
| 47 |
- password # Needed for --ask-pass to come through on delegation |
| 48 |
secret: true |
| 49 |
port: |
| 50 |
description: |
| 51 |
- The port for PSRP to connect on the remote target. |
| 52 |
- Default is V(5986) if O(protocol) is not defined or is V(https), |
| 53 |
otherwise the port is V(5985). |
| 54 |
type: int |
| 55 |
vars: |
| 56 |
- name: ansible_port |
| 57 |
- name: ansible_psrp_port |
| 58 |
keyword: |
| 59 |
- name: port |
| 60 |
protocol: |
| 61 |
description: |
| 62 |
- Set the protocol to use for the connection. |
| 63 |
- Default is V(https) if O(port) is not defined or O(port) is not V(5985). |
| 64 |
choices: |
| 65 |
- http |
| 66 |
- https |
| 67 |
type: str |
| 68 |
vars: |
| 69 |
- name: ansible_psrp_protocol |
| 70 |
path: |
| 71 |
description: |
| 72 |
- The URI path to connect to. |
| 73 |
type: str |
| 74 |
vars: |
| 75 |
- name: ansible_psrp_path |
| 76 |
default: 'wsman' |
| 77 |
auth: |
| 78 |
description: |
| 79 |
- The authentication protocol to use when authenticating the remote user. |
| 80 |
- The default, V(negotiate), will attempt to use Kerberos (V(kerberos)) if it is |
| 81 |
available and fall back to NTLM (V(ntlm)) if it isn't. |
| 82 |
type: str |
| 83 |
vars: |
| 84 |
- name: ansible_psrp_auth |
| 85 |
choices: |
| 86 |
- basic |
| 87 |
- certificate |
| 88 |
- negotiate |
| 89 |
- kerberos |
| 90 |
- ntlm |
| 91 |
- credssp |
| 92 |
default: negotiate |
| 93 |
cert_validation: |
| 94 |
description: |
| 95 |
- Whether to validate the remote server's certificate or not. |
| 96 |
- Set to V(ignore) to not validate any certificates. |
| 97 |
- O(ca_cert) can be set to the path of a PEM certificate chain to |
| 98 |
use in the validation. |
| 99 |
choices: |
| 100 |
- validate |
| 101 |
- ignore |
| 102 |
default: validate |
| 103 |
type: str |
| 104 |
vars: |
| 105 |
- name: ansible_psrp_cert_validation |
| 106 |
ca_cert: |
| 107 |
description: |
| 108 |
- The path to a PEM certificate chain to use when validating the server's |
| 109 |
certificate. |
| 110 |
- This value is ignored if O(cert_validation) is set to V(ignore). |
| 111 |
type: path |
| 112 |
vars: |
| 113 |
- name: ansible_psrp_cert_trust_path |
| 114 |
- name: ansible_psrp_ca_cert |
| 115 |
aliases: [ cert_trust_path ] |
| 116 |
connection_timeout: |
| 117 |
description: |
| 118 |
- The connection timeout for making the request to the remote host. |
| 119 |
- This is measured in seconds. |
| 120 |
type: int |
| 121 |
vars: |
| 122 |
- name: ansible_psrp_connection_timeout |
| 123 |
default: 30 |
| 124 |
read_timeout: |
| 125 |
description: |
| 126 |
- The read timeout for receiving data from the remote host. |
| 127 |
- This value must always be greater than O(operation_timeout). |
| 128 |
- This option requires pypsrp >= 0.3. |
| 129 |
- This is measured in seconds. |
| 130 |
type: int |
| 131 |
vars: |
| 132 |
- name: ansible_psrp_read_timeout |
| 133 |
default: 30 |
| 134 |
version_added: '2.8' |
| 135 |
reconnection_retries: |
| 136 |
description: |
| 137 |
- The number of retries on connection errors. |
| 138 |
type: int |
| 139 |
vars: |
| 140 |
- name: ansible_psrp_reconnection_retries |
| 141 |
default: 0 |
| 142 |
version_added: '2.8' |
| 143 |
reconnection_backoff: |
| 144 |
description: |
| 145 |
- The backoff time to use in between reconnection attempts. |
| 146 |
(First sleeps X, then sleeps 2*X, then sleeps 4*X, ...) |
| 147 |
- This is measured in seconds. |
| 148 |
- The C(ansible_psrp_reconnection_backoff) variable was added in Ansible |
| 149 |
2.9. |
| 150 |
type: int |
| 151 |
vars: |
| 152 |
- name: ansible_psrp_connection_backoff |
| 153 |
- name: ansible_psrp_reconnection_backoff |
| 154 |
default: 2 |
| 155 |
version_added: '2.8' |
| 156 |
message_encryption: |
| 157 |
description: |
| 158 |
- Controls the message encryption settings, this is different from TLS |
| 159 |
encryption when O(protocol) is V(https). |
| 160 |
- Only the auth protocols V(negotiate), V(kerberos), V(ntlm), and |
| 161 |
V(credssp) can do message encryption. The other authentication protocols |
| 162 |
only support encryption when V(protocol) is set to V(https). |
| 163 |
- V(auto) means means message encryption is only used when not using |
| 164 |
TLS/HTTPS. |
| 165 |
- V(always) is the same as V(auto) but message encryption is always used |
| 166 |
even when running over TLS/HTTPS. |
| 167 |
- V(never) disables any encryption checks that are in place when running |
| 168 |
over HTTP and disables any authentication encryption processes. |
| 169 |
type: str |
| 170 |
vars: |
| 171 |
- name: ansible_psrp_message_encryption |
| 172 |
choices: |
| 173 |
- auto |
| 174 |
- always |
| 175 |
- never |
| 176 |
default: auto |
| 177 |
proxy: |
| 178 |
description: |
| 179 |
- Set the proxy URL to use when connecting to the remote host. |
| 180 |
vars: |
| 181 |
- name: ansible_psrp_proxy |
| 182 |
type: str |
| 183 |
ignore_proxy: |
| 184 |
description: |
| 185 |
- Will disable any environment proxy settings and connect directly to the |
| 186 |
remote host. |
| 187 |
- This option is ignored if O(proxy) is set. |
| 188 |
vars: |
| 189 |
- name: ansible_psrp_ignore_proxy |
| 190 |
type: bool |
| 191 |
default: false |
| 192 |
|
| 193 |
# auth options |
| 194 |
certificate_key_pem: |
| 195 |
description: |
| 196 |
- The local path to an X509 certificate key to use with certificate auth. |
| 197 |
- If the certificate key is encrypted then O(certificate_key_password) must also be set. |
| 198 |
type: path |
| 199 |
vars: |
| 200 |
- name: ansible_psrp_certificate_key_pem |
| 201 |
certificate_pem: |
| 202 |
description: |
| 203 |
- The local path to an X509 certificate to use with certificate auth. |
| 204 |
type: path |
| 205 |
vars: |
| 206 |
- name: ansible_psrp_certificate_pem |
| 207 |
certificate_key_password: |
| 208 |
description: |
| 209 |
- The password for the O(certificate_key_pem) key file if it is encrypted. |
| 210 |
- This option requires pypsrp >= 0.9.0 to be installed. |
| 211 |
type: str |
| 212 |
secret: true |
| 213 |
vars: |
| 214 |
- name: ansible_psrp_certificate_key_password |
| 215 |
version_added: '2.21' |
| 216 |
credssp_auth_mechanism: |
| 217 |
description: |
| 218 |
- The sub authentication mechanism to use with CredSSP auth. |
| 219 |
- When V(auto), both Kerberos and NTLM is attempted with kerberos being |
| 220 |
preferred. |
| 221 |
type: str |
| 222 |
choices: |
| 223 |
- auto |
| 224 |
- kerberos |
| 225 |
- ntlm |
| 226 |
default: auto |
| 227 |
vars: |
| 228 |
- name: ansible_psrp_credssp_auth_mechanism |
| 229 |
credssp_disable_tlsv1_2: |
| 230 |
description: |
| 231 |
- Disables the use of TLSv1.2 on the CredSSP authentication channel. |
| 232 |
- This should not be set to V(yes) unless dealing with a host that does not |
| 233 |
have TLSv1.2. |
| 234 |
default: false |
| 235 |
type: bool |
| 236 |
vars: |
| 237 |
- name: ansible_psrp_credssp_disable_tlsv1_2 |
| 238 |
credssp_minimum_version: |
| 239 |
description: |
| 240 |
- The minimum CredSSP server authentication version that will be accepted. |
| 241 |
- Set to V(5) to ensure the server has been patched and is not vulnerable |
| 242 |
to CVE 2018-0886. |
| 243 |
default: 2 |
| 244 |
type: int |
| 245 |
vars: |
| 246 |
- name: ansible_psrp_credssp_minimum_version |
| 247 |
negotiate_delegate: |
| 248 |
description: |
| 249 |
- Allow the remote user the ability to delegate it's credentials to another |
| 250 |
server, i.e. credential delegation. |
| 251 |
- Only valid when Kerberos was the negotiated auth or was explicitly set as |
| 252 |
the authentication. |
| 253 |
- Ignored when NTLM was the negotiated auth. |
| 254 |
type: bool |
| 255 |
vars: |
| 256 |
- name: ansible_psrp_negotiate_delegate |
| 257 |
negotiate_hostname_override: |
| 258 |
description: |
| 259 |
- Override the remote hostname when searching for the host in the Kerberos |
| 260 |
lookup. |
| 261 |
- This allows Ansible to connect over IP but authenticate with the remote |
| 262 |
server using it's DNS name. |
| 263 |
- Only valid when Kerberos was the negotiated auth or was explicitly set as |
| 264 |
the authentication. |
| 265 |
- Ignored when NTLM was the negotiated auth. |
| 266 |
type: str |
| 267 |
vars: |
| 268 |
- name: ansible_psrp_negotiate_hostname_override |
| 269 |
negotiate_send_cbt: |
| 270 |
description: |
| 271 |
- Send the Channel Binding Token (CBT) structure when authenticating. |
| 272 |
- CBT is used to provide extra protection against Man in the Middle C(MitM) |
| 273 |
attacks by binding the outer transport channel to the auth channel. |
| 274 |
- CBT is not used when using just C(HTTP), only C(HTTPS). |
| 275 |
default: true |
| 276 |
type: bool |
| 277 |
vars: |
| 278 |
- name: ansible_psrp_negotiate_send_cbt |
| 279 |
negotiate_service: |
| 280 |
description: |
| 281 |
- Override the service part of the SPN used during Kerberos authentication. |
| 282 |
- Only valid when Kerberos was the negotiated auth or was explicitly set as |
| 283 |
the authentication. |
| 284 |
- Ignored when NTLM was the negotiated auth. |
| 285 |
- Before ansible-core 2.21, this had a default value of V(WSMAN) which failed to |
| 286 |
work on some hosts. Since ansible-core 2.21 the default value is V(host). |
| 287 |
default: host |
| 288 |
type: str |
| 289 |
vars: |
| 290 |
- name: ansible_psrp_negotiate_service |
| 291 |
|
| 292 |
# protocol options |
| 293 |
operation_timeout: |
| 294 |
description: |
| 295 |
- Sets the WSMan timeout for each operation. |
| 296 |
- This is measured in seconds. |
| 297 |
- This should not exceed the value for O(connection_timeout). |
| 298 |
type: int |
| 299 |
vars: |
| 300 |
- name: ansible_psrp_operation_timeout |
| 301 |
default: 20 |
| 302 |
max_envelope_size: |
| 303 |
description: |
| 304 |
- Sets the maximum size of each WSMan message sent to the remote host. |
| 305 |
- This is measured in bytes. |
| 306 |
- Defaults to C(150KiB) for compatibility with older hosts. |
| 307 |
type: int |
| 308 |
vars: |
| 309 |
- name: ansible_psrp_max_envelope_size |
| 310 |
default: 153600 |
| 311 |
configuration_name: |
| 312 |
description: |
| 313 |
- The name of the PowerShell configuration endpoint to connect to. |
| 314 |
type: str |
| 315 |
vars: |
| 316 |
- name: ansible_psrp_configuration_name |
| 317 |
default: Microsoft.PowerShell |
| 318 |
no_profile: |
| 319 |
description: |
| 320 |
- Do not load the user's PowerShell profile when connecting. |
| 321 |
- This option requires pypsrp >= 0.9.0 to be installed. |
| 322 |
type: bool |
| 323 |
default: false |
| 324 |
vars: |
| 325 |
- name: ansible_psrp_no_profile |
| 326 |
version_added: '2.21' |
| 327 |
""" |
| 328 |
|
| 329 |
import base64 |
| 330 |
import json |
| 331 |
import logging |
| 332 |
import os |
| 333 |
import typing as t |
| 334 |
|
| 335 |
from ansible import constants as C |
| 336 |
from ansible._internal._powershell import _script |
| 337 |
from ansible.errors import AnsibleConnectionFailure, AnsibleError |
| 338 |
from ansible.errors import AnsibleFileNotFound |
| 339 |
from ansible.executor.powershell.module_manifest import _bootstrap_powershell_script |
| 340 |
from ansible.module_utils.parsing.convert_bool import boolean |
| 341 |
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text |
| 342 |
from ansible.plugins.connection import ConnectionBase |
| 343 |
from ansible.plugins.shell.powershell import ShellModule as PowerShellPlugin |
| 344 |
from ansible.utils.display import Display |
| 345 |
from ansible.utils.hashing import sha1 |
| 346 |
|
| 347 |
HAS_PYPSRP = True |
| 348 |
PYPSRP_IMP_ERR = None |
| 349 |
try: |
| 350 |
from pypsrp.complex_objects import GenericComplexObject, PSInvocationState, RunspacePoolState |
| 351 |
from pypsrp.exceptions import AuthenticationError, WinRMError |
| 352 |
from pypsrp.host import PSHost, PSHostUserInterface |
| 353 |
from pypsrp.powershell import PowerShell, RunspacePool |
| 354 |
from pypsrp.wsman import WSMan |
| 355 |
from requests.exceptions import ConnectionError, ConnectTimeout, ReadTimeout |
| 356 |
except ImportError as err: |
| 357 |
HAS_PYPSRP = False |
| 358 |
PYPSRP_IMP_ERR = err |
| 359 |
|
| 360 |
display = Display() |
| 361 |
|
| 362 |
|
| 363 |
class Connection(ConnectionBase): |
| 364 |
|
| 365 |
transport = 'psrp' |
| 366 |
module_implementation_preferences = ('.ps1', '.exe', '') |
| 367 |
allow_executable = False |
| 368 |
has_pipelining = True |
| 369 |
|
| 370 |
# Satisfies mypy as this connection only ever runs with this plugin |
| 371 |
_shell: PowerShellPlugin |
| 372 |
|
| 373 |
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None: |
| 374 |
self.runspace: RunspacePool | None = None |
| 375 |
self.host: PSHost | None = None |
| 376 |
self._last_pipeline: PowerShell | None = None |
| 377 |
|
| 378 |
self._shell_type = 'powershell' |
| 379 |
super(Connection, self).__init__(*args, **kwargs) |
| 380 |
if self._shell.SHELL_FAMILY != 'powershell': |
| 381 |
# This shouldn't happen but someone might have ansible_shell_type=cmd |
| 382 |
# set from testing with winrm/ssh. This plugin will probably still work |
| 383 |
# but there are edge cases that could fail unless powershell was |
| 384 |
# used. |
| 385 |
display.warning( |
| 386 |
msg=( |
| 387 |
"The psrp connection plugin should have the shell type of powershell and not " |
| 388 |
f"{self._shell.SHELL_FAMILY}. This may result in an error when attempting to run more complex commands." |
| 389 |
), |
| 390 |
help_text="Unset ansible_shell_type or set to powershell to use the required powershell shell.", |
| 391 |
) |
| 392 |
|
| 393 |
if not C.DEFAULT_DEBUG: |
| 394 |
logging.getLogger('pypsrp').setLevel(logging.WARNING) |
| 395 |
logging.getLogger('requests_credssp').setLevel(logging.INFO) |
| 396 |
logging.getLogger('urllib3').setLevel(logging.INFO) |
| 397 |
|
| 398 |
def _connect(self) -> Connection: |
| 399 |
if not HAS_PYPSRP: |
| 400 |
raise AnsibleError("pypsrp or dependencies are not installed: %s" |
| 401 |
% to_native(PYPSRP_IMP_ERR)) |
| 402 |
super(Connection, self)._connect() |
| 403 |
self._build_kwargs() |
| 404 |
display.vvv("ESTABLISH PSRP CONNECTION FOR USER: %s ON PORT %s TO %s" % |
| 405 |
(self._psrp_user, self._psrp_port, self._psrp_host), |
| 406 |
host=self._psrp_host) |
| 407 |
|
| 408 |
if not self.runspace: |
| 409 |
connection = WSMan(**self._psrp_conn_kwargs) |
| 410 |
|
| 411 |
# create our pseudo host to capture the exit code and host output |
| 412 |
host_ui = PSHostUserInterface() |
| 413 |
self.host = PSHost(None, None, False, "Ansible PSRP Host", None, |
| 414 |
host_ui, None) |
| 415 |
|
| 416 |
self.runspace = RunspacePool( |
| 417 |
connection, host=self.host, |
| 418 |
**self._psrp_runspace_kwargs, |
| 419 |
) |
| 420 |
display.vvvvv( |
| 421 |
"PSRP OPEN RUNSPACE: auth=%s configuration=%s endpoint=%s" % |
| 422 |
(self._psrp_auth, self._psrp_runspace_kwargs.get('configuration_name', 'Unknown'), |
| 423 |
connection.transport.endpoint), host=self._psrp_host |
| 424 |
) |
| 425 |
try: |
| 426 |
self.runspace.open() |
| 427 |
except AuthenticationError as e: |
| 428 |
raise AnsibleConnectionFailure("failed to authenticate with " |
| 429 |
"the server: %s" % to_native(e)) |
| 430 |
except WinRMError as e: |
| 431 |
raise AnsibleConnectionFailure( |
| 432 |
"psrp connection failure during runspace open: %s" |
| 433 |
% to_native(e) |
| 434 |
) |
| 435 |
except (ConnectionError, ConnectTimeout) as e: |
| 436 |
raise AnsibleConnectionFailure( |
| 437 |
"Failed to connect to the host via PSRP: %s" |
| 438 |
% to_native(e) |
| 439 |
) |
| 440 |
|
| 441 |
self._connected = True |
| 442 |
self._last_pipeline = None |
| 443 |
return self |
| 444 |
|
| 445 |
def reset(self) -> None: |
| 446 |
if not self._connected: |
| 447 |
self.runspace = None |
| 448 |
return |
| 449 |
|
| 450 |
# Try out best to ensure the runspace is closed to free up server side resources |
| 451 |
try: |
| 452 |
self.close() |
| 453 |
except Exception as e: |
| 454 |
# There's a good chance the connection was already closed so just log the error and move on |
| 455 |
display.debug("PSRP reset - failed to closed runspace: %s" % to_text(e)) |
| 456 |
|
| 457 |
display.vvvvv("PSRP: Reset Connection", host=self._psrp_host) |
| 458 |
self.runspace = None |
| 459 |
self._connect() |
| 460 |
|
| 461 |
def exec_command(self, cmd: str, in_data: bytes | None = None, sudoable: bool = True) -> tuple[int, bytes, bytes]: |
| 462 |
super(Connection, self).exec_command(cmd, in_data=in_data, |
| 463 |
sudoable=sudoable) |
| 464 |
|
| 465 |
pwsh_in_data: bytes | str | None = to_text(in_data, errors="surrogate_or_strict", nonstring="passthru") |
| 466 |
script_args: list[str] | None = None |
| 467 |
|
| 468 |
# If -EncodedCommand is present we assume it's an encoded PowerShell |
| 469 |
# command which we will just execute directly without spawning a new |
| 470 |
# subprocess. |
| 471 |
if enc_cmd := _script.parse_encoded_cmdline(cmd): |
| 472 |
script, script_args = enc_cmd |
| 473 |
else: |
| 474 |
# In other cases we want to execute the cmd as the script. We |
| 475 |
# expect the cmd to be a valid PowerShell script/command. |
| 476 |
# We add on the 'exit $LASTEXITCODE' to ensure the # rc is |
| 477 |
# propagated back to the connection plugin. |
| 478 |
script = f"{cmd}\nexit $LASTEXITCODE" |
| 479 |
pwsh_in_data = in_data |
| 480 |
display.vvv(u"PSRP: EXEC %s" % script, host=self._psrp_host) |
| 481 |
|
| 482 |
try: |
| 483 |
rc, stdout, stderr = self._exec_psrp_script( |
| 484 |
script=script, |
| 485 |
input_data=pwsh_in_data.splitlines() if pwsh_in_data else None, |
| 486 |
arguments=script_args, |
| 487 |
) |
| 488 |
except ReadTimeout as e: |
| 489 |
raise AnsibleConnectionFailure( |
| 490 |
"HTTP read timeout during PSRP script execution" |
| 491 |
) from e |
| 492 |
return rc, stdout, stderr |
| 493 |
|
| 494 |
def put_file(self, in_path: str, out_path: str) -> None: |
| 495 |
super(Connection, self).put_file(in_path, out_path) |
| 496 |
|
| 497 |
display.vvv("PUT %s TO %s" % (in_path, out_path), host=self._psrp_host) |
| 498 |
|
| 499 |
script, in_data = _bootstrap_powershell_script('psrp_put_file.ps1', { |
| 500 |
'Path': out_path, |
| 501 |
}, has_input=True) |
| 502 |
|
| 503 |
# Get the buffer size of each fragment to send, subtract 82 for the fragment, message, and other header info |
| 504 |
# fields that PSRP adds. Adjust to size of the base64 encoded bytes length. |
| 505 |
buffer_size = int((self.runspace.connection.max_payload_size - 82) / 4 * 3) |
| 506 |
|
| 507 |
sha1_hash = sha1() |
| 508 |
|
| 509 |
b_in_path = to_bytes(in_path, errors='surrogate_or_strict') |
| 510 |
if not os.path.exists(b_in_path): |
| 511 |
raise AnsibleFileNotFound('file or module does not exist: "%s"' % to_native(in_path)) |
| 512 |
|
| 513 |
def read_gen(): |
| 514 |
yield from in_data.decode().splitlines() |
| 515 |
|
| 516 |
offset = 0 |
| 517 |
|
| 518 |
with open(b_in_path, 'rb') as src_fd: |
| 519 |
for b_data in iter((lambda: src_fd.read(buffer_size)), b""): |
| 520 |
data_len = len(b_data) |
| 521 |
offset += data_len |
| 522 |
sha1_hash.update(b_data) |
| 523 |
|
| 524 |
# PSRP technically supports sending raw bytes but that method requires a larger CLIXML message. |
| 525 |
# Sending base64 is still more efficient here. |
| 526 |
display.vvvvv("PSRP PUT %s to %s (offset=%d, size=%d" % (in_path, out_path, offset, data_len), |
| 527 |
host=self._psrp_host) |
| 528 |
b64_data = base64.b64encode(b_data) |
| 529 |
yield [to_text(b64_data)] |
| 530 |
|
| 531 |
if offset == 0: # empty file |
| 532 |
yield [""] |
| 533 |
|
| 534 |
rc, stdout, stderr = self._exec_psrp_script(script, read_gen()) |
| 535 |
|
| 536 |
if rc != 0: |
| 537 |
raise AnsibleError(to_native(stderr)) |
| 538 |
|
| 539 |
put_output = json.loads(to_text(stdout)) |
| 540 |
local_sha1 = sha1_hash.hexdigest() |
| 541 |
remote_sha1 = put_output.get("sha1") |
| 542 |
|
| 543 |
if not remote_sha1: |
| 544 |
raise AnsibleError("Remote sha1 was not returned, stdout: '%s', stderr: '%s'" |
| 545 |
% (to_native(stdout), to_native(stderr))) |
| 546 |
|
| 547 |
if not remote_sha1 == local_sha1: |
| 548 |
raise AnsibleError("Remote sha1 hash %s does not match local hash %s" |
| 549 |
% (to_native(remote_sha1), to_native(local_sha1))) |
| 550 |
|
| 551 |
def fetch_file(self, in_path: str, out_path: str) -> None: |
| 552 |
super(Connection, self).fetch_file(in_path, out_path) |
| 553 |
display.vvv("FETCH %s TO %s" % (in_path, out_path), |
| 554 |
host=self._psrp_host) |
| 555 |
|
| 556 |
out_path = out_path.replace('\\', '/') |
| 557 |
b_out_path = to_bytes(out_path, errors='surrogate_or_strict') |
| 558 |
|
| 559 |
# because we are dealing with base64 data we need to get the max size |
| 560 |
# of the bytes that the base64 size would equal |
| 561 |
max_b64_size = int(self.runspace.connection.max_payload_size - |
| 562 |
(self.runspace.connection.max_payload_size / 4 * 3)) |
| 563 |
buffer_size = max_b64_size - (max_b64_size % 1024) |
| 564 |
|
| 565 |
script, in_data = _bootstrap_powershell_script('psrp_fetch_file.ps1', { |
| 566 |
'Path': in_path, |
| 567 |
'BufferSize': buffer_size, |
| 568 |
}) |
| 569 |
|
| 570 |
ps = PowerShell(self.runspace) |
| 571 |
ps.add_script(script) |
| 572 |
ps.begin_invoke(in_data.decode().splitlines()) |
| 573 |
|
| 574 |
# Call poll once to get the first output telling us if it's a file/dir/failure |
| 575 |
ps.poll_invoke() |
| 576 |
|
| 577 |
if ps.output: |
| 578 |
if ps.output.pop(0) == '[DIR]': |
| 579 |
# to be consistent with other connection plugins, we assume the caller has created the target dir |
| 580 |
return |
| 581 |
|
| 582 |
with open(b_out_path, 'wb') as out_file: |
| 583 |
while True: |
| 584 |
while ps.output: |
| 585 |
data = base64.b64decode(ps.output.pop(0)) |
| 586 |
out_file.write(data) |
| 587 |
|
| 588 |
if ps.state == PSInvocationState.RUNNING: |
| 589 |
ps.poll_invoke() |
| 590 |
else: |
| 591 |
break |
| 592 |
|
| 593 |
ps.end_invoke() |
| 594 |
rc, stdout, stderr = self._parse_pipeline_result(ps) |
| 595 |
if rc != 0: |
| 596 |
raise AnsibleError(f"failed to transfer file to '{out_path}': {to_text(stderr)}") |
| 597 |
|
| 598 |
def close(self) -> None: |
| 599 |
if self.runspace and self.runspace.state == RunspacePoolState.OPENED: |
| 600 |
display.vvvvv("PSRP CLOSE RUNSPACE: %s" % (self.runspace.id), |
| 601 |
host=self._psrp_host) |
| 602 |
self.runspace.close() |
| 603 |
self.runspace = None |
| 604 |
self._connected = False |
| 605 |
self._last_pipeline = None |
| 606 |
|
| 607 |
def _build_kwargs(self) -> None: |
| 608 |
self._psrp_host = self.get_option('remote_addr') |
| 609 |
self._psrp_user = self.get_option('remote_user') |
| 610 |
|
| 611 |
protocol = self.get_option('protocol') |
| 612 |
port = self.get_option('port') |
| 613 |
if protocol is None and port is None: |
| 614 |
protocol = 'https' |
| 615 |
port = 5986 |
| 616 |
elif protocol is None: |
| 617 |
protocol = 'https' if int(port) != 5985 else 'http' |
| 618 |
elif port is None: |
| 619 |
port = 5986 if protocol == 'https' else 5985 |
| 620 |
|
| 621 |
self._psrp_port = int(port) |
| 622 |
self._psrp_auth = self.get_option('auth') |
| 623 |
|
| 624 |
self._psrp_runspace_kwargs = dict( |
| 625 |
configuration_name=self.get_option('configuration_name'), |
| 626 |
) |
| 627 |
if no_profile := self.get_option('no_profile'): |
| 628 |
self._psrp_runspace_kwargs['no_profile'] = no_profile |
| 629 |
|
| 630 |
# cert validation can either be a bool or a path to the cert |
| 631 |
cert_validation = self.get_option('cert_validation') |
| 632 |
cert_trust_path = self.get_option('ca_cert') |
| 633 |
if cert_validation == 'ignore': |
| 634 |
psrp_cert_validation = False |
| 635 |
elif cert_trust_path is not None: |
| 636 |
psrp_cert_validation = cert_trust_path |
| 637 |
else: |
| 638 |
psrp_cert_validation = True |
| 639 |
|
| 640 |
self._psrp_conn_kwargs = dict( |
| 641 |
server=self._psrp_host, |
| 642 |
port=self._psrp_port, |
| 643 |
username=self._psrp_user, |
| 644 |
password=self.get_option('remote_password'), |
| 645 |
ssl=protocol == 'https', |
| 646 |
path=self.get_option('path'), |
| 647 |
auth=self._psrp_auth, |
| 648 |
cert_validation=psrp_cert_validation, |
| 649 |
connection_timeout=self.get_option('connection_timeout'), |
| 650 |
encryption=self.get_option('message_encryption'), |
| 651 |
proxy=self.get_option('proxy'), |
| 652 |
no_proxy=boolean(self.get_option('ignore_proxy')), |
| 653 |
max_envelope_size=self.get_option('max_envelope_size'), |
| 654 |
operation_timeout=self.get_option('operation_timeout'), |
| 655 |
read_timeout=self.get_option('read_timeout'), |
| 656 |
reconnection_retries=self.get_option('reconnection_retries'), |
| 657 |
reconnection_backoff=float(self.get_option('reconnection_backoff')), |
| 658 |
certificate_key_pem=self.get_option('certificate_key_pem'), |
| 659 |
certificate_pem=self.get_option('certificate_pem'), |
| 660 |
credssp_auth_mechanism=self.get_option('credssp_auth_mechanism'), |
| 661 |
credssp_disable_tlsv1_2=self.get_option('credssp_disable_tlsv1_2'), |
| 662 |
credssp_minimum_version=self.get_option('credssp_minimum_version'), |
| 663 |
negotiate_send_cbt=self.get_option('negotiate_send_cbt'), |
| 664 |
negotiate_delegate=self.get_option('negotiate_delegate'), |
| 665 |
negotiate_hostname_override=self.get_option('negotiate_hostname_override'), |
| 666 |
negotiate_service=self.get_option('negotiate_service'), |
| 667 |
) |
| 668 |
|
| 669 |
# We don't always set this in case we are working with an older pypsrp |
| 670 |
# version that doesn't support this option. |
| 671 |
certificate_key_password = self.get_option('certificate_key_password') |
| 672 |
if certificate_key_password: |
| 673 |
self._psrp_conn_kwargs['certificate_key_password'] = certificate_key_password |
| 674 |
|
| 675 |
def _exec_psrp_script( |
| 676 |
self, |
| 677 |
script: str, |
| 678 |
input_data: bytes | str | t.Iterable | None = None, |
| 679 |
use_local_scope: bool = True, |
| 680 |
arguments: t.Iterable[t.Any] | None = None, |
| 681 |
) -> tuple[int, bytes, bytes]: |
| 682 |
# Check if there's a command on the current pipeline that still needs to be closed. |
| 683 |
if self._last_pipeline: |
| 684 |
# Current pypsrp versions raise an exception if the current state was not RUNNING. We manually set it so we |
| 685 |
# can call stop without any issues. |
| 686 |
self._last_pipeline.state = PSInvocationState.RUNNING |
| 687 |
self._last_pipeline.stop() |
| 688 |
self._last_pipeline = None |
| 689 |
|
| 690 |
ps = PowerShell(self.runspace) |
| 691 |
ps.add_script(script, use_local_scope=use_local_scope) |
| 692 |
if arguments: |
| 693 |
for arg in arguments: |
| 694 |
ps.add_argument(arg) |
| 695 |
|
| 696 |
ps.invoke(input=input_data) |
| 697 |
|
| 698 |
rc, stdout, stderr = self._parse_pipeline_result(ps) |
| 699 |
|
| 700 |
# We should really call .stop() on all pipelines that are run to decrement the concurrent command counter on |
| 701 |
# PSSession but that involves another round trip and is done when the runspace is closed. We instead store the |
| 702 |
# last pipeline which is closed if another command is run on the runspace. |
| 703 |
self._last_pipeline = ps |
| 704 |
|
| 705 |
return rc, stdout, stderr |
| 706 |
|
| 707 |
def _parse_pipeline_result(self, pipeline: PowerShell) -> tuple[int, bytes, bytes]: |
| 708 |
""" |
| 709 |
PSRP doesn't have the same concept as other protocols with its output. |
| 710 |
We need some extra logic to convert the pipeline streams and host |
| 711 |
output into the format that Ansible understands. |
| 712 |
|
| 713 |
:param pipeline: The finished PowerShell pipeline that invoked our |
| 714 |
commands |
| 715 |
:return: rc, stdout, stderr based on the pipeline output |
| 716 |
""" |
| 717 |
# we try and get the rc from our host implementation, this is set if |
| 718 |
# exit or $host.SetShouldExit() is called in our pipeline, if not we |
| 719 |
# set to 0 if the pipeline had not errors and 1 if it did |
| 720 |
rc = self.host.rc or (1 if pipeline.had_errors else 0) |
| 721 |
|
| 722 |
# TODO: figure out a better way of merging this with the host output |
| 723 |
stdout_list = [] |
| 724 |
for output in pipeline.output: |
| 725 |
# Not all pipeline outputs are a string or contain a __str__ value, |
| 726 |
# we will create our own output based on the properties of the |
| 727 |
# complex object if that is the case. |
| 728 |
if isinstance(output, GenericComplexObject) and output.to_string is None: |
| 729 |
obj_lines = output.property_sets |
| 730 |
for key, value in output.adapted_properties.items(): |
| 731 |
obj_lines.append(u"%s: %s" % (key, value)) |
| 732 |
for key, value in output.extended_properties.items(): |
| 733 |
obj_lines.append(u"%s: %s" % (key, value)) |
| 734 |
output_msg = u"\n".join(obj_lines) |
| 735 |
else: |
| 736 |
output_msg = to_text(output, nonstring='simplerepr') |
| 737 |
|
| 738 |
stdout_list.append(output_msg) |
| 739 |
|
| 740 |
if len(self.host.ui.stdout) > 0: |
| 741 |
stdout_list += self.host.ui.stdout |
| 742 |
stdout = u"\r\n".join(stdout_list) |
| 743 |
|
| 744 |
stderr_list = [] |
| 745 |
for error in pipeline.streams.error: |
| 746 |
# the error record is not as fully fleshed out like we usually get |
| 747 |
# in PS, we will manually create it here |
| 748 |
# NativeCommandError and NativeCommandErrorMessage are special |
| 749 |
# cases used for stderr from a subprocess, we will just print the |
| 750 |
# error message |
| 751 |
if error.fq_error in ['NativeCommandError', 'NativeCommandErrorMessage']: |
| 752 |
stderr_list.append(f"{error}\r\n") |
| 753 |
continue |
| 754 |
|
| 755 |
command_name = "%s : " % error.command_name if error.command_name else '' |
| 756 |
position = "%s\r\n" % error.invocation_position_message if error.invocation_position_message else '' |
| 757 |
error_msg = "%s%s\r\n%s" \ |
| 758 |
" + CategoryInfo : %s\r\n" \ |
| 759 |
" + FullyQualifiedErrorId : %s" \ |
| 760 |
% (command_name, str(error), position, |
| 761 |
error.message, error.fq_error) |
| 762 |
stacktrace = error.script_stacktrace |
| 763 |
if display.verbosity >= 3 and stacktrace is not None: |
| 764 |
error_msg += "\r\nStackTrace:\r\n%s" % stacktrace |
| 765 |
stderr_list.append(f"{error_msg}\r\n") |
| 766 |
|
| 767 |
if len(self.host.ui.stderr) > 0: |
| 768 |
stderr_list += self.host.ui.stderr |
| 769 |
stderr = "".join([to_text(o) for o in stderr_list]) |
| 770 |
|
| 771 |
log_stdout = stdout |
| 772 |
log_stderr = stderr |
| 773 |
if self._play_context.no_log: |
| 774 |
log_stdout = log_stderr = '<censored due to no log>' |
| 775 |
|
| 776 |
display.vvvvv("PSRP RC: %d" % rc, host=self._psrp_host) |
| 777 |
# The raw output is only shown under ANSIBLE_DEBUG. Module output may contain secrets which are not |
| 778 |
# registered with the secret masker until the result has been parsed by the action plugin, so displaying |
| 779 |
# the raw output here at a normal verbosity level could leak them. |
| 780 |
display.debug(f"PSRP STDOUT: {log_stdout}") |
| 781 |
display.debug(f"PSRP STDERR: {log_stderr}") |
| 782 |
|
| 783 |
# reset the host back output back to defaults, needed if running |
| 784 |
# multiple pipelines on the same RunspacePool |
| 785 |
self.host.rc = 0 |
| 786 |
self.host.ui.stdout = [] |
| 787 |
self.host.ui.stderr = [] |
| 788 |
|
| 789 |
return rc, to_bytes(stdout, encoding='utf-8'), to_bytes(stderr, encoding='utf-8') |
| 790 |
|
| 791 |
def is_pipelining_enabled(self, wrap_async: bool = False) -> bool: |
| 792 |
return True |