| 1 |
"""High level functions for working with SSH.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import dataclasses |
| 6 |
import itertools |
| 7 |
import json |
| 8 |
import os |
| 9 |
import random |
| 10 |
import re |
| 11 |
import subprocess |
| 12 |
import shlex |
| 13 |
import typing as t |
| 14 |
|
| 15 |
from .encoding import ( |
| 16 |
to_text, |
| 17 |
) |
| 18 |
|
| 19 |
from .util import ( |
| 20 |
ApplicationError, |
| 21 |
common_environment, |
| 22 |
display, |
| 23 |
exclude_none_values, |
| 24 |
sanitize_host_name, |
| 25 |
) |
| 26 |
|
| 27 |
from .config import ( |
| 28 |
EnvironmentConfig, |
| 29 |
) |
| 30 |
|
| 31 |
|
| 32 |
@dataclasses.dataclass |
| 33 |
class SshConnectionDetail: |
| 34 |
"""Information needed to establish an SSH connection to a host.""" |
| 35 |
|
| 36 |
name: str |
| 37 |
host: str |
| 38 |
port: t.Optional[int] |
| 39 |
user: str |
| 40 |
identity_file: str |
| 41 |
python_interpreter: t.Optional[str] = None |
| 42 |
powershell_interpreter: str | None = None |
| 43 |
shell_type: t.Optional[str] = None |
| 44 |
enable_rsa_sha1: bool = False |
| 45 |
|
| 46 |
def __post_init__(self): |
| 47 |
self.name = sanitize_host_name(self.name) |
| 48 |
|
| 49 |
@property |
| 50 |
def options(self) -> dict[str, str]: |
| 51 |
"""OpenSSH config options, which can be passed to the `ssh` CLI with the `-o` argument.""" |
| 52 |
options: dict[str, str] = {} |
| 53 |
|
| 54 |
if self.enable_rsa_sha1: |
| 55 |
# Newer OpenSSH clients connecting to older SSH servers must explicitly enable ssh-rsa support. |
| 56 |
# OpenSSH 8.8, released on 2021-09-26, deprecated using RSA with the SHA-1 hash algorithm (ssh-rsa). |
| 57 |
# OpenSSH 7.2, released on 2016-02-29, added support for using RSA with SHA-256/512 hash algorithms. |
| 58 |
# See: https://www.openssh.com/txt/release-8.8 |
| 59 |
algorithms = '+ssh-rsa' # append the algorithm to the default list, requires OpenSSH 7.0 or later |
| 60 |
|
| 61 |
options.update( |
| 62 |
# Host key signature algorithms that the client wants to use. |
| 63 |
# Available options can be found with `ssh -Q HostKeyAlgorithms` or `ssh -Q key` on older clients. |
| 64 |
# This option was updated in OpenSSH 7.0, released on 2015-08-11, to support the "+" prefix. |
| 65 |
# See: https://www.openssh.com/txt/release-7.0 |
| 66 |
HostKeyAlgorithms=algorithms, |
| 67 |
# Signature algorithms that will be used for public key authentication. |
| 68 |
# Available options can be found with `ssh -Q PubkeyAcceptedAlgorithms` or `ssh -Q key` on older clients. |
| 69 |
# This option was added in OpenSSH 7.0, released on 2015-08-11. |
| 70 |
# See: https://www.openssh.com/txt/release-7.0 |
| 71 |
# This option is an alias for PubkeyAcceptedAlgorithms, which was added in OpenSSH 8.5. |
| 72 |
# See: https://www.openssh.com/txt/release-8.5 |
| 73 |
PubkeyAcceptedKeyTypes=algorithms, |
| 74 |
) |
| 75 |
|
| 76 |
return options |
| 77 |
|
| 78 |
|
| 79 |
class SshProcess: |
| 80 |
"""Wrapper around an SSH process.""" |
| 81 |
|
| 82 |
def __init__(self, process: t.Optional[subprocess.Popen]) -> None: |
| 83 |
self._process = process |
| 84 |
self.pending_forwards: t.Optional[list[tuple[str, int]]] = None |
| 85 |
|
| 86 |
self.forwards: dict[tuple[str, int], int] = {} |
| 87 |
|
| 88 |
def terminate(self) -> None: |
| 89 |
"""Terminate the SSH process.""" |
| 90 |
if not self._process: |
| 91 |
return # explain mode |
| 92 |
|
| 93 |
# noinspection PyBroadException |
| 94 |
try: |
| 95 |
self._process.terminate() |
| 96 |
except Exception: # pylint: disable=broad-except |
| 97 |
pass |
| 98 |
|
| 99 |
def wait(self) -> None: |
| 100 |
"""Wait for the SSH process to terminate.""" |
| 101 |
if not self._process: |
| 102 |
return # explain mode |
| 103 |
|
| 104 |
self._process.wait() |
| 105 |
|
| 106 |
def collect_port_forwards(self) -> dict[tuple[str, int], int]: |
| 107 |
"""Collect port assignments for dynamic SSH port forwards.""" |
| 108 |
errors: list[str] = [] |
| 109 |
|
| 110 |
display.info('Collecting %d SSH port forward(s).' % len(self.pending_forwards), verbosity=2) |
| 111 |
|
| 112 |
while self.pending_forwards: |
| 113 |
if self._process: |
| 114 |
line_bytes = self._process.stderr.readline() |
| 115 |
|
| 116 |
if not line_bytes: |
| 117 |
if errors: |
| 118 |
details = ':\n%s' % '\n'.join(errors) |
| 119 |
else: |
| 120 |
details = '.' |
| 121 |
|
| 122 |
raise ApplicationError('SSH port forwarding failed%s' % details) |
| 123 |
|
| 124 |
line = to_text(line_bytes).strip() |
| 125 |
|
| 126 |
match = re.search(r'^Allocated port (?P<src_port>[0-9]+) for remote forward to (?P<dst_host>[^:]+):(?P<dst_port>[0-9]+)$', line) |
| 127 |
|
| 128 |
if not match: |
| 129 |
if re.search(r'^Warning: Permanently added .* to the list of known hosts\.$', line): |
| 130 |
continue |
| 131 |
|
| 132 |
display.warning('Unexpected SSH port forwarding output: %s' % line, verbosity=2) |
| 133 |
|
| 134 |
errors.append(line) |
| 135 |
continue |
| 136 |
|
| 137 |
src_port = int(match.group('src_port')) |
| 138 |
dst_host = str(match.group('dst_host')) |
| 139 |
dst_port = int(match.group('dst_port')) |
| 140 |
|
| 141 |
dst = (dst_host, dst_port) |
| 142 |
else: |
| 143 |
# explain mode |
| 144 |
dst = self.pending_forwards[0] |
| 145 |
src_port = random.randint(40000, 50000) |
| 146 |
|
| 147 |
self.pending_forwards.remove(dst) |
| 148 |
self.forwards[dst] = src_port |
| 149 |
|
| 150 |
display.info('Collected %d SSH port forward(s):\n%s' % ( |
| 151 |
len(self.forwards), '\n'.join('%s -> %s:%s' % (src_port, dst[0], dst[1]) for dst, src_port in sorted(self.forwards.items()))), verbosity=2) |
| 152 |
|
| 153 |
return self.forwards |
| 154 |
|
| 155 |
|
| 156 |
def create_ssh_command( |
| 157 |
ssh: SshConnectionDetail, |
| 158 |
options: t.Optional[dict[str, t.Union[str, int]]] = None, |
| 159 |
cli_args: list[str] = None, |
| 160 |
command: t.Optional[str] = None, |
| 161 |
) -> list[str]: |
| 162 |
"""Create an SSH command using the specified options.""" |
| 163 |
cmd = [ |
| 164 |
'ssh', |
| 165 |
'-n', # prevent reading from stdin |
| 166 |
'-i', ssh.identity_file, # file from which the identity for public key authentication is read |
| 167 |
] # fmt: skip |
| 168 |
|
| 169 |
if not command: |
| 170 |
cmd.append('-N') # do not execute a remote command |
| 171 |
|
| 172 |
if ssh.port: |
| 173 |
cmd.extend(['-p', str(ssh.port)]) # port to connect to on the remote host |
| 174 |
|
| 175 |
if ssh.user: |
| 176 |
cmd.extend(['-l', ssh.user]) # user to log in as on the remote machine |
| 177 |
|
| 178 |
ssh_options: dict[str, t.Union[int, str]] = dict( |
| 179 |
BatchMode='yes', |
| 180 |
ExitOnForwardFailure='yes', |
| 181 |
LogLevel='ERROR', |
| 182 |
ServerAliveCountMax=4, |
| 183 |
ServerAliveInterval=15, |
| 184 |
StrictHostKeyChecking='no', |
| 185 |
UserKnownHostsFile='/dev/null', |
| 186 |
) |
| 187 |
|
| 188 |
ssh_options.update(options or {}) |
| 189 |
|
| 190 |
cmd.extend(ssh_options_to_list(ssh_options)) |
| 191 |
cmd.extend(cli_args or []) |
| 192 |
cmd.append(ssh.host) |
| 193 |
|
| 194 |
if command: |
| 195 |
cmd.append(command) |
| 196 |
|
| 197 |
return cmd |
| 198 |
|
| 199 |
|
| 200 |
def ssh_options_to_list(options: t.Union[dict[str, t.Union[int, str]], dict[str, str]]) -> list[str]: |
| 201 |
"""Format a dictionary of SSH options as a list suitable for passing to the `ssh` command.""" |
| 202 |
return list(itertools.chain.from_iterable( |
| 203 |
('-o', f'{key}={value}') for key, value in sorted(options.items()) |
| 204 |
)) |
| 205 |
|
| 206 |
|
| 207 |
def ssh_options_to_str(options: t.Union[dict[str, t.Union[int, str]], dict[str, str]]) -> str: |
| 208 |
"""Format a dictionary of SSH options as a string suitable for passing as `ansible_ssh_extra_args` in inventory.""" |
| 209 |
return shlex.join(ssh_options_to_list(options)) |
| 210 |
|
| 211 |
|
| 212 |
def run_ssh_command( |
| 213 |
args: EnvironmentConfig, |
| 214 |
ssh: SshConnectionDetail, |
| 215 |
options: t.Optional[dict[str, t.Union[str, int]]] = None, |
| 216 |
cli_args: list[str] = None, |
| 217 |
command: t.Optional[str] = None, |
| 218 |
) -> SshProcess: |
| 219 |
"""Run the specified SSH command, returning the created SshProcess instance created.""" |
| 220 |
cmd = create_ssh_command(ssh, options, cli_args, command) |
| 221 |
env = common_environment() |
| 222 |
|
| 223 |
cmd_show = shlex.join(cmd) |
| 224 |
display.info('Run background command: %s' % cmd_show, verbosity=1, truncate=True) |
| 225 |
|
| 226 |
if args.explain: |
| 227 |
process = SshProcess(None) |
| 228 |
else: |
| 229 |
process = SshProcess(subprocess.Popen(cmd, env=env, bufsize=-1, # pylint: disable=consider-using-with |
| 230 |
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE)) |
| 231 |
|
| 232 |
return process |
| 233 |
|
| 234 |
|
| 235 |
def create_ssh_port_forwards( |
| 236 |
args: EnvironmentConfig, |
| 237 |
ssh: SshConnectionDetail, |
| 238 |
forwards: list[tuple[str, int]], |
| 239 |
) -> SshProcess: |
| 240 |
""" |
| 241 |
Create SSH port forwards using the provided list of tuples (target_host, target_port). |
| 242 |
Port bindings will be automatically assigned by SSH and must be collected with a subsequent call to collect_port_forwards. |
| 243 |
""" |
| 244 |
options: dict[str, t.Union[str, int]] = dict( |
| 245 |
LogLevel='INFO', # info level required to get messages on stderr indicating the ports assigned to each forward |
| 246 |
ControlPath='none', # if the user has ControlPath set up for every host, it will prevent creation of forwards |
| 247 |
) |
| 248 |
|
| 249 |
cli_args = [] |
| 250 |
|
| 251 |
for forward_host, forward_port in forwards: |
| 252 |
cli_args.extend(['-R', ':'.join([str(0), forward_host, str(forward_port)])]) |
| 253 |
|
| 254 |
process = run_ssh_command(args, ssh, options, cli_args) |
| 255 |
process.pending_forwards = forwards |
| 256 |
|
| 257 |
return process |
| 258 |
|
| 259 |
|
| 260 |
def create_ssh_port_redirects( |
| 261 |
args: EnvironmentConfig, |
| 262 |
ssh: SshConnectionDetail, |
| 263 |
redirects: list[tuple[int, str, int]], |
| 264 |
) -> SshProcess: |
| 265 |
"""Create SSH port redirections using the provided list of tuples (bind_port, target_host, target_port).""" |
| 266 |
options: dict[str, t.Union[str, int]] = {} |
| 267 |
cli_args = [] |
| 268 |
|
| 269 |
for bind_port, target_host, target_port in redirects: |
| 270 |
cli_args.extend(['-R', ':'.join([str(bind_port), target_host, str(target_port)])]) |
| 271 |
|
| 272 |
process = run_ssh_command(args, ssh, options, cli_args) |
| 273 |
|
| 274 |
return process |
| 275 |
|
| 276 |
|
| 277 |
def generate_ssh_inventory(ssh_connections: list[SshConnectionDetail]) -> str: |
| 278 |
"""Return an inventory file in JSON format, created from the provided SSH connection details.""" |
| 279 |
inventory = dict( |
| 280 |
all=dict( |
| 281 |
hosts=dict((ssh.name, exclude_none_values(dict( |
| 282 |
ansible_host=ssh.host, |
| 283 |
ansible_port=ssh.port, |
| 284 |
ansible_user=ssh.user, |
| 285 |
ansible_ssh_private_key_file=os.path.abspath(ssh.identity_file), |
| 286 |
ansible_connection='ssh', |
| 287 |
ansible_pipelining='yes', |
| 288 |
ansible_python_interpreter=ssh.python_interpreter, |
| 289 |
ansible_pwsh_interpreter=ssh.powershell_interpreter, |
| 290 |
ansible_shell_type=ssh.shell_type, |
| 291 |
ansible_ssh_extra_args=ssh_options_to_str(dict(UserKnownHostsFile='/dev/null', **ssh.options)), # avoid changing the test environment |
| 292 |
ansible_ssh_host_key_checking='no', |
| 293 |
))) for ssh in ssh_connections), |
| 294 |
), |
| 295 |
) |
| 296 |
|
| 297 |
inventory_text = json.dumps(inventory, indent=4, sort_keys=True) |
| 298 |
|
| 299 |
display.info('>>> SSH Inventory\n%s' % inventory_text, verbosity=3) |
| 300 |
|
| 301 |
return inventory_text |