| 1 |
# Derived from ansible/plugins/connection/paramiko_ssh.py (c) 2012, Michael DeHaan <[email protected]> |
| 2 |
# Copyright (c) 2024 Nils Stein (@mietzen) <[email protected]> |
| 3 |
# Copyright (c) 2024 Ansible Project |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
author: Nils Stein (@mietzen) <[email protected]> |
| 11 |
name: proxmox_pct_remote |
| 12 |
short_description: Run tasks in Proxmox LXC container instances using pct CLI via SSH |
| 13 |
requirements: |
| 14 |
- paramiko |
| 15 |
description: |
| 16 |
- Run commands or put/fetch files to an existing Proxmox LXC container using pct CLI via SSH. |
| 17 |
- Uses the Python SSH implementation (Paramiko) to connect to the Proxmox host. |
| 18 |
options: |
| 19 |
remote_addr: |
| 20 |
description: |
| 21 |
- Address of the remote target. |
| 22 |
default: inventory_hostname |
| 23 |
type: string |
| 24 |
vars: |
| 25 |
- name: inventory_hostname |
| 26 |
- name: ansible_host |
| 27 |
- name: ansible_ssh_host |
| 28 |
- name: ansible_paramiko_host |
| 29 |
port: |
| 30 |
description: Remote port to connect to. |
| 31 |
type: int |
| 32 |
default: 22 |
| 33 |
ini: |
| 34 |
- section: defaults |
| 35 |
key: remote_port |
| 36 |
- section: paramiko_connection |
| 37 |
key: remote_port |
| 38 |
env: |
| 39 |
- name: ANSIBLE_REMOTE_PORT |
| 40 |
- name: ANSIBLE_REMOTE_PARAMIKO_PORT |
| 41 |
vars: |
| 42 |
- name: ansible_port |
| 43 |
- name: ansible_ssh_port |
| 44 |
- name: ansible_paramiko_port |
| 45 |
keyword: |
| 46 |
- name: port |
| 47 |
remote_user: |
| 48 |
description: |
| 49 |
- User to login/authenticate as. |
| 50 |
- Can be set from the CLI via the C(--user) or C(-u) options. |
| 51 |
type: string |
| 52 |
vars: |
| 53 |
- name: ansible_user |
| 54 |
- name: ansible_ssh_user |
| 55 |
- name: ansible_paramiko_user |
| 56 |
env: |
| 57 |
- name: ANSIBLE_REMOTE_USER |
| 58 |
- name: ANSIBLE_PARAMIKO_REMOTE_USER |
| 59 |
ini: |
| 60 |
- section: defaults |
| 61 |
key: remote_user |
| 62 |
- section: paramiko_connection |
| 63 |
key: remote_user |
| 64 |
keyword: |
| 65 |
- name: remote_user |
| 66 |
password: |
| 67 |
description: |
| 68 |
- Secret used to either login the SSH server or as a passphrase for SSH keys that require it. |
| 69 |
- Can be set from the CLI via the C(--ask-pass) option. |
| 70 |
type: string |
| 71 |
vars: |
| 72 |
- name: ansible_password |
| 73 |
- name: ansible_ssh_pass |
| 74 |
- name: ansible_ssh_password |
| 75 |
- name: ansible_paramiko_pass |
| 76 |
- name: ansible_paramiko_password |
| 77 |
use_rsa_sha2_algorithms: |
| 78 |
description: |
| 79 |
- Whether or not to enable RSA SHA2 algorithms for pubkeys and hostkeys. |
| 80 |
- On paramiko versions older than 2.9, this only affects hostkeys. |
| 81 |
- For behavior matching paramiko<2.9 set this to V(false). |
| 82 |
vars: |
| 83 |
- name: ansible_paramiko_use_rsa_sha2_algorithms |
| 84 |
ini: |
| 85 |
- {key: use_rsa_sha2_algorithms, section: paramiko_connection} |
| 86 |
env: |
| 87 |
- {name: ANSIBLE_PARAMIKO_USE_RSA_SHA2_ALGORITHMS} |
| 88 |
default: true |
| 89 |
type: boolean |
| 90 |
host_key_auto_add: |
| 91 |
description: "Automatically add host keys to C(~/.ssh/known_hosts)." |
| 92 |
env: |
| 93 |
- name: ANSIBLE_PARAMIKO_HOST_KEY_AUTO_ADD |
| 94 |
ini: |
| 95 |
- key: host_key_auto_add |
| 96 |
section: paramiko_connection |
| 97 |
type: boolean |
| 98 |
look_for_keys: |
| 99 |
default: True |
| 100 |
description: "Set to V(false) to disable searching for private key files in C(~/.ssh/)." |
| 101 |
env: |
| 102 |
- name: ANSIBLE_PARAMIKO_LOOK_FOR_KEYS |
| 103 |
ini: |
| 104 |
- {key: look_for_keys, section: paramiko_connection} |
| 105 |
type: boolean |
| 106 |
proxy_command: |
| 107 |
default: "" |
| 108 |
description: |
| 109 |
- Proxy information for running the connection via a jumphost. |
| 110 |
type: string |
| 111 |
env: |
| 112 |
- name: ANSIBLE_PARAMIKO_PROXY_COMMAND |
| 113 |
ini: |
| 114 |
- {key: proxy_command, section: paramiko_connection} |
| 115 |
vars: |
| 116 |
- name: ansible_paramiko_proxy_command |
| 117 |
pty: |
| 118 |
default: True |
| 119 |
description: "C(sudo) usually requires a PTY, V(true) to give a PTY and V(false) to not give a PTY." |
| 120 |
env: |
| 121 |
- name: ANSIBLE_PARAMIKO_PTY |
| 122 |
ini: |
| 123 |
- section: paramiko_connection |
| 124 |
key: pty |
| 125 |
type: boolean |
| 126 |
record_host_keys: |
| 127 |
default: True |
| 128 |
description: "Save the host keys to a file." |
| 129 |
env: |
| 130 |
- name: ANSIBLE_PARAMIKO_RECORD_HOST_KEYS |
| 131 |
ini: |
| 132 |
- section: paramiko_connection |
| 133 |
key: record_host_keys |
| 134 |
type: boolean |
| 135 |
host_key_checking: |
| 136 |
description: "Set this to V(false) if you want to avoid host key checking by the underlying tools Ansible uses to connect to the host." |
| 137 |
type: boolean |
| 138 |
default: true |
| 139 |
env: |
| 140 |
- name: ANSIBLE_HOST_KEY_CHECKING |
| 141 |
- name: ANSIBLE_SSH_HOST_KEY_CHECKING |
| 142 |
- name: ANSIBLE_PARAMIKO_HOST_KEY_CHECKING |
| 143 |
ini: |
| 144 |
- section: defaults |
| 145 |
key: host_key_checking |
| 146 |
- section: paramiko_connection |
| 147 |
key: host_key_checking |
| 148 |
vars: |
| 149 |
- name: ansible_host_key_checking |
| 150 |
- name: ansible_ssh_host_key_checking |
| 151 |
- name: ansible_paramiko_host_key_checking |
| 152 |
use_persistent_connections: |
| 153 |
description: "Toggles the use of persistence for connections." |
| 154 |
type: boolean |
| 155 |
default: False |
| 156 |
env: |
| 157 |
- name: ANSIBLE_USE_PERSISTENT_CONNECTIONS |
| 158 |
ini: |
| 159 |
- section: defaults |
| 160 |
key: use_persistent_connections |
| 161 |
forward_agent: |
| 162 |
description: "Enable SSH agent forwarding." |
| 163 |
type: boolean |
| 164 |
default: False |
| 165 |
env: |
| 166 |
- name: ANSIBLE_PARAMIKO_FORWARD_AGENT |
| 167 |
ini: |
| 168 |
- section: paramiko_connection |
| 169 |
key: forward_agent |
| 170 |
banner_timeout: |
| 171 |
type: float |
| 172 |
default: 30 |
| 173 |
description: |
| 174 |
- Configures, in seconds, the amount of time to wait for the SSH |
| 175 |
banner to be presented. This option is supported by paramiko |
| 176 |
version 1.15.0 or newer. |
| 177 |
ini: |
| 178 |
- section: paramiko_connection |
| 179 |
key: banner_timeout |
| 180 |
env: |
| 181 |
- name: ANSIBLE_PARAMIKO_BANNER_TIMEOUT |
| 182 |
timeout: |
| 183 |
type: int |
| 184 |
default: 10 |
| 185 |
description: Number of seconds until the plugin gives up on failing to establish a TCP connection. |
| 186 |
ini: |
| 187 |
- section: defaults |
| 188 |
key: timeout |
| 189 |
- section: ssh_connection |
| 190 |
key: timeout |
| 191 |
- section: paramiko_connection |
| 192 |
key: timeout |
| 193 |
env: |
| 194 |
- name: ANSIBLE_TIMEOUT |
| 195 |
- name: ANSIBLE_SSH_TIMEOUT |
| 196 |
- name: ANSIBLE_PARAMIKO_TIMEOUT |
| 197 |
vars: |
| 198 |
- name: ansible_ssh_timeout |
| 199 |
- name: ansible_paramiko_timeout |
| 200 |
cli: |
| 201 |
- name: timeout |
| 202 |
lock_file_timeout: |
| 203 |
type: int |
| 204 |
default: 60 |
| 205 |
description: Number of seconds until the plugin gives up on trying to write a lock file when writing SSH known host keys. |
| 206 |
vars: |
| 207 |
- name: ansible_lock_file_timeout |
| 208 |
env: |
| 209 |
- name: ANSIBLE_LOCK_FILE_TIMEOUT |
| 210 |
private_key_file: |
| 211 |
description: |
| 212 |
- Path to private key file to use for authentication. |
| 213 |
type: string |
| 214 |
ini: |
| 215 |
- section: defaults |
| 216 |
key: private_key_file |
| 217 |
- section: paramiko_connection |
| 218 |
key: private_key_file |
| 219 |
env: |
| 220 |
- name: ANSIBLE_PRIVATE_KEY_FILE |
| 221 |
- name: ANSIBLE_PARAMIKO_PRIVATE_KEY_FILE |
| 222 |
vars: |
| 223 |
- name: ansible_private_key_file |
| 224 |
- name: ansible_ssh_private_key_file |
| 225 |
- name: ansible_paramiko_private_key_file |
| 226 |
cli: |
| 227 |
- name: private_key_file |
| 228 |
option: "--private-key" |
| 229 |
vmid: |
| 230 |
description: |
| 231 |
- LXC Container ID |
| 232 |
type: int |
| 233 |
vars: |
| 234 |
- name: proxmox_vmid |
| 235 |
proxmox_become_method: |
| 236 |
description: |
| 237 |
- Become command used in proxmox |
| 238 |
type: str |
| 239 |
default: sudo |
| 240 |
vars: |
| 241 |
- name: proxmox_become_method |
| 242 |
notes: |
| 243 |
- > |
| 244 |
When NOT using this plugin as root, you need to have a become mechanism, |
| 245 |
e.g. C(sudo), installed on Proxmox and setup so we can run it without prompting for the password. |
| 246 |
Inside the container, we need a shell, for example C(sh) and the C(cat) command to be available in the C(PATH) for this plugin to work. |
| 247 |
""" |
| 248 |
|
| 249 |
EXAMPLES = r""" |
| 250 |
# -------------------------------------------------------------- |
| 251 |
# Setup sudo with password less access to pct for user 'ansible': |
| 252 |
# -------------------------------------------------------------- |
| 253 |
# |
| 254 |
# Open a Proxmox root shell and execute: |
| 255 |
# $ useradd -d /opt/ansible-pct -r -m -s /bin/sh ansible |
| 256 |
# $ mkdir -p /opt/ansible-pct/.ssh |
| 257 |
# $ ssh-keygen -t ed25519 -C 'ansible' -N "" -f /opt/ansible-pct/.ssh/ansible <<< y > /dev/null |
| 258 |
# $ cat /opt/ansible-pct/.ssh/ansible |
| 259 |
# $ mv /opt/ansible-pct/.ssh/ansible.pub /opt/ansible-pct/.ssh/authorized-keys |
| 260 |
# $ rm /opt/ansible-pct/.ssh/ansible* |
| 261 |
# $ chown -R ansible:ansible /opt/ansible-pct/.ssh |
| 262 |
# $ chmod 700 /opt/ansible-pct/.ssh |
| 263 |
# $ chmod 600 /opt/ansible-pct/.ssh/authorized-keys |
| 264 |
# $ echo 'ansible ALL = (root) NOPASSWD: /usr/sbin/pct' > /etc/sudoers.d/ansible_pct |
| 265 |
# |
| 266 |
# Save the displayed private key and add it to your ssh-agent |
| 267 |
# |
| 268 |
# Or use ansible: |
| 269 |
# --- |
| 270 |
# - name: Setup ansible-pct user and configure environment on Proxmox host |
| 271 |
# hosts: proxmox |
| 272 |
# become: true |
| 273 |
# gather_facts: false |
| 274 |
# |
| 275 |
# tasks: |
| 276 |
# - name: Create ansible user |
| 277 |
# ansible.builtin.user: |
| 278 |
# name: ansible |
| 279 |
# comment: Ansible User |
| 280 |
# home: /opt/ansible-pct |
| 281 |
# shell: /bin/sh |
| 282 |
# create_home: true |
| 283 |
# system: true |
| 284 |
# |
| 285 |
# - name: Create .ssh directory |
| 286 |
# ansible.builtin.file: |
| 287 |
# path: /opt/ansible-pct/.ssh |
| 288 |
# state: directory |
| 289 |
# owner: ansible |
| 290 |
# group: ansible |
| 291 |
# mode: '0700' |
| 292 |
# |
| 293 |
# - name: Generate SSH key for ansible user |
| 294 |
# community.crypto.openssh_keypair: |
| 295 |
# path: /opt/ansible-pct/.ssh/ansible |
| 296 |
# type: ed25519 |
| 297 |
# comment: 'ansible' |
| 298 |
# force: true |
| 299 |
# mode: '0600' |
| 300 |
# owner: ansible |
| 301 |
# group: ansible |
| 302 |
# |
| 303 |
# - name: Set public key as authorized key |
| 304 |
# ansible.builtin.copy: |
| 305 |
# src: /opt/ansible-pct/.ssh/ansible.pub |
| 306 |
# dest: /opt/ansible-pct/.ssh/authorized-keys |
| 307 |
# remote_src: yes |
| 308 |
# owner: ansible |
| 309 |
# group: ansible |
| 310 |
# mode: '0600' |
| 311 |
# |
| 312 |
# - name: Add sudoers entry for ansible user |
| 313 |
# ansible.builtin.copy: |
| 314 |
# content: 'ansible ALL = (root) NOPASSWD: /usr/sbin/pct' |
| 315 |
# dest: /etc/sudoers.d/ansible_pct |
| 316 |
# owner: root |
| 317 |
# group: root |
| 318 |
# mode: '0440' |
| 319 |
# |
| 320 |
# - name: Fetch private SSH key to localhost |
| 321 |
# ansible.builtin.fetch: |
| 322 |
# src: /opt/ansible-pct/.ssh/ansible |
| 323 |
# dest: ~/.ssh/proxmox_ansible_private_key |
| 324 |
# flat: yes |
| 325 |
# fail_on_missing: true |
| 326 |
# |
| 327 |
# - name: Clean up generated SSH keys |
| 328 |
# ansible.builtin.file: |
| 329 |
# path: /opt/ansible-pct/.ssh/ansible* |
| 330 |
# state: absent |
| 331 |
# |
| 332 |
# - name: Configure private key permissions on localhost |
| 333 |
# hosts: localhost |
| 334 |
# tasks: |
| 335 |
# - name: Set permissions for fetched private key |
| 336 |
# ansible.builtin.file: |
| 337 |
# path: ~/.ssh/proxmox_ansible_private_key |
| 338 |
# mode: '0600' |
| 339 |
# |
| 340 |
# -------------------------------- |
| 341 |
# Static inventory file: hosts.yml |
| 342 |
# -------------------------------- |
| 343 |
# all: |
| 344 |
# children: |
| 345 |
# lxc: |
| 346 |
# hosts: |
| 347 |
# container-1: |
| 348 |
# ansible_host: 10.0.0.10 |
| 349 |
# proxmox_vmid: 100 |
| 350 |
# ansible_connection: community.proxmox.proxmox_pct_remote |
| 351 |
# ansible_user: ansible |
| 352 |
# container-2: |
| 353 |
# ansible_host: 10.0.0.10 |
| 354 |
# proxmox_vmid: 200 |
| 355 |
# ansible_connection: community.proxmox.proxmox_pct_remote |
| 356 |
# ansible_user: ansible |
| 357 |
# proxmox: |
| 358 |
# hosts: |
| 359 |
# proxmox-1: |
| 360 |
# ansible_host: 10.0.0.10 |
| 361 |
# |
| 362 |
# |
| 363 |
# --------------------------------------------- |
| 364 |
# Dynamic inventory file: inventory.proxmox.yml |
| 365 |
# --------------------------------------------- |
| 366 |
# plugin: community.proxmox.proxmox |
| 367 |
# url: https://10.0.0.10:8006 |
| 368 |
# user: ansible@pam |
| 369 |
# token_id: ansible |
| 370 |
# token_secret: !vault | |
| 371 |
# $ANSIBLE_VAULT;1.1;AES256 |
| 372 |
# ... |
| 373 |
|
| 374 |
# want_facts: true |
| 375 |
# exclude_nodes: true |
| 376 |
# filters: |
| 377 |
# - proxmox_vmtype == "lxc" |
| 378 |
# want_proxmox_nodes_ansible_host: false |
| 379 |
# compose: |
| 380 |
# ansible_host: "'10.0.0.10'" |
| 381 |
# ansible_connection: "'community.proxmox.proxmox_pct_remote'" |
| 382 |
# ansible_user: "'ansible'" |
| 383 |
# |
| 384 |
# |
| 385 |
# ---------------------- |
| 386 |
# Playbook: playbook.yml |
| 387 |
# ---------------------- |
| 388 |
--- |
| 389 |
- hosts: lxc |
| 390 |
# On nodes with many containers you might want to deactivate the devices facts |
| 391 |
# or set `gather_facts: false` if you don't need them. |
| 392 |
# More info on gathering fact subsets: |
| 393 |
# https://docs.ansible.com/ansible/latest/collections/ansible/builtin/setup_module.html |
| 394 |
# |
| 395 |
# gather_facts: true |
| 396 |
# gather_subset: |
| 397 |
# - "!devices" |
| 398 |
tasks: |
| 399 |
- name: Ping LXC container |
| 400 |
ansible.builtin.ping: |
| 401 |
""" |
| 402 |
|
| 403 |
import os |
| 404 |
import pathlib |
| 405 |
import socket |
| 406 |
import tempfile |
| 407 |
import traceback |
| 408 |
import typing as t |
| 409 |
from binascii import hexlify |
| 410 |
|
| 411 |
from ansible.errors import ( |
| 412 |
AnsibleAuthenticationFailure, |
| 413 |
AnsibleConnectionFailure, |
| 414 |
AnsibleError, |
| 415 |
) |
| 416 |
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text |
| 417 |
from ansible.plugins.connection import ConnectionBase |
| 418 |
from ansible.utils.display import Display |
| 419 |
from ansible.utils.path import makedirs_safe |
| 420 |
|
| 421 |
from ansible_collections.community.proxmox.plugins.module_utils._filelock import FileLock, LockTimeout |
| 422 |
from ansible_collections.community.proxmox.plugins.module_utils.version import LooseVersion |
| 423 |
|
| 424 |
try: |
| 425 |
import paramiko |
| 426 |
|
| 427 |
PARAMIKO_IMPORT_ERR = None |
| 428 |
except ImportError: |
| 429 |
paramiko = None |
| 430 |
PARAMIKO_IMPORT_ERR = traceback.format_exc() |
| 431 |
|
| 432 |
|
| 433 |
display = Display() |
| 434 |
|
| 435 |
|
| 436 |
def authenticity_msg(hostname: str, ktype: str, fingerprint: str) -> str: |
| 437 |
msg = f""" |
| 438 |
paramiko: The authenticity of host '{hostname}' can't be established. |
| 439 |
The {ktype} key fingerprint is {fingerprint}. |
| 440 |
Are you sure you want to continue connecting (yes/no)? |
| 441 |
""" |
| 442 |
return msg |
| 443 |
|
| 444 |
|
| 445 |
MissingHostKeyPolicy: type = object |
| 446 |
if paramiko: |
| 447 |
MissingHostKeyPolicy = paramiko.MissingHostKeyPolicy |
| 448 |
|
| 449 |
|
| 450 |
class MyAddPolicy(MissingHostKeyPolicy): |
| 451 |
""" |
| 452 |
Based on AutoAddPolicy in paramiko so we can determine when keys are added |
| 453 |
|
| 454 |
and also prompt for input. |
| 455 |
|
| 456 |
Policy for automatically adding the hostname and new host key to the |
| 457 |
local L{HostKeys} object, and saving it. This is used by L{SSHClient}. |
| 458 |
""" |
| 459 |
|
| 460 |
def __init__(self, connection: Connection) -> None: |
| 461 |
self.connection = connection |
| 462 |
self._options = connection._options |
| 463 |
|
| 464 |
def missing_host_key(self, client, hostname, key) -> None: |
| 465 |
if all((self.connection.get_option("host_key_checking"), not self.connection.get_option("host_key_auto_add"))): |
| 466 |
fingerprint = hexlify(key.get_fingerprint()) |
| 467 |
ktype = key.get_name() |
| 468 |
|
| 469 |
if self.connection.get_option("use_persistent_connections") or self.connection.force_persistence: |
| 470 |
# don't print the prompt string since the user cannot respond |
| 471 |
# to the question anyway |
| 472 |
raise AnsibleError(authenticity_msg(hostname, ktype, fingerprint)[1:92]) |
| 473 |
|
| 474 |
inp = to_text( |
| 475 |
display.prompt_until(authenticity_msg(hostname, ktype, fingerprint), private=False), |
| 476 |
errors="surrogate_or_strict", |
| 477 |
) |
| 478 |
|
| 479 |
if inp.lower() not in ["yes", "y", ""]: |
| 480 |
raise AnsibleError("host connection rejected by user") |
| 481 |
|
| 482 |
key._added_by_ansible_this_time = True |
| 483 |
|
| 484 |
# existing implementation below: |
| 485 |
client._host_keys.add(hostname, key.get_name(), key) |
| 486 |
|
| 487 |
# host keys are actually saved in close() function below |
| 488 |
# in order to control ordering. |
| 489 |
|
| 490 |
|
| 491 |
class Connection(ConnectionBase): |
| 492 |
"""SSH based connections (paramiko) to Proxmox pct""" |
| 493 |
|
| 494 |
transport = "community.proxmox.proxmox_pct_remote" |
| 495 |
_log_channel: str | None = None |
| 496 |
|
| 497 |
def __init__(self, play_context, new_stdin, *args, **kwargs): |
| 498 |
super().__init__(play_context, new_stdin, *args, **kwargs) |
| 499 |
|
| 500 |
def _set_log_channel(self, name: str) -> None: |
| 501 |
"""Mimic paramiko.SSHClient.set_log_channel""" |
| 502 |
self._log_channel = name |
| 503 |
|
| 504 |
def _parse_proxy_command(self, port: int = 22) -> dict[str, t.Any]: |
| 505 |
proxy_command = self.get_option("proxy_command") or None |
| 506 |
|
| 507 |
sock_kwarg = {} |
| 508 |
if proxy_command: |
| 509 |
replacers = {"%h": self.get_option("remote_addr"), "%p": port, "%r": self.get_option("remote_user")} |
| 510 |
for find, replace in replacers.items(): |
| 511 |
proxy_command = proxy_command.replace(find, str(replace)) |
| 512 |
try: |
| 513 |
sock_kwarg = {"sock": paramiko.ProxyCommand(proxy_command)} |
| 514 |
display.vvv( |
| 515 |
f"CONFIGURE PROXY COMMAND FOR CONNECTION: {proxy_command}", host=self.get_option("remote_addr") |
| 516 |
) |
| 517 |
except AttributeError: |
| 518 |
display.warning( |
| 519 |
"Paramiko ProxyCommand support unavailable. " |
| 520 |
"Please upgrade to Paramiko 1.9.0 or newer. " |
| 521 |
"Not using configured ProxyCommand" |
| 522 |
) |
| 523 |
|
| 524 |
return sock_kwarg |
| 525 |
|
| 526 |
def _build_paramiko_disabled_algorithms(self) -> dict[str, t.Iterable[str]]: |
| 527 |
"""Build dict of algorithms to disable when RSA-SHA2 is turned off.""" |
| 528 |
paramiko_preferred_pubkeys = getattr(paramiko.Transport, "_preferred_pubkeys", ()) |
| 529 |
paramiko_preferred_hostkeys = getattr(paramiko.Transport, "_preferred_keys", ()) |
| 530 |
use_rsa_sha2_algorithms = self.get_option("use_rsa_sha2_algorithms") |
| 531 |
disabled_algorithms: dict[str, t.Iterable[str]] = {} |
| 532 |
if not use_rsa_sha2_algorithms: |
| 533 |
if paramiko_preferred_pubkeys: |
| 534 |
disabled_algorithms["pubkeys"] = tuple(a for a in paramiko_preferred_pubkeys if "rsa-sha2" in a) |
| 535 |
if paramiko_preferred_hostkeys: |
| 536 |
disabled_algorithms["keys"] = tuple(a for a in paramiko_preferred_hostkeys if "rsa-sha2" in a) |
| 537 |
return disabled_algorithms |
| 538 |
|
| 539 |
def _load_paramiko_system_host_keys(self, ssh: paramiko.SSHClient) -> None: |
| 540 |
"""Load system and user host key files when host key checking is enabled.""" |
| 541 |
for ssh_known_hosts in ("/etc/ssh/ssh_known_hosts", "/etc/openssh/ssh_known_hosts"): |
| 542 |
try: |
| 543 |
ssh.load_system_host_keys(ssh_known_hosts) |
| 544 |
break |
| 545 |
except OSError: |
| 546 |
pass # file was not found, but not required to function |
| 547 |
except paramiko.hostkeys.InvalidHostKey as e: |
| 548 |
raise AnsibleConnectionFailure(f"Invalid host key: {to_text(e.line)}") from e |
| 549 |
try: |
| 550 |
ssh.load_system_host_keys() |
| 551 |
except paramiko.hostkeys.InvalidHostKey as e: |
| 552 |
raise AnsibleConnectionFailure(f"Invalid host key: {to_text(e.line)}") from e |
| 553 |
|
| 554 |
def _paramiko_connect_ssh( |
| 555 |
self, |
| 556 |
ssh: paramiko.SSHClient, |
| 557 |
port: int, |
| 558 |
disabled_algorithms: dict[str, t.Iterable[str]], |
| 559 |
ssh_connect_kwargs: dict[str, t.Any], |
| 560 |
) -> None: |
| 561 |
"""Complete Paramiko ssh.connect with version-specific kwargs and error translation.""" |
| 562 |
conn_password = self.get_option("password") |
| 563 |
allow_agent = conn_password is None |
| 564 |
|
| 565 |
try: |
| 566 |
key_filename = None |
| 567 |
if self.get_option("private_key_file"): |
| 568 |
key_filename = os.path.expanduser(self.get_option("private_key_file")) |
| 569 |
|
| 570 |
# paramiko 2.2 introduced auth_timeout parameter |
| 571 |
if LooseVersion(paramiko.__version__) >= LooseVersion("2.2.0"): |
| 572 |
ssh_connect_kwargs["auth_timeout"] = self.get_option("timeout") |
| 573 |
|
| 574 |
# paramiko 1.15 introduced banner timeout parameter |
| 575 |
if LooseVersion(paramiko.__version__) >= LooseVersion("1.15.0"): |
| 576 |
ssh_connect_kwargs["banner_timeout"] = self.get_option("banner_timeout") |
| 577 |
|
| 578 |
ssh.connect( |
| 579 |
self.get_option("remote_addr").lower(), |
| 580 |
username=self.get_option("remote_user"), |
| 581 |
allow_agent=allow_agent, |
| 582 |
look_for_keys=self.get_option("look_for_keys"), |
| 583 |
key_filename=key_filename, |
| 584 |
password=conn_password, |
| 585 |
timeout=self.get_option("timeout"), |
| 586 |
port=port, |
| 587 |
disabled_algorithms=disabled_algorithms, |
| 588 |
**ssh_connect_kwargs, |
| 589 |
) |
| 590 |
except paramiko.ssh_exception.BadHostKeyException as e: |
| 591 |
raise AnsibleConnectionFailure(f"host key mismatch for {to_text(e.hostname)}") from e |
| 592 |
except paramiko.ssh_exception.AuthenticationException as e: |
| 593 |
raise AnsibleAuthenticationFailure(f"Failed to authenticate: {e}") from e |
| 594 |
except Exception as e: |
| 595 |
self._raise_paramiko_connect_exception(e, port) |
| 596 |
|
| 597 |
def _connect(self) -> Connection: |
| 598 |
"""Open an SSH session to the Proxmox host via Paramiko.""" |
| 599 |
|
| 600 |
if PARAMIKO_IMPORT_ERR is not None: |
| 601 |
raise AnsibleError(f"paramiko is not installed: {to_native(PARAMIKO_IMPORT_ERR)}") |
| 602 |
|
| 603 |
port = self.get_option("port") |
| 604 |
display.vvv( |
| 605 |
f"ESTABLISH PARAMIKO SSH CONNECTION FOR USER: {self.get_option('remote_user')} on PORT {to_text(port)} TO {self.get_option('remote_addr')}", |
| 606 |
host=self.get_option("remote_addr"), |
| 607 |
) |
| 608 |
|
| 609 |
ssh = paramiko.SSHClient() |
| 610 |
disabled_algorithms = self._build_paramiko_disabled_algorithms() |
| 611 |
|
| 612 |
# override paramiko's default logger name |
| 613 |
if self._log_channel is not None: |
| 614 |
ssh.set_log_channel(self._log_channel) |
| 615 |
|
| 616 |
self.keyfile = os.path.expanduser("~/.ssh/known_hosts") |
| 617 |
|
| 618 |
if self.get_option("host_key_checking"): |
| 619 |
self._load_paramiko_system_host_keys(ssh) |
| 620 |
|
| 621 |
ssh_connect_kwargs = self._parse_proxy_command(port) |
| 622 |
ssh.set_missing_host_key_policy(MyAddPolicy(self)) |
| 623 |
self._paramiko_connect_ssh(ssh, port, disabled_algorithms, ssh_connect_kwargs) |
| 624 |
self.ssh = ssh |
| 625 |
self._connected = True |
| 626 |
return self |
| 627 |
|
| 628 |
def _any_keys_added(self) -> bool: |
| 629 |
for keys in self.ssh._host_keys.values(): |
| 630 |
for key in keys.values(): |
| 631 |
if getattr(key, "_added_by_ansible_this_time", False): |
| 632 |
return True |
| 633 |
return False |
| 634 |
|
| 635 |
def _save_ssh_host_keys(self, filename: str) -> None: |
| 636 |
""" |
| 637 |
not using the paramiko save_ssh_host_keys function as we want to add new SSH keys at the bottom so folks |
| 638 |
don't complain about it :) |
| 639 |
""" |
| 640 |
|
| 641 |
if not self._any_keys_added(): |
| 642 |
return |
| 643 |
|
| 644 |
path = os.path.expanduser("~/.ssh") |
| 645 |
makedirs_safe(path) |
| 646 |
|
| 647 |
with open(filename, "w") as f: |
| 648 |
for hostname, keys in self.ssh._host_keys.items(): |
| 649 |
for keytype, key in keys.items(): |
| 650 |
# was f.write |
| 651 |
added_this_time = getattr(key, "_added_by_ansible_this_time", False) |
| 652 |
if not added_this_time: |
| 653 |
f.write(f"{hostname} {keytype} {key.get_base64()}\n") |
| 654 |
|
| 655 |
for hostname, keys in self.ssh._host_keys.items(): |
| 656 |
for keytype, key in keys.items(): |
| 657 |
added_this_time = getattr(key, "_added_by_ansible_this_time", False) |
| 658 |
if added_this_time: |
| 659 |
f.write(f"{hostname} {keytype} {key.get_base64()}\n") |
| 660 |
|
| 661 |
def _build_pct_command(self, cmd: str) -> str: |
| 662 |
cmd = ["/usr/sbin/pct", "exec", str(self.get_option("vmid")), "--", cmd] |
| 663 |
if self.get_option("remote_user") != "root": |
| 664 |
cmd = [self.get_option("proxmox_become_method")] + cmd |
| 665 |
display.vvv( |
| 666 |
f"INFO Running as non root user: {self.get_option('remote_user')}, trying to run pct with become method: " |
| 667 |
+ f"{self.get_option('proxmox_become_method')}", |
| 668 |
host=self.get_option("remote_addr"), |
| 669 |
) |
| 670 |
return " ".join(cmd) |
| 671 |
|
| 672 |
def _open_exec_channel(self) -> t.Any: |
| 673 |
try: |
| 674 |
self.ssh.get_transport().set_keepalive(5) |
| 675 |
return self.ssh.get_transport().open_session() |
| 676 |
except Exception as e: |
| 677 |
text_e = to_text(e) |
| 678 |
msg = "Failed to open session" |
| 679 |
if text_e: |
| 680 |
msg += f": {text_e}" |
| 681 |
raise AnsibleConnectionFailure(to_native(msg)) from e |
| 682 |
|
| 683 |
def _configure_exec_channel(self, chan: t.Any, cmd: str, sudoable: bool) -> None: |
| 684 |
# sudo usually requires a PTY (cf. requiretty option), therefore |
| 685 |
# we give it one by default (pty=True in ansible.cfg), and we try |
| 686 |
# to initialise from the calling environment when sudoable is enabled |
| 687 |
if self.get_option("pty") and sudoable: |
| 688 |
chan.get_pty( |
| 689 |
term=os.getenv("TERM", "vt100"), |
| 690 |
width=int(os.getenv("COLUMNS", "0")), |
| 691 |
height=int(os.getenv("LINES", "0")), |
| 692 |
) |
| 693 |
|
| 694 |
display.vvv(f"EXEC {cmd}", host=self.get_option("remote_addr")) |
| 695 |
|
| 696 |
if self.get_option("forward_agent"): |
| 697 |
paramiko.agent.AgentRequestHandler(chan) |
| 698 |
|
| 699 |
def _resolve_become_prompt(self, chan: t.Any, bufsize: int, become_buf: list[bytes]) -> tuple[bytes, bytes]: |
| 700 |
password_prompt = False |
| 701 |
become_success = False |
| 702 |
while not (become_success or password_prompt): |
| 703 |
display.debug("Waiting for Privilege Escalation input") |
| 704 |
|
| 705 |
chunk = chan.recv(bufsize) |
| 706 |
display.debug(f"chunk is: {to_text(chunk)}") |
| 707 |
if not chunk: |
| 708 |
if b"unknown user" in become_buf[0]: |
| 709 |
n_become_user = to_native(self.become.get_option("become_user")) |
| 710 |
raise AnsibleError(f"user {n_become_user} does not exist") |
| 711 |
else: |
| 712 |
break |
| 713 |
# raise AnsibleError('ssh connection closed waiting for password prompt') |
| 714 |
become_buf[0] += chunk |
| 715 |
|
| 716 |
# need to check every line because we might get lectured |
| 717 |
# and we might get the middle of a line in a chunk |
| 718 |
for line in become_buf[0].splitlines(True): |
| 719 |
if self.become.check_success(line): |
| 720 |
become_success = True |
| 721 |
break |
| 722 |
elif self.become.check_password_prompt(line): |
| 723 |
password_prompt = True |
| 724 |
break |
| 725 |
|
| 726 |
no_prompt_out = b"" |
| 727 |
no_prompt_err = b"" |
| 728 |
if password_prompt: |
| 729 |
if self.become: |
| 730 |
become_pass = self.become.get_option("become_pass") |
| 731 |
chan.sendall(to_bytes(become_pass, errors="surrogate_or_strict") + b"\n") |
| 732 |
else: |
| 733 |
raise AnsibleError("A password is required but none was supplied") |
| 734 |
else: |
| 735 |
no_prompt_out += become_buf[0] |
| 736 |
no_prompt_err += become_buf[0] |
| 737 |
|
| 738 |
return no_prompt_out, no_prompt_err |
| 739 |
|
| 740 |
def _exec_channel_cmd_and_stdin( |
| 741 |
self, chan: t.Any, cmd: bytes, in_data: bytes | None, bufsize: int |
| 742 |
) -> tuple[bytes, bytes]: |
| 743 |
no_prompt_out = b"" |
| 744 |
no_prompt_err = b"" |
| 745 |
become_buf = [b""] |
| 746 |
|
| 747 |
try: |
| 748 |
chan.exec_command(cmd) |
| 749 |
if self.become and self.become.expect_prompt(): |
| 750 |
np, ne = self._resolve_become_prompt(chan, bufsize, become_buf) |
| 751 |
no_prompt_out += np |
| 752 |
no_prompt_err += ne |
| 753 |
|
| 754 |
if in_data: |
| 755 |
for i in range(0, len(in_data), bufsize): |
| 756 |
chan.send(in_data[i : i + bufsize]) |
| 757 |
chan.shutdown_write() |
| 758 |
elif in_data == b"": |
| 759 |
chan.shutdown_write() |
| 760 |
|
| 761 |
except socket.timeout as e: |
| 762 |
raise AnsibleError("ssh timed out waiting for privilege escalation.\n" + to_text(become_buf[0])) from e |
| 763 |
|
| 764 |
return no_prompt_out, no_prompt_err |
| 765 |
|
| 766 |
def exec_command(self, cmd: str, in_data: bytes | None = None, sudoable: bool = True) -> tuple[int, bytes, bytes]: |
| 767 |
"""run a command on inside the LXC container""" |
| 768 |
|
| 769 |
cmd = self._build_pct_command(cmd) |
| 770 |
|
| 771 |
super().exec_command(cmd, in_data=in_data, sudoable=sudoable) |
| 772 |
|
| 773 |
bufsize = 4096 |
| 774 |
|
| 775 |
chan = self._open_exec_channel() |
| 776 |
self._configure_exec_channel(chan, cmd, sudoable) |
| 777 |
|
| 778 |
cmd_bytes = to_bytes(cmd, errors="surrogate_or_strict") |
| 779 |
no_prompt_out, no_prompt_err = self._exec_channel_cmd_and_stdin(chan, cmd_bytes, in_data, bufsize) |
| 780 |
|
| 781 |
stdout = b"".join(chan.makefile("rb", bufsize)) |
| 782 |
stderr = b"".join(chan.makefile_stderr("rb", bufsize)) |
| 783 |
returncode = chan.recv_exit_status() |
| 784 |
|
| 785 |
if "pct: not found" in stderr.decode("utf-8"): |
| 786 |
raise AnsibleError(f"pct not found in path of host: {to_text(self.get_option('remote_addr'))}") |
| 787 |
|
| 788 |
return (returncode, no_prompt_out + stdout, no_prompt_out + stderr) |
| 789 |
|
| 790 |
def put_file(self, in_path: str, out_path: str) -> None: |
| 791 |
"""transfer a file from local to remote""" |
| 792 |
|
| 793 |
display.vvv(f"PUT {in_path} TO {out_path}", host=self.get_option("remote_addr")) |
| 794 |
try: |
| 795 |
with open(in_path, "rb") as f: |
| 796 |
data = f.read() |
| 797 |
returncode, stdout, stderr = self.exec_command( |
| 798 |
" ".join([self._shell.executable, "-c", self._shell.quote(f"cat > {out_path}")]), |
| 799 |
in_data=data, |
| 800 |
sudoable=False, |
| 801 |
) |
| 802 |
if returncode != 0: |
| 803 |
if "cat: not found" in stderr.decode("utf-8"): |
| 804 |
raise AnsibleError(f"cat not found in path of container: {to_text(self.get_option('vmid'))}") |
| 805 |
raise AnsibleError(f"{to_text(stdout)}\n{to_text(stderr)}") |
| 806 |
except Exception as e: |
| 807 |
raise AnsibleError(f"error occurred while putting file from {in_path} to {out_path}!\n{to_text(e)}") from e |
| 808 |
|
| 809 |
def fetch_file(self, in_path: str, out_path: str) -> None: |
| 810 |
"""save a remote file to the specified path""" |
| 811 |
|
| 812 |
display.vvv(f"FETCH {in_path} TO {out_path}", host=self.get_option("remote_addr")) |
| 813 |
try: |
| 814 |
returncode, stdout, stderr = self.exec_command( |
| 815 |
" ".join([self._shell.executable, "-c", self._shell.quote(f"cat {in_path}")]), sudoable=False |
| 816 |
) |
| 817 |
if returncode != 0: |
| 818 |
if "cat: not found" in stderr.decode("utf-8"): |
| 819 |
raise AnsibleError(f"cat not found in path of container: {to_text(self.get_option('vmid'))}") |
| 820 |
raise AnsibleError(f"{to_text(stdout)}\n{to_text(stderr)}") |
| 821 |
with open(out_path, "wb") as f: |
| 822 |
f.write(stdout) |
| 823 |
except Exception as e: |
| 824 |
raise AnsibleError(f"error occurred while fetching file from {in_path} to {out_path}!\n{to_text(e)}") from e |
| 825 |
|
| 826 |
def reset(self) -> None: |
| 827 |
"""reset the connection""" |
| 828 |
|
| 829 |
if not self._connected: |
| 830 |
return |
| 831 |
self.close() |
| 832 |
self._connect() |
| 833 |
|
| 834 |
def close(self) -> None: |
| 835 |
"""terminate the connection""" |
| 836 |
|
| 837 |
if self.get_option("host_key_checking") and self.get_option("record_host_keys") and self._any_keys_added(): |
| 838 |
# add any new SSH host keys -- warning -- this could be slow |
| 839 |
# (This doesn't acquire the connection lock because it needs |
| 840 |
# to exclude only other known_hosts writers, not connections |
| 841 |
# that are starting up.) |
| 842 |
lockfile = os.path.basename(self.keyfile) |
| 843 |
dirname = os.path.dirname(self.keyfile) |
| 844 |
makedirs_safe(dirname) |
| 845 |
tmp_keyfile_name = None |
| 846 |
try: |
| 847 |
with FileLock().lock_file(lockfile, dirname, self.get_option("lock_file_timeout")): |
| 848 |
# just in case any were added recently |
| 849 |
|
| 850 |
self.ssh.load_system_host_keys() |
| 851 |
self.ssh._host_keys.update(self.ssh._system_host_keys) |
| 852 |
|
| 853 |
# gather information about the current key file, so |
| 854 |
# we can ensure the new file has the correct mode/owner |
| 855 |
|
| 856 |
key_dir = os.path.dirname(self.keyfile) |
| 857 |
if os.path.exists(self.keyfile): |
| 858 |
key_stat = os.stat(self.keyfile) |
| 859 |
mode = key_stat.st_mode & 0o777 |
| 860 |
uid = key_stat.st_uid |
| 861 |
gid = key_stat.st_gid |
| 862 |
else: |
| 863 |
mode = 0o644 |
| 864 |
uid = os.getuid() |
| 865 |
gid = os.getgid() |
| 866 |
|
| 867 |
# Save the new keys to a temporary file and move it into place |
| 868 |
# rather than rewriting the file. We set delete=False because |
| 869 |
# the file will be moved into place rather than cleaned up. |
| 870 |
|
| 871 |
with tempfile.NamedTemporaryFile(dir=key_dir, delete=False) as tmp_keyfile: |
| 872 |
tmp_keyfile_name = tmp_keyfile.name |
| 873 |
os.chmod(tmp_keyfile_name, mode) |
| 874 |
os.chown(tmp_keyfile_name, uid, gid) |
| 875 |
self._save_ssh_host_keys(tmp_keyfile_name) |
| 876 |
|
| 877 |
os.rename(tmp_keyfile_name, self.keyfile) |
| 878 |
except LockTimeout as e: |
| 879 |
raise AnsibleError( |
| 880 |
f"writing lock file for {self.keyfile} ran in to the timeout of {self.get_option('lock_file_timeout')}s" |
| 881 |
) from e |
| 882 |
except paramiko.hostkeys.InvalidHostKey as e: |
| 883 |
raise AnsibleConnectionFailure(f"Invalid host key: {e.line}") from e |
| 884 |
except Exception as e: |
| 885 |
# unable to save keys, including scenario when key was invalid |
| 886 |
# and caught earlier |
| 887 |
raise AnsibleError(f"error occurred while writing SSH host keys!\n{to_text(e)}") from e |
| 888 |
finally: |
| 889 |
if tmp_keyfile_name is not None: |
| 890 |
pathlib.Path(tmp_keyfile_name).unlink(missing_ok=True) |
| 891 |
|
| 892 |
self.ssh.close() |
| 893 |
self._connected = False |