| 1 |
"""Basic ssh tunnel utilities, and convenience functions for tunneling |
| 2 |
zeromq connections. |
| 3 |
""" |
| 4 |
|
| 5 |
# Copyright (C) 2010-2011 IPython Development Team |
| 6 |
# Copyright (C) 2011- PyZMQ Developers |
| 7 |
# |
| 8 |
# Redistributed from IPython under the terms of the BSD License. |
| 9 |
from __future__ import annotations |
| 10 |
|
| 11 |
import atexit |
| 12 |
import os |
| 13 |
import re |
| 14 |
import signal |
| 15 |
import socket |
| 16 |
import sys |
| 17 |
import warnings |
| 18 |
from getpass import getpass, getuser |
| 19 |
from multiprocessing import Process |
| 20 |
from types import ModuleType |
| 21 |
from typing import Any, cast |
| 22 |
|
| 23 |
try: |
| 24 |
with warnings.catch_warnings(): |
| 25 |
warnings.simplefilter("ignore", DeprecationWarning) |
| 26 |
import paramiko |
| 27 |
|
| 28 |
SSHException = paramiko.ssh_exception.SSHException |
| 29 |
except ImportError: |
| 30 |
paramiko = None # type:ignore[assignment] |
| 31 |
|
| 32 |
class SSHException(Exception): # type:ignore[no-redef] # noqa |
| 33 |
pass |
| 34 |
|
| 35 |
else: |
| 36 |
from .forward import forward_tunnel |
| 37 |
|
| 38 |
pexpect: ModuleType | None |
| 39 |
try: |
| 40 |
import pexpect |
| 41 |
except ImportError: |
| 42 |
pexpect = None |
| 43 |
|
| 44 |
|
| 45 |
def select_random_ports(n: int) -> list[int]: |
| 46 |
"""Select and return n random ports that are available.""" |
| 47 |
ports = [] |
| 48 |
sockets = [] |
| 49 |
for _ in range(n): |
| 50 |
sock = socket.socket() |
| 51 |
sock.bind(("", 0)) |
| 52 |
ports.append(sock.getsockname()[1]) |
| 53 |
sockets.append(sock) |
| 54 |
for sock in sockets: |
| 55 |
sock.close() |
| 56 |
return ports |
| 57 |
|
| 58 |
|
| 59 |
# ----------------------------------------------------------------------------- |
| 60 |
# Check for passwordless login |
| 61 |
# ----------------------------------------------------------------------------- |
| 62 |
_password_pat = re.compile((rb"pass(word|phrase):"), re.IGNORECASE) |
| 63 |
|
| 64 |
|
| 65 |
def try_passwordless_ssh(server: str, keyfile: str | None, paramiko: Any = None) -> Any: |
| 66 |
"""Attempt to make an ssh connection without a password. |
| 67 |
This is mainly used for requiring password input only once |
| 68 |
when many tunnels may be connected to the same server. |
| 69 |
|
| 70 |
If paramiko is None, the default for the platform is chosen. |
| 71 |
""" |
| 72 |
if paramiko is None: |
| 73 |
paramiko = sys.platform == "win32" |
| 74 |
f = _try_passwordless_paramiko if paramiko else _try_passwordless_openssh |
| 75 |
return f(server, keyfile) |
| 76 |
|
| 77 |
|
| 78 |
def _try_passwordless_openssh(server: str, keyfile: str | None) -> bool: |
| 79 |
"""Try passwordless login with shell ssh command.""" |
| 80 |
if pexpect is None: |
| 81 |
msg = "pexpect unavailable, use paramiko" |
| 82 |
raise ImportError(msg) |
| 83 |
cmd = "ssh -f " + server |
| 84 |
if keyfile: |
| 85 |
cmd += " -i " + keyfile |
| 86 |
cmd += " exit" |
| 87 |
|
| 88 |
# pop SSH_ASKPASS from env |
| 89 |
env = os.environ.copy() |
| 90 |
env.pop("SSH_ASKPASS", None) |
| 91 |
|
| 92 |
ssh_newkey = "Are you sure you want to continue connecting" |
| 93 |
p = pexpect.spawn(cmd, env=env) |
| 94 |
while True: |
| 95 |
try: |
| 96 |
i = p.expect([ssh_newkey, _password_pat], timeout=0.1) |
| 97 |
if i == 0: |
| 98 |
msg = "The authenticity of the host can't be established." |
| 99 |
raise SSHException(msg) |
| 100 |
except pexpect.TIMEOUT: |
| 101 |
continue |
| 102 |
except pexpect.EOF: |
| 103 |
return True |
| 104 |
else: |
| 105 |
return False |
| 106 |
|
| 107 |
|
| 108 |
def _try_passwordless_paramiko(server: str, keyfile: str | None) -> bool: |
| 109 |
"""Try passwordless login with paramiko.""" |
| 110 |
if paramiko is None: |
| 111 |
msg = "Paramiko unavailable, " # type:ignore[unreachable] |
| 112 |
if sys.platform == "win32": |
| 113 |
msg += "Paramiko is required for ssh tunneled connections on Windows." |
| 114 |
else: |
| 115 |
msg += "use OpenSSH." |
| 116 |
raise ImportError(msg) |
| 117 |
username, server, port = _split_server(server) |
| 118 |
client = paramiko.SSHClient() |
| 119 |
client.load_system_host_keys() |
| 120 |
client.set_missing_host_key_policy(paramiko.WarningPolicy()) |
| 121 |
try: |
| 122 |
client.connect(server, port, username=username, key_filename=keyfile, look_for_keys=True) |
| 123 |
except paramiko.AuthenticationException: |
| 124 |
return False |
| 125 |
else: |
| 126 |
client.close() |
| 127 |
return True |
| 128 |
|
| 129 |
|
| 130 |
def tunnel_connection( |
| 131 |
socket: socket.socket, |
| 132 |
addr: str, |
| 133 |
server: str, |
| 134 |
keyfile: str | None = None, |
| 135 |
password: str | None = None, |
| 136 |
paramiko: Any = None, |
| 137 |
timeout: int = 60, |
| 138 |
) -> int: |
| 139 |
"""Connect a socket to an address via an ssh tunnel. |
| 140 |
|
| 141 |
This is a wrapper for socket.connect(addr), when addr is not accessible |
| 142 |
from the local machine. It simply creates an ssh tunnel using the remaining args, |
| 143 |
and calls socket.connect('tcp://localhost:lport') where lport is the randomly |
| 144 |
selected local port of the tunnel. |
| 145 |
|
| 146 |
""" |
| 147 |
new_url, tunnel = open_tunnel( |
| 148 |
addr, |
| 149 |
server, |
| 150 |
keyfile=keyfile, |
| 151 |
password=password, |
| 152 |
paramiko=paramiko, |
| 153 |
timeout=timeout, |
| 154 |
) |
| 155 |
socket.connect(new_url) |
| 156 |
return tunnel |
| 157 |
|
| 158 |
|
| 159 |
def open_tunnel( |
| 160 |
addr: str, |
| 161 |
server: str, |
| 162 |
keyfile: str | None = None, |
| 163 |
password: str | None = None, |
| 164 |
paramiko: Any = None, |
| 165 |
timeout: int = 60, |
| 166 |
) -> tuple[str, int]: |
| 167 |
"""Open a tunneled connection from a 0MQ url. |
| 168 |
|
| 169 |
For use inside tunnel_connection. |
| 170 |
|
| 171 |
Returns |
| 172 |
------- |
| 173 |
|
| 174 |
(url, tunnel) : (str, object) |
| 175 |
The 0MQ url that has been forwarded, and the tunnel object |
| 176 |
""" |
| 177 |
|
| 178 |
lport = select_random_ports(1)[0] |
| 179 |
_, addr = addr.split("://") |
| 180 |
ip, rport = addr.split(":") |
| 181 |
rport_int = int(rport) |
| 182 |
paramiko = sys.platform == "win32" if paramiko is None else paramiko_tunnel |
| 183 |
tunnelf = paramiko_tunnel if paramiko else openssh_tunnel |
| 184 |
|
| 185 |
tunnel = tunnelf( |
| 186 |
lport, |
| 187 |
rport_int, |
| 188 |
server, |
| 189 |
remoteip=ip, |
| 190 |
keyfile=keyfile, |
| 191 |
password=password, |
| 192 |
timeout=timeout, |
| 193 |
) |
| 194 |
return "tcp://127.0.0.1:%i" % lport, cast(int, tunnel) |
| 195 |
|
| 196 |
|
| 197 |
def openssh_tunnel( |
| 198 |
lport: int, |
| 199 |
rport: int, |
| 200 |
server: str, |
| 201 |
remoteip: str = "127.0.0.1", |
| 202 |
keyfile: str | None = None, |
| 203 |
password: str | None | bool = None, |
| 204 |
timeout: int = 60, |
| 205 |
) -> int: |
| 206 |
"""Create an ssh tunnel using command-line ssh that connects port lport |
| 207 |
on this machine to localhost:rport on server. The tunnel |
| 208 |
will automatically close when not in use, remaining open |
| 209 |
for a minimum of timeout seconds for an initial connection. |
| 210 |
|
| 211 |
This creates a tunnel redirecting `localhost:lport` to `remoteip:rport`, |
| 212 |
as seen from `server`. |
| 213 |
|
| 214 |
keyfile and password may be specified, but ssh config is checked for defaults. |
| 215 |
|
| 216 |
Parameters |
| 217 |
---------- |
| 218 |
|
| 219 |
lport : int |
| 220 |
local port for connecting to the tunnel from this machine. |
| 221 |
rport : int |
| 222 |
port on the remote machine to connect to. |
| 223 |
server : str |
| 224 |
The ssh server to connect to. The full ssh server string will be parsed. |
| 225 |
user@server:port |
| 226 |
remoteip : str [Default: 127.0.0.1] |
| 227 |
The remote ip, specifying the destination of the tunnel. |
| 228 |
Default is localhost, which means that the tunnel would redirect |
| 229 |
localhost:lport on this machine to localhost:rport on the *server*. |
| 230 |
|
| 231 |
keyfile : str; path to public key file |
| 232 |
This specifies a key to be used in ssh login, default None. |
| 233 |
Regular default ssh keys will be used without specifying this argument. |
| 234 |
password : str; |
| 235 |
Your ssh password to the ssh server. Note that if this is left None, |
| 236 |
you will be prompted for it if passwordless key based login is unavailable. |
| 237 |
timeout : int [default: 60] |
| 238 |
The time (in seconds) after which no activity will result in the tunnel |
| 239 |
closing. This prevents orphaned tunnels from running forever. |
| 240 |
""" |
| 241 |
if pexpect is None: |
| 242 |
msg = "pexpect unavailable, use paramiko_tunnel" |
| 243 |
raise ImportError(msg) |
| 244 |
ssh = "ssh " |
| 245 |
if keyfile: |
| 246 |
ssh += "-i " + keyfile |
| 247 |
|
| 248 |
if ":" in server: |
| 249 |
server, port = server.split(":") |
| 250 |
ssh += " -p %s" % port |
| 251 |
|
| 252 |
cmd = f"{ssh} -O check {server}" |
| 253 |
(output, exitstatus) = pexpect.run(cmd, withexitstatus=True) |
| 254 |
if not exitstatus: |
| 255 |
pid = int(output[output.find(b"(pid=") + 5 : output.find(b")")]) |
| 256 |
cmd = "%s -O forward -L 127.0.0.1:%i:%s:%i %s" % ( |
| 257 |
ssh, |
| 258 |
lport, |
| 259 |
remoteip, |
| 260 |
rport, |
| 261 |
server, |
| 262 |
) |
| 263 |
(output, exitstatus) = pexpect.run(cmd, withexitstatus=True) |
| 264 |
if not exitstatus: |
| 265 |
atexit.register(_stop_tunnel, cmd.replace("-O forward", "-O cancel", 1)) |
| 266 |
return pid |
| 267 |
cmd = "%s -f -S none -L 127.0.0.1:%i:%s:%i %s sleep %i" % ( |
| 268 |
ssh, |
| 269 |
lport, |
| 270 |
remoteip, |
| 271 |
rport, |
| 272 |
server, |
| 273 |
timeout, |
| 274 |
) |
| 275 |
|
| 276 |
# pop SSH_ASKPASS from env |
| 277 |
env = os.environ.copy() |
| 278 |
env.pop("SSH_ASKPASS", None) |
| 279 |
|
| 280 |
ssh_newkey = "Are you sure you want to continue connecting" |
| 281 |
tunnel = pexpect.spawn(cmd, env=env) |
| 282 |
failed = False |
| 283 |
while True: |
| 284 |
try: |
| 285 |
i = tunnel.expect([ssh_newkey, _password_pat], timeout=0.1) |
| 286 |
if i == 0: |
| 287 |
msg = "The authenticity of the host can't be established." |
| 288 |
raise SSHException(msg) |
| 289 |
except pexpect.TIMEOUT: |
| 290 |
continue |
| 291 |
except pexpect.EOF as e: |
| 292 |
tunnel.wait() |
| 293 |
if tunnel.exitstatus: |
| 294 |
raise RuntimeError("tunnel '%s' failed to start" % (cmd)) from e |
| 295 |
else: |
| 296 |
return tunnel.pid |
| 297 |
else: |
| 298 |
if failed: |
| 299 |
warnings.warn("Password rejected, try again", stacklevel=2) |
| 300 |
password = None |
| 301 |
if password is None: |
| 302 |
password = getpass("%s's password: " % (server)) |
| 303 |
tunnel.sendline(password) |
| 304 |
failed = True |
| 305 |
|
| 306 |
|
| 307 |
def _stop_tunnel(cmd: Any) -> None: |
| 308 |
assert pexpect is not None |
| 309 |
pexpect.run(cmd) |
| 310 |
|
| 311 |
|
| 312 |
def _split_server(server: str) -> tuple[str, str, int]: |
| 313 |
if "@" in server: |
| 314 |
username, server = server.split("@", 1) |
| 315 |
else: |
| 316 |
username = getuser() |
| 317 |
if ":" in server: |
| 318 |
server, port_str = server.split(":") |
| 319 |
port = int(port_str) |
| 320 |
else: |
| 321 |
port = 22 |
| 322 |
return username, server, port |
| 323 |
|
| 324 |
|
| 325 |
def paramiko_tunnel( |
| 326 |
lport: int, |
| 327 |
rport: int, |
| 328 |
server: str, |
| 329 |
remoteip: str = "127.0.0.1", |
| 330 |
keyfile: str | None = None, |
| 331 |
password: str | None = None, |
| 332 |
timeout: float = 60, |
| 333 |
) -> Process: |
| 334 |
"""launch a tunner with paramiko in a subprocess. This should only be used |
| 335 |
when shell ssh is unavailable (e.g. Windows). |
| 336 |
|
| 337 |
This creates a tunnel redirecting `localhost:lport` to `remoteip:rport`, |
| 338 |
as seen from `server`. |
| 339 |
|
| 340 |
If you are familiar with ssh tunnels, this creates the tunnel: |
| 341 |
|
| 342 |
ssh server -L localhost:lport:remoteip:rport |
| 343 |
|
| 344 |
keyfile and password may be specified, but ssh config is checked for defaults. |
| 345 |
|
| 346 |
|
| 347 |
Parameters |
| 348 |
---------- |
| 349 |
|
| 350 |
lport : int |
| 351 |
local port for connecting to the tunnel from this machine. |
| 352 |
rport : int |
| 353 |
port on the remote machine to connect to. |
| 354 |
server : str |
| 355 |
The ssh server to connect to. The full ssh server string will be parsed. |
| 356 |
user@server:port |
| 357 |
remoteip : str [Default: 127.0.0.1] |
| 358 |
The remote ip, specifying the destination of the tunnel. |
| 359 |
Default is localhost, which means that the tunnel would redirect |
| 360 |
localhost:lport on this machine to localhost:rport on the *server*. |
| 361 |
|
| 362 |
keyfile : str; path to public key file |
| 363 |
This specifies a key to be used in ssh login, default None. |
| 364 |
Regular default ssh keys will be used without specifying this argument. |
| 365 |
password : str; |
| 366 |
Your ssh password to the ssh server. Note that if this is left None, |
| 367 |
you will be prompted for it if passwordless key based login is unavailable. |
| 368 |
timeout : int [default: 60] |
| 369 |
The time (in seconds) after which no activity will result in the tunnel |
| 370 |
closing. This prevents orphaned tunnels from running forever. |
| 371 |
|
| 372 |
""" |
| 373 |
if paramiko is None: |
| 374 |
msg = "Paramiko not available" # type:ignore[unreachable] |
| 375 |
raise ImportError(msg) |
| 376 |
|
| 377 |
if password is None and not _try_passwordless_paramiko(server, keyfile): |
| 378 |
password = getpass("%s's password: " % (server)) |
| 379 |
|
| 380 |
p = Process( |
| 381 |
target=_paramiko_tunnel, |
| 382 |
args=(lport, rport, server, remoteip), |
| 383 |
kwargs={"keyfile": keyfile, "password": password}, |
| 384 |
) |
| 385 |
p.daemon = True |
| 386 |
p.start() |
| 387 |
return p |
| 388 |
|
| 389 |
|
| 390 |
def _paramiko_tunnel( |
| 391 |
lport: int, |
| 392 |
rport: int, |
| 393 |
server: str, |
| 394 |
remoteip: str, |
| 395 |
keyfile: str | None = None, |
| 396 |
password: str | None = None, |
| 397 |
) -> None: |
| 398 |
"""Function for actually starting a paramiko tunnel, to be passed |
| 399 |
to multiprocessing.Process(target=this), and not called directly. |
| 400 |
""" |
| 401 |
username, server, port = _split_server(server) |
| 402 |
client = paramiko.SSHClient() |
| 403 |
client.load_system_host_keys() |
| 404 |
client.set_missing_host_key_policy(paramiko.WarningPolicy()) |
| 405 |
|
| 406 |
try: |
| 407 |
client.connect( |
| 408 |
server, |
| 409 |
port, |
| 410 |
username=username, |
| 411 |
key_filename=keyfile, |
| 412 |
look_for_keys=True, |
| 413 |
password=password, |
| 414 |
) |
| 415 |
# except paramiko.AuthenticationException: |
| 416 |
# if password is None: |
| 417 |
# password = getpass("%s@%s's password: "%(username, server)) |
| 418 |
# client.connect(server, port, username=username, password=password) |
| 419 |
# else: |
| 420 |
# raise |
| 421 |
except Exception as e: |
| 422 |
warnings.warn("*** Failed to connect to %s:%d: %r" % (server, port, e), stacklevel=2) |
| 423 |
sys.exit(1) |
| 424 |
|
| 425 |
# Don't let SIGINT kill the tunnel subprocess |
| 426 |
signal.signal(signal.SIGINT, signal.SIG_IGN) |
| 427 |
|
| 428 |
try: |
| 429 |
forward_tunnel(lport, remoteip, rport, client.get_transport()) |
| 430 |
except KeyboardInterrupt: |
| 431 |
warnings.warn("SIGINT: Port forwarding stopped cleanly", stacklevel=2) |
| 432 |
sys.exit(0) |
| 433 |
except Exception as e: |
| 434 |
warnings.warn("Port forwarding stopped uncleanly: %s" % e, stacklevel=2) |
| 435 |
sys.exit(255) |
| 436 |
|
| 437 |
|
| 438 |
if sys.platform == "win32": |
| 439 |
ssh_tunnel = paramiko_tunnel |
| 440 |
else: |
| 441 |
ssh_tunnel = openssh_tunnel |
| 442 |
|
| 443 |
|
| 444 |
__all__ = [ |
| 445 |
"openssh_tunnel", |
| 446 |
"paramiko_tunnel", |
| 447 |
"ssh_tunnel", |
| 448 |
"try_passwordless_ssh", |
| 449 |
"tunnel_connection", |
| 450 |
] |