1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
|
# SPDX-FileCopyrightText: 2024 Greenbone AG
#
# SPDX-License-Identifier: GPL-3.0-or-later
import base64
import errno
import hashlib
import logging
import socket as socketlib
import sys
from os import PathLike
from pathlib import Path
from time import time
from typing import Any, Callable, Optional, TextIO, Union
import paramiko
import paramiko.ssh_exception
import paramiko.transport
from gvm.errors import GvmError
from ._connection import BUF_SIZE, DEFAULT_TIMEOUT
logger = logging.getLogger("gvm.connections.ssh")
DEFAULT_SSH_PORT = 22
DEFAULT_SSH_USERNAME = "gmp"
DEFAULT_SSH_PASSWORD = ""
DEFAULT_HOSTNAME = "127.0.0.1"
DEFAULT_KNOWN_HOSTS_FILE = ".ssh/known_hosts"
class SSHConnection:
"""
SSH Class to connect, read and write from GVM via SSH
"""
def __init__(
self,
*,
timeout: Optional[Union[int, float]] = DEFAULT_TIMEOUT,
hostname: Optional[str] = DEFAULT_HOSTNAME,
port: Optional[int] = DEFAULT_SSH_PORT,
username: Optional[str] = DEFAULT_SSH_USERNAME,
password: Optional[str] = DEFAULT_SSH_PASSWORD,
known_hosts_file: Optional[Union[str, PathLike]] = None,
auto_accept_host: Optional[bool] = None,
file: TextIO = sys.stdout,
input: Callable[[], str] = input,
exit: Callable[[str], Any] = sys.exit,
) -> None:
"""
Create a new SSH connection instance.
Args:
timeout: Timeout in seconds for the connection.
hostname: DNS name or IP address of the remote server. Default is
127.0.0.1.
port: Port of the remote SSH server. Default is port 22.
username: Username to use for SSH login. Default is "gmp".
password: Password to use for SSH login. Default is "".
"""
self._client: Optional[paramiko.SSHClient] = None
self.hostname = hostname if hostname is not None else DEFAULT_HOSTNAME
self.port = int(port) if port is not None else DEFAULT_SSH_PORT
self.username = (
username if username is not None else DEFAULT_SSH_USERNAME
)
self.password = (
password if password is not None else DEFAULT_SSH_PASSWORD
)
self.known_hosts_file = (
Path(known_hosts_file)
if known_hosts_file is not None
else Path.home() / DEFAULT_KNOWN_HOSTS_FILE
)
self.auto_accept_host = auto_accept_host
self._timeout = timeout
self._file = file
self._input = input
self._exit = exit
def _send_all(self, data: bytes) -> int:
"""Returns the sum of sent bytes if success"""
sent_sum = 0
while data:
sent = self._stdin.channel.send(data)
if not sent:
# Connection was closed by server
raise GvmError("Remote closed the connection")
sent_sum += sent
data = data[sent:]
return sent_sum
def _auto_accept_host(
self, hostkeys: paramiko.HostKeys, key: paramiko.PKey
) -> None:
if self.port == DEFAULT_SSH_PORT:
hostkeys.add(self.hostname, key.get_name(), key)
elif self.port != DEFAULT_SSH_PORT:
hostkeys.add(
"[" + self.hostname + "]:" + str(self.port),
key.get_name(),
key,
)
try:
hostkeys.save(filename=str(self.known_hosts_file))
except OSError as e:
raise GvmError(
"Something went wrong with writing "
f"the known_hosts file {self.known_hosts_file.absolute()}: {e}"
) from None
key_type = key.get_name().replace("ssh-", "").upper()
logger.info(
"Warning: Permanently added '%s' (%s) to "
"the list of known hosts.",
self.hostname,
key_type,
)
def _ssh_authentication_input_loop(
self, hostkeys: paramiko.HostKeys, key: paramiko.PKey
) -> None:
# Ask user for permission to continue
# let it look like openssh
sha64_fingerprint = base64.b64encode(
hashlib.sha256(base64.b64decode(key.get_base64())).digest()
).decode("utf-8")[:-1]
key_type = key.get_name().replace("ssh-", "").upper()
print(
f"The authenticity of host '{self.hostname}' can't "
"be established.",
file=self._file,
)
print(
f"{key_type} key fingerprint is {sha64_fingerprint}.",
file=self._file,
)
print(
"Are you sure you want to continue connecting (yes/no)? ",
end="",
file=self._file,
)
add = self._input()
while True:
if add == "yes":
if self.port == DEFAULT_SSH_PORT:
hostkeys.add(self.hostname, key.get_name(), key)
elif self.port != DEFAULT_SSH_PORT:
hostkeys.add(
"[" + self.hostname + "]:" + str(self.port),
key.get_name(),
key,
)
# ask user if the key should be added permanently
print(
f"Do you want to add {self.hostname} "
"to known_hosts (yes/no)? ",
end="",
file=self._file,
)
save = self._input()
while True:
if save == "yes":
try:
hostkeys.save(filename=str(self.known_hosts_file))
except OSError as e:
raise GvmError(
"Something went wrong with writing "
f"the known_hosts file: {e}"
) from None
logger.info(
"Warning: Permanently added '%s' (%s) to "
"the list of known hosts.",
self.hostname,
key_type,
)
break
elif save == "no":
logger.info(
"Warning: Host '%s' (%s) not added to "
"the list of known hosts.",
self.hostname,
key_type,
)
break
else:
print(
"Please type 'yes' or 'no': ",
end="",
file=self._file,
)
save = self._input()
break
elif add == "no":
self._exit("User denied key. Host key verification failed.")
else:
print("Please type 'yes' or 'no': ", end="", file=self._file)
add = self._input()
def _get_remote_host_key(self) -> paramiko.PKey:
"""Get the remote host key for ssh connection"""
try:
tmp_socket = socketlib.socket()
tmp_socket.settimeout(self._timeout)
tmp_socket.connect((self.hostname, self.port))
except OSError as e:
tmp_socket.close()
raise GvmError(
"Couldn't establish a connection to fetch the"
f" remote server key: {e}"
) from None
trans = paramiko.transport.Transport(tmp_socket)
try:
trans.start_client()
except paramiko.SSHException as e:
tmp_socket.close()
raise GvmError(
f"Couldn't fetch the remote server key: {e}"
) from None
key = trans.get_remote_server_key()
try:
trans.close()
except paramiko.SSHException as e:
raise GvmError(
f"Couldn't close the connection to the remote server key: {e}"
) from None
finally:
tmp_socket.close()
return key
def _ssh_authentication(self) -> None:
"""Search/add/save the servers key for the SSH authentication process"""
if not self._client:
raise GvmError("SSH Client not connected.")
# set to reject policy (avoid MITM attacks)
self._client.set_missing_host_key_policy(paramiko.RejectPolicy())
# openssh is posix, so this might only a posix approach
# https://stackoverflow.com/q/32945533
try:
# load the keys into paramiko and check if remote is in the list
self._client.load_host_keys(filename=str(self.known_hosts_file))
except OSError as e:
if e.errno != errno.ENOENT:
raise GvmError(
"Something went wrong with reading "
f"the known_hosts file: {e}"
) from None
hostkeys = self._client.get_host_keys()
# Switch based on SSH Port
if self.port == DEFAULT_SSH_PORT:
hostname = self.hostname
else:
hostname = f"[{self.hostname}]:{self.port}"
if not hostkeys.lookup(hostname):
# Key not found, so connect to remote and fetch the key
# with the paramiko Transport protocol
key = self._get_remote_host_key()
if self.auto_accept_host:
self._auto_accept_host(hostkeys=hostkeys, key=key)
else:
self._ssh_authentication_input_loop(hostkeys=hostkeys, key=key)
def _read(self) -> bytes:
return self._stdout.channel.recv(BUF_SIZE)
def send(self, data: bytes) -> None:
self._send_all(data)
def read(self) -> bytes:
break_timeout = (
time() + self._timeout if self._timeout is not None else None
)
data = self._read()
if not data:
# Connection was closed by server
raise GvmError("Remote closed the connection")
if break_timeout and time() > break_timeout:
raise GvmError("Timeout while reading the response")
return data
def connect(self) -> None:
"""
Connect to the SSH server and authenticate to it
"""
self._client = paramiko.SSHClient()
self._ssh_authentication()
try:
self._client.connect(
hostname=self.hostname,
username=self.username,
password=self.password,
timeout=self._timeout,
port=int(self.port),
allow_agent=False,
look_for_keys=False,
)
except (
paramiko.BadHostKeyException,
paramiko.AuthenticationException,
paramiko.SSHException,
paramiko.ssh_exception.NoValidConnectionsError,
ConnectionError,
) as e:
raise GvmError(f"SSH Connection failed: {e}") from None
self._stdin, self._stdout, self._stderr = self._client.exec_command(
"", get_pty=False
)
def disconnect(self) -> None:
"""Disconnect and close the connection to the remote server"""
try:
if self._client is not None:
self._client.close()
except OSError as e:
logger.debug("Connection closing error: %s", e)
raise e
if self._client is not None:
self._client = None
del self._stdin, self._stdout, self._stderr
def finish_send(self) -> None:
# shutdown socket for sending. only allow reading data afterwards
self._stdout.channel.shutdown(socketlib.SHUT_WR)
|