tunnel.py 13 KB

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