PageRenderTime 65ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/contrib/paramiko/paramiko/transport.py

https://gitlab.com/Smileyt/KomodoEdit
Python | 1195 lines | 1132 code | 24 blank | 39 comment | 19 complexity | 72b3315697d971f6c15ada14d7e6bea8 MD5 | raw file
  1. # Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com>
  2. #
  3. # This file is part of paramiko.
  4. #
  5. # Paramiko is free software; you can redistribute it and/or modify it under the
  6. # terms of the GNU Lesser General Public License as published by the Free
  7. # Software Foundation; either version 2.1 of the License, or (at your option)
  8. # any later version.
  9. #
  10. # Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY
  11. # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  13. # details.
  14. #
  15. # You should have received a copy of the GNU Lesser General Public License
  16. # along with Paramiko; if not, write to the Free Software Foundation, Inc.,
  17. # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
  18. """
  19. Core protocol implementation
  20. """
  21. import os
  22. import socket
  23. import sys
  24. import threading
  25. import time
  26. import weakref
  27. from hashlib import md5, sha1
  28. import paramiko
  29. from paramiko import util
  30. from paramiko.auth_handler import AuthHandler
  31. from paramiko.ssh_gss import GSSAuth
  32. from paramiko.channel import Channel
  33. from paramiko.common import xffffffff, cMSG_CHANNEL_OPEN, cMSG_IGNORE, \
  34. cMSG_GLOBAL_REQUEST, DEBUG, MSG_KEXINIT, MSG_IGNORE, MSG_DISCONNECT, \
  35. MSG_DEBUG, ERROR, WARNING, cMSG_UNIMPLEMENTED, INFO, cMSG_KEXINIT, \
  36. cMSG_NEWKEYS, MSG_NEWKEYS, cMSG_REQUEST_SUCCESS, cMSG_REQUEST_FAILURE, \
  37. CONNECTION_FAILED_CODE, OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED, \
  38. OPEN_SUCCEEDED, cMSG_CHANNEL_OPEN_FAILURE, cMSG_CHANNEL_OPEN_SUCCESS, \
  39. MSG_GLOBAL_REQUEST, MSG_REQUEST_SUCCESS, MSG_REQUEST_FAILURE, \
  40. MSG_CHANNEL_OPEN_SUCCESS, MSG_CHANNEL_OPEN_FAILURE, MSG_CHANNEL_OPEN, \
  41. MSG_CHANNEL_SUCCESS, MSG_CHANNEL_FAILURE, MSG_CHANNEL_DATA, \
  42. MSG_CHANNEL_EXTENDED_DATA, MSG_CHANNEL_WINDOW_ADJUST, MSG_CHANNEL_REQUEST, \
  43. MSG_CHANNEL_EOF, MSG_CHANNEL_CLOSE, MIN_PACKET_SIZE, MAX_WINDOW_SIZE, \
  44. DEFAULT_WINDOW_SIZE, DEFAULT_MAX_PACKET_SIZE
  45. from paramiko.compress import ZlibCompressor, ZlibDecompressor
  46. from paramiko.dsskey import DSSKey
  47. from paramiko.kex_gex import KexGex
  48. from paramiko.kex_group1 import KexGroup1
  49. from paramiko.kex_group14 import KexGroup14
  50. from paramiko.kex_gss import KexGSSGex, KexGSSGroup1, KexGSSGroup14, NullHostKey
  51. from paramiko.message import Message
  52. from paramiko.packet import Packetizer, NeedRekeyException
  53. from paramiko.primes import ModulusPack
  54. from paramiko.py3compat import string_types, long, byte_ord, b
  55. from paramiko.rsakey import RSAKey
  56. from paramiko.ecdsakey import ECDSAKey
  57. from paramiko.server import ServerInterface
  58. from paramiko.sftp_client import SFTPClient
  59. from paramiko.ssh_exception import (SSHException, BadAuthenticationType,
  60. ChannelException, ProxyCommandFailure)
  61. from paramiko.util import retry_on_signal, ClosingContextManager, clamp_value
  62. from Crypto.Cipher import Blowfish, AES, DES3, ARC4
  63. try:
  64. from Crypto.Util import Counter
  65. except ImportError:
  66. from paramiko.util import Counter
  67. # for thread cleanup
  68. _active_threads = []
  69. def _join_lingering_threads():
  70. for thr in _active_threads:
  71. thr.stop_thread()
  72. import atexit
  73. atexit.register(_join_lingering_threads)
  74. class Transport (threading.Thread, ClosingContextManager):
  75. """
  76. An SSH Transport attaches to a stream (usually a socket), negotiates an
  77. encrypted session, authenticates, and then creates stream tunnels, called
  78. `channels <.Channel>`, across the session. Multiple channels can be
  79. multiplexed across a single session (and often are, in the case of port
  80. forwardings).
  81. Instances of this class may be used as context managers.
  82. """
  83. _PROTO_ID = '2.0'
  84. _CLIENT_ID = 'paramiko_%s' % paramiko.__version__
  85. _preferred_ciphers = ('aes128-ctr', 'aes256-ctr', 'aes128-cbc', 'blowfish-cbc',
  86. 'aes256-cbc', '3des-cbc', 'arcfour128', 'arcfour256')
  87. _preferred_macs = ('hmac-sha1', 'hmac-md5', 'hmac-sha1-96', 'hmac-md5-96')
  88. _preferred_keys = ('ssh-rsa', 'ssh-dss', 'ecdsa-sha2-nistp256')
  89. _preferred_kex = ( 'diffie-hellman-group14-sha1', 'diffie-hellman-group-exchange-sha1' , 'diffie-hellman-group1-sha1')
  90. _preferred_compression = ('none',)
  91. _cipher_info = {
  92. 'aes128-ctr': {'class': AES, 'mode': AES.MODE_CTR, 'block-size': 16, 'key-size': 16},
  93. 'aes256-ctr': {'class': AES, 'mode': AES.MODE_CTR, 'block-size': 16, 'key-size': 32},
  94. 'blowfish-cbc': {'class': Blowfish, 'mode': Blowfish.MODE_CBC, 'block-size': 8, 'key-size': 16},
  95. 'aes128-cbc': {'class': AES, 'mode': AES.MODE_CBC, 'block-size': 16, 'key-size': 16},
  96. 'aes256-cbc': {'class': AES, 'mode': AES.MODE_CBC, 'block-size': 16, 'key-size': 32},
  97. '3des-cbc': {'class': DES3, 'mode': DES3.MODE_CBC, 'block-size': 8, 'key-size': 24},
  98. 'arcfour128': {'class': ARC4, 'mode': None, 'block-size': 8, 'key-size': 16},
  99. 'arcfour256': {'class': ARC4, 'mode': None, 'block-size': 8, 'key-size': 32},
  100. }
  101. _mac_info = {
  102. 'hmac-sha1': {'class': sha1, 'size': 20},
  103. 'hmac-sha1-96': {'class': sha1, 'size': 12},
  104. 'hmac-md5': {'class': md5, 'size': 16},
  105. 'hmac-md5-96': {'class': md5, 'size': 12},
  106. }
  107. _key_info = {
  108. 'ssh-rsa': RSAKey,
  109. 'ssh-dss': DSSKey,
  110. 'ecdsa-sha2-nistp256': ECDSAKey,
  111. }
  112. _kex_info = {
  113. 'diffie-hellman-group1-sha1': KexGroup1,
  114. 'diffie-hellman-group14-sha1': KexGroup14,
  115. 'diffie-hellman-group-exchange-sha1': KexGex,
  116. 'gss-group1-sha1-toWM5Slw5Ew8Mqkay+al2g==': KexGSSGroup1,
  117. 'gss-group14-sha1-toWM5Slw5Ew8Mqkay+al2g==': KexGSSGroup14,
  118. 'gss-gex-sha1-toWM5Slw5Ew8Mqkay+al2g==': KexGSSGex
  119. }
  120. _compression_info = {
  121. # zlib@openssh.com is just zlib, but only turned on after a successful
  122. # authentication. openssh servers may only offer this type because
  123. # they've had troubles with security holes in zlib in the past.
  124. 'zlib@openssh.com': (ZlibCompressor, ZlibDecompressor),
  125. 'zlib': (ZlibCompressor, ZlibDecompressor),
  126. 'none': (None, None),
  127. }
  128. _modulus_pack = None
  129. def __init__(self,
  130. sock,
  131. default_window_size=DEFAULT_WINDOW_SIZE,
  132. default_max_packet_size=DEFAULT_MAX_PACKET_SIZE,
  133. gss_kex=False,
  134. gss_deleg_creds=True):
  135. """
  136. Create a new SSH session over an existing socket, or socket-like
  137. object. This only creates the `.Transport` object; it doesn't begin the
  138. SSH session yet. Use `connect` or `start_client` to begin a client
  139. session, or `start_server` to begin a server session.
  140. If the object is not actually a socket, it must have the following
  141. methods:
  142. - ``send(str)``: Writes from 1 to ``len(str)`` bytes, and returns an
  143. int representing the number of bytes written. Returns
  144. 0 or raises ``EOFError`` if the stream has been closed.
  145. - ``recv(int)``: Reads from 1 to ``int`` bytes and returns them as a
  146. string. Returns 0 or raises ``EOFError`` if the stream has been
  147. closed.
  148. - ``close()``: Closes the socket.
  149. - ``settimeout(n)``: Sets a (float) timeout on I/O operations.
  150. For ease of use, you may also pass in an address (as a tuple) or a host
  151. string as the ``sock`` argument. (A host string is a hostname with an
  152. optional port (separated by ``":"``) which will be converted into a
  153. tuple of ``(hostname, port)``.) A socket will be connected to this
  154. address and used for communication. Exceptions from the ``socket``
  155. call may be thrown in this case.
  156. .. note::
  157. Modifying the the window and packet sizes might have adverse
  158. effects on your channels created from this transport. The default
  159. values are the same as in the OpenSSH code base and have been
  160. battle tested.
  161. :param socket sock:
  162. a socket or socket-like object to create the session over.
  163. :param int default_window_size:
  164. sets the default window size on the transport. (defaults to
  165. 2097152)
  166. :param int default_max_packet_size:
  167. sets the default max packet size on the transport. (defaults to
  168. 32768)
  169. .. versionchanged:: 1.15
  170. Added the ``default_window_size`` and ``default_max_packet_size``
  171. arguments.
  172. """
  173. self.active = False
  174. if isinstance(sock, string_types):
  175. # convert "host:port" into (host, port)
  176. hl = sock.split(':', 1)
  177. if len(hl) == 1:
  178. sock = (hl[0], 22)
  179. else:
  180. sock = (hl[0], int(hl[1]))
  181. if type(sock) is tuple:
  182. # connect to the given (host, port)
  183. hostname, port = sock
  184. reason = 'No suitable address family'
  185. for (family, socktype, proto, canonname, sockaddr) in socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM):
  186. if socktype == socket.SOCK_STREAM:
  187. af = family
  188. addr = sockaddr
  189. sock = socket.socket(af, socket.SOCK_STREAM)
  190. try:
  191. retry_on_signal(lambda: sock.connect((hostname, port)))
  192. except socket.error as e:
  193. reason = str(e)
  194. else:
  195. break
  196. else:
  197. raise SSHException(
  198. 'Unable to connect to %s: %s' % (hostname, reason))
  199. # okay, normal socket-ish flow here...
  200. threading.Thread.__init__(self)
  201. self.setDaemon(True)
  202. self.sock = sock
  203. # Python < 2.3 doesn't have the settimeout method - RogerB
  204. try:
  205. # we set the timeout so we can check self.active periodically to
  206. # see if we should bail. socket.timeout exception is never
  207. # propagated.
  208. self.sock.settimeout(0.1)
  209. except AttributeError:
  210. pass
  211. # negotiated crypto parameters
  212. self.packetizer = Packetizer(sock)
  213. self.local_version = 'SSH-' + self._PROTO_ID + '-' + self._CLIENT_ID
  214. self.remote_version = ''
  215. self.local_cipher = self.remote_cipher = ''
  216. self.local_kex_init = self.remote_kex_init = None
  217. self.local_mac = self.remote_mac = None
  218. self.local_compression = self.remote_compression = None
  219. self.session_id = None
  220. self.host_key_type = None
  221. self.host_key = None
  222. # GSS-API / SSPI Key Exchange
  223. self.use_gss_kex = gss_kex
  224. # This will be set to True if GSS-API Key Exchange was performed
  225. self.gss_kex_used = False
  226. self.kexgss_ctxt = None
  227. self.gss_host = None
  228. if self.use_gss_kex:
  229. self.kexgss_ctxt = GSSAuth("gssapi-keyex", gss_deleg_creds)
  230. self._preferred_kex = ('gss-gex-sha1-toWM5Slw5Ew8Mqkay+al2g==',
  231. 'gss-group14-sha1-toWM5Slw5Ew8Mqkay+al2g==',
  232. 'gss-group1-sha1-toWM5Slw5Ew8Mqkay+al2g==',
  233. 'diffie-hellman-group-exchange-sha1',
  234. 'diffie-hellman-group14-sha1',
  235. 'diffie-hellman-group1-sha1')
  236. # state used during negotiation
  237. self.kex_engine = None
  238. self.H = None
  239. self.K = None
  240. self.initial_kex_done = False
  241. self.in_kex = False
  242. self.authenticated = False
  243. self._expected_packet = tuple()
  244. self.lock = threading.Lock() # synchronization (always higher level than write_lock)
  245. # tracking open channels
  246. self._channels = ChannelMap()
  247. self.channel_events = {} # (id -> Event)
  248. self.channels_seen = {} # (id -> True)
  249. self._channel_counter = 1
  250. self.default_max_packet_size = default_max_packet_size
  251. self.default_window_size = default_window_size
  252. self._forward_agent_handler = None
  253. self._x11_handler = None
  254. self._tcp_handler = None
  255. self.saved_exception = None
  256. self.clear_to_send = threading.Event()
  257. self.clear_to_send_lock = threading.Lock()
  258. self.clear_to_send_timeout = 30.0
  259. self.log_name = 'paramiko.transport'
  260. self.logger = util.get_logger(self.log_name)
  261. self.packetizer.set_log(self.logger)
  262. self.auth_handler = None
  263. self.global_response = None # response Message from an arbitrary global request
  264. self.completion_event = None # user-defined event callbacks
  265. self.banner_timeout = 15 # how long (seconds) to wait for the SSH banner
  266. # server mode:
  267. self.server_mode = False
  268. self.server_object = None
  269. self.server_key_dict = {}
  270. self.server_accepts = []
  271. self.server_accept_cv = threading.Condition(self.lock)
  272. self.subsystem_table = {}
  273. def __repr__(self):
  274. """
  275. Returns a string representation of this object, for debugging.
  276. """
  277. out = '<paramiko.Transport at %s' % hex(long(id(self)) & xffffffff)
  278. if not self.active:
  279. out += ' (unconnected)'
  280. else:
  281. if self.local_cipher != '':
  282. out += ' (cipher %s, %d bits)' % (self.local_cipher,
  283. self._cipher_info[self.local_cipher]['key-size'] * 8)
  284. if self.is_authenticated():
  285. out += ' (active; %d open channel(s))' % len(self._channels)
  286. elif self.initial_kex_done:
  287. out += ' (connected; awaiting auth)'
  288. else:
  289. out += ' (connecting)'
  290. out += '>'
  291. return out
  292. def atfork(self):
  293. """
  294. Terminate this Transport without closing the session. On posix
  295. systems, if a Transport is open during process forking, both parent
  296. and child will share the underlying socket, but only one process can
  297. use the connection (without corrupting the session). Use this method
  298. to clean up a Transport object without disrupting the other process.
  299. .. versionadded:: 1.5.3
  300. """
  301. self.sock.close()
  302. self.close()
  303. def get_security_options(self):
  304. """
  305. Return a `.SecurityOptions` object which can be used to tweak the
  306. encryption algorithms this transport will permit (for encryption,
  307. digest/hash operations, public keys, and key exchanges) and the order
  308. of preference for them.
  309. """
  310. return SecurityOptions(self)
  311. def set_gss_host(self, gss_host):
  312. """
  313. Setter for C{gss_host} if GSS-API Key Exchange is performed.
  314. :param str gss_host: The targets name in the kerberos database
  315. Default: The name of the host to connect to
  316. :rtype: Void
  317. """
  318. # We need the FQDN to get this working with SSPI
  319. self.gss_host = socket.getfqdn(gss_host)
  320. def start_client(self, event=None):
  321. """
  322. Negotiate a new SSH2 session as a client. This is the first step after
  323. creating a new `.Transport`. A separate thread is created for protocol
  324. negotiation.
  325. If an event is passed in, this method returns immediately. When
  326. negotiation is done (successful or not), the given ``Event`` will
  327. be triggered. On failure, `is_active` will return ``False``.
  328. (Since 1.4) If ``event`` is ``None``, this method will not return until
  329. negotation is done. On success, the method returns normally.
  330. Otherwise an SSHException is raised.
  331. After a successful negotiation, you will usually want to authenticate,
  332. calling `auth_password <Transport.auth_password>` or
  333. `auth_publickey <Transport.auth_publickey>`.
  334. .. note:: `connect` is a simpler method for connecting as a client.
  335. .. note::
  336. After calling this method (or `start_server` or `connect`), you
  337. should no longer directly read from or write to the original socket
  338. object.
  339. :param .threading.Event event:
  340. an event to trigger when negotiation is complete (optional)
  341. :raises SSHException: if negotiation fails (and no ``event`` was passed
  342. in)
  343. """
  344. self.active = True
  345. if event is not None:
  346. # async, return immediately and let the app poll for completion
  347. self.completion_event = event
  348. self.start()
  349. return
  350. # synchronous, wait for a result
  351. self.completion_event = event = threading.Event()
  352. self.start()
  353. while True:
  354. event.wait(0.1)
  355. if not self.active:
  356. e = self.get_exception()
  357. if e is not None:
  358. raise e
  359. raise SSHException('Negotiation failed.')
  360. if event.isSet():
  361. break
  362. def start_server(self, event=None, server=None):
  363. """
  364. Negotiate a new SSH2 session as a server. This is the first step after
  365. creating a new `.Transport` and setting up your server host key(s). A
  366. separate thread is created for protocol negotiation.
  367. If an event is passed in, this method returns immediately. When
  368. negotiation is done (successful or not), the given ``Event`` will
  369. be triggered. On failure, `is_active` will return ``False``.
  370. (Since 1.4) If ``event`` is ``None``, this method will not return until
  371. negotation is done. On success, the method returns normally.
  372. Otherwise an SSHException is raised.
  373. After a successful negotiation, the client will need to authenticate.
  374. Override the methods `get_allowed_auths
  375. <.ServerInterface.get_allowed_auths>`, `check_auth_none
  376. <.ServerInterface.check_auth_none>`, `check_auth_password
  377. <.ServerInterface.check_auth_password>`, and `check_auth_publickey
  378. <.ServerInterface.check_auth_publickey>` in the given ``server`` object
  379. to control the authentication process.
  380. After a successful authentication, the client should request to open a
  381. channel. Override `check_channel_request
  382. <.ServerInterface.check_channel_request>` in the given ``server``
  383. object to allow channels to be opened.
  384. .. note::
  385. After calling this method (or `start_client` or `connect`), you
  386. should no longer directly read from or write to the original socket
  387. object.
  388. :param .threading.Event event:
  389. an event to trigger when negotiation is complete.
  390. :param .ServerInterface server:
  391. an object used to perform authentication and create `channels
  392. <.Channel>`
  393. :raises SSHException: if negotiation fails (and no ``event`` was passed
  394. in)
  395. """
  396. if server is None:
  397. server = ServerInterface()
  398. self.server_mode = True
  399. self.server_object = server
  400. self.active = True
  401. if event is not None:
  402. # async, return immediately and let the app poll for completion
  403. self.completion_event = event
  404. self.start()
  405. return
  406. # synchronous, wait for a result
  407. self.completion_event = event = threading.Event()
  408. self.start()
  409. while True:
  410. event.wait(0.1)
  411. if not self.active:
  412. e = self.get_exception()
  413. if e is not None:
  414. raise e
  415. raise SSHException('Negotiation failed.')
  416. if event.isSet():
  417. break
  418. def add_server_key(self, key):
  419. """
  420. Add a host key to the list of keys used for server mode. When behaving
  421. as a server, the host key is used to sign certain packets during the
  422. SSH2 negotiation, so that the client can trust that we are who we say
  423. we are. Because this is used for signing, the key must contain private
  424. key info, not just the public half. Only one key of each type (RSA or
  425. DSS) is kept.
  426. :param .PKey key:
  427. the host key to add, usually an `.RSAKey` or `.DSSKey`.
  428. """
  429. self.server_key_dict[key.get_name()] = key
  430. def get_server_key(self):
  431. """
  432. Return the active host key, in server mode. After negotiating with the
  433. client, this method will return the negotiated host key. If only one
  434. type of host key was set with `add_server_key`, that's the only key
  435. that will ever be returned. But in cases where you have set more than
  436. one type of host key (for example, an RSA key and a DSS key), the key
  437. type will be negotiated by the client, and this method will return the
  438. key of the type agreed on. If the host key has not been negotiated
  439. yet, ``None`` is returned. In client mode, the behavior is undefined.
  440. :return:
  441. host key (`.PKey`) of the type negotiated by the client, or
  442. ``None``.
  443. """
  444. try:
  445. return self.server_key_dict[self.host_key_type]
  446. except KeyError:
  447. pass
  448. return None
  449. def load_server_moduli(filename=None):
  450. """
  451. (optional)
  452. Load a file of prime moduli for use in doing group-exchange key
  453. negotiation in server mode. It's a rather obscure option and can be
  454. safely ignored.
  455. In server mode, the remote client may request "group-exchange" key
  456. negotiation, which asks the server to send a random prime number that
  457. fits certain criteria. These primes are pretty difficult to compute,
  458. so they can't be generated on demand. But many systems contain a file
  459. of suitable primes (usually named something like ``/etc/ssh/moduli``).
  460. If you call `load_server_moduli` and it returns ``True``, then this
  461. file of primes has been loaded and we will support "group-exchange" in
  462. server mode. Otherwise server mode will just claim that it doesn't
  463. support that method of key negotiation.
  464. :param str filename:
  465. optional path to the moduli file, if you happen to know that it's
  466. not in a standard location.
  467. :return:
  468. True if a moduli file was successfully loaded; False otherwise.
  469. .. note:: This has no effect when used in client mode.
  470. """
  471. Transport._modulus_pack = ModulusPack()
  472. # places to look for the openssh "moduli" file
  473. file_list = ['/etc/ssh/moduli', '/usr/local/etc/moduli']
  474. if filename is not None:
  475. file_list.insert(0, filename)
  476. for fn in file_list:
  477. try:
  478. Transport._modulus_pack.read_file(fn)
  479. return True
  480. except IOError:
  481. pass
  482. # none succeeded
  483. Transport._modulus_pack = None
  484. return False
  485. load_server_moduli = staticmethod(load_server_moduli)
  486. def close(self):
  487. """
  488. Close this session, and any open channels that are tied to it.
  489. """
  490. if not self.active:
  491. return
  492. self.stop_thread()
  493. for chan in list(self._channels.values()):
  494. chan._unlink()
  495. self.sock.close()
  496. def get_remote_server_key(self):
  497. """
  498. Return the host key of the server (in client mode).
  499. .. note::
  500. Previously this call returned a tuple of ``(key type, key
  501. string)``. You can get the same effect by calling `.PKey.get_name`
  502. for the key type, and ``str(key)`` for the key string.
  503. :raises SSHException: if no session is currently active.
  504. :return: public key (`.PKey`) of the remote server
  505. """
  506. if (not self.active) or (not self.initial_kex_done):
  507. raise SSHException('No existing session')
  508. return self.host_key
  509. def is_active(self):
  510. """
  511. Return true if this session is active (open).
  512. :return:
  513. True if the session is still active (open); False if the session is
  514. closed
  515. """
  516. return self.active
  517. def open_session(self, window_size=None, max_packet_size=None):
  518. """
  519. Request a new channel to the server, of type ``"session"``. This is
  520. just an alias for calling `open_channel` with an argument of
  521. ``"session"``.
  522. .. note:: Modifying the the window and packet sizes might have adverse
  523. effects on the session created. The default values are the same
  524. as in the OpenSSH code base and have been battle tested.
  525. :param int window_size:
  526. optional window size for this session.
  527. :param int max_packet_size:
  528. optional max packet size for this session.
  529. :return: a new `.Channel`
  530. :raises SSHException: if the request is rejected or the session ends
  531. prematurely
  532. .. versionchanged:: 1.15
  533. Added the ``window_size`` and ``max_packet_size`` arguments.
  534. """
  535. return self.open_channel('session',
  536. window_size=window_size,
  537. max_packet_size=max_packet_size)
  538. def open_x11_channel(self, src_addr=None):
  539. """
  540. Request a new channel to the client, of type ``"x11"``. This
  541. is just an alias for ``open_channel('x11', src_addr=src_addr)``.
  542. :param tuple src_addr:
  543. the source address (``(str, int)``) of the x11 server (port is the
  544. x11 port, ie. 6010)
  545. :return: a new `.Channel`
  546. :raises SSHException: if the request is rejected or the session ends
  547. prematurely
  548. """
  549. return self.open_channel('x11', src_addr=src_addr)
  550. def open_forward_agent_channel(self):
  551. """
  552. Request a new channel to the client, of type
  553. ``"auth-agent@openssh.com"``.
  554. This is just an alias for ``open_channel('auth-agent@openssh.com')``.
  555. :return: a new `.Channel`
  556. :raises SSHException:
  557. if the request is rejected or the session ends prematurely
  558. """
  559. return self.open_channel('auth-agent@openssh.com')
  560. def open_forwarded_tcpip_channel(self, src_addr, dest_addr):
  561. """
  562. Request a new channel back to the client, of type ``"forwarded-tcpip"``.
  563. This is used after a client has requested port forwarding, for sending
  564. incoming connections back to the client.
  565. :param src_addr: originator's address
  566. :param dest_addr: local (server) connected address
  567. """
  568. return self.open_channel('forwarded-tcpip', dest_addr, src_addr)
  569. def open_channel(self,
  570. kind,
  571. dest_addr=None,
  572. src_addr=None,
  573. window_size=None,
  574. max_packet_size=None):
  575. """
  576. Request a new channel to the server. `Channels <.Channel>` are
  577. socket-like objects used for the actual transfer of data across the
  578. session. You may only request a channel after negotiating encryption
  579. (using `connect` or `start_client`) and authenticating.
  580. .. note:: Modifying the the window and packet sizes might have adverse
  581. effects on the channel created. The default values are the same
  582. as in the OpenSSH code base and have been battle tested.
  583. :param str kind:
  584. the kind of channel requested (usually ``"session"``,
  585. ``"forwarded-tcpip"``, ``"direct-tcpip"``, or ``"x11"``)
  586. :param tuple dest_addr:
  587. the destination address (address + port tuple) of this port
  588. forwarding, if ``kind`` is ``"forwarded-tcpip"`` or
  589. ``"direct-tcpip"`` (ignored for other channel types)
  590. :param src_addr: the source address of this port forwarding, if
  591. ``kind`` is ``"forwarded-tcpip"``, ``"direct-tcpip"``, or ``"x11"``
  592. :param int window_size:
  593. optional window size for this session.
  594. :param int max_packet_size:
  595. optional max packet size for this session.
  596. :return: a new `.Channel` on success
  597. :raises SSHException: if the request is rejected or the session ends
  598. prematurely
  599. .. versionchanged:: 1.15
  600. Added the ``window_size`` and ``max_packet_size`` arguments.
  601. """
  602. if not self.active:
  603. raise SSHException('SSH session not active')
  604. self.lock.acquire()
  605. try:
  606. window_size = self._sanitize_window_size(window_size)
  607. max_packet_size = self._sanitize_packet_size(max_packet_size)
  608. chanid = self._next_channel()
  609. m = Message()
  610. m.add_byte(cMSG_CHANNEL_OPEN)
  611. m.add_string(kind)
  612. m.add_int(chanid)
  613. m.add_int(window_size)
  614. m.add_int(max_packet_size)
  615. if (kind == 'forwarded-tcpip') or (kind == 'direct-tcpip'):
  616. m.add_string(dest_addr[0])
  617. m.add_int(dest_addr[1])
  618. m.add_string(src_addr[0])
  619. m.add_int(src_addr[1])
  620. elif kind == 'x11':
  621. m.add_string(src_addr[0])
  622. m.add_int(src_addr[1])
  623. chan = Channel(chanid)
  624. self._channels.put(chanid, chan)
  625. self.channel_events[chanid] = event = threading.Event()
  626. self.channels_seen[chanid] = True
  627. chan._set_transport(self)
  628. chan._set_window(window_size, max_packet_size)
  629. finally:
  630. self.lock.release()
  631. self._send_user_message(m)
  632. while True:
  633. event.wait(0.1)
  634. if not self.active:
  635. e = self.get_exception()
  636. if e is None:
  637. e = SSHException('Unable to open channel.')
  638. raise e
  639. if event.isSet():
  640. break
  641. chan = self._channels.get(chanid)
  642. if chan is not None:
  643. return chan
  644. e = self.get_exception()
  645. if e is None:
  646. e = SSHException('Unable to open channel.')
  647. raise e
  648. def request_port_forward(self, address, port, handler=None):
  649. """
  650. Ask the server to forward TCP connections from a listening port on
  651. the server, across this SSH session.
  652. If a handler is given, that handler is called from a different thread
  653. whenever a forwarded connection arrives. The handler parameters are::
  654. handler(channel, (origin_addr, origin_port), (server_addr, server_port))
  655. where ``server_addr`` and ``server_port`` are the address and port that
  656. the server was listening on.
  657. If no handler is set, the default behavior is to send new incoming
  658. forwarded connections into the accept queue, to be picked up via
  659. `accept`.
  660. :param str address: the address to bind when forwarding
  661. :param int port:
  662. the port to forward, or 0 to ask the server to allocate any port
  663. :param callable handler:
  664. optional handler for incoming forwarded connections, of the form
  665. ``func(Channel, (str, int), (str, int))``.
  666. :return: the port number (`int`) allocated by the server
  667. :raises SSHException: if the server refused the TCP forward request
  668. """
  669. if not self.active:
  670. raise SSHException('SSH session not active')
  671. port = int(port)
  672. response = self.global_request('tcpip-forward', (address, port), wait=True)
  673. if response is None:
  674. raise SSHException('TCP forwarding request denied')
  675. if port == 0:
  676. port = response.get_int()
  677. if handler is None:
  678. def default_handler(channel, src_addr, dest_addr_port):
  679. #src_addr, src_port = src_addr_port
  680. #dest_addr, dest_port = dest_addr_port
  681. self._queue_incoming_channel(channel)
  682. handler = default_handler
  683. self._tcp_handler = handler
  684. return port
  685. def cancel_port_forward(self, address, port):
  686. """
  687. Ask the server to cancel a previous port-forwarding request. No more
  688. connections to the given address & port will be forwarded across this
  689. ssh connection.
  690. :param str address: the address to stop forwarding
  691. :param int port: the port to stop forwarding
  692. """
  693. if not self.active:
  694. return
  695. self._tcp_handler = None
  696. self.global_request('cancel-tcpip-forward', (address, port), wait=True)
  697. def open_sftp_client(self):
  698. """
  699. Create an SFTP client channel from an open transport. On success, an
  700. SFTP session will be opened with the remote host, and a new
  701. `.SFTPClient` object will be returned.
  702. :return:
  703. a new `.SFTPClient` referring to an sftp session (channel) across
  704. this transport
  705. """
  706. return SFTPClient.from_transport(self)
  707. def send_ignore(self, byte_count=None):
  708. """
  709. Send a junk packet across the encrypted link. This is sometimes used
  710. to add "noise" to a connection to confuse would-be attackers. It can
  711. also be used as a keep-alive for long lived connections traversing
  712. firewalls.
  713. :param int byte_count:
  714. the number of random bytes to send in the payload of the ignored
  715. packet -- defaults to a random number from 10 to 41.
  716. """
  717. m = Message()
  718. m.add_byte(cMSG_IGNORE)
  719. if byte_count is None:
  720. byte_count = (byte_ord(os.urandom(1)) % 32) + 10
  721. m.add_bytes(os.urandom(byte_count))
  722. self._send_user_message(m)
  723. def renegotiate_keys(self):
  724. """
  725. Force this session to switch to new keys. Normally this is done
  726. automatically after the session hits a certain number of packets or
  727. bytes sent or received, but this method gives you the option of forcing
  728. new keys whenever you want. Negotiating new keys causes a pause in
  729. traffic both ways as the two sides swap keys and do computations. This
  730. method returns when the session has switched to new keys.
  731. :raises SSHException: if the key renegotiation failed (which causes the
  732. session to end)
  733. """
  734. self.completion_event = threading.Event()
  735. self._send_kex_init()
  736. while True:
  737. self.completion_event.wait(0.1)
  738. if not self.active:
  739. e = self.get_exception()
  740. if e is not None:
  741. raise e
  742. raise SSHException('Negotiation failed.')
  743. if self.completion_event.isSet():
  744. break
  745. return
  746. def set_keepalive(self, interval):
  747. """
  748. Turn on/off keepalive packets (default is off). If this is set, after
  749. ``interval`` seconds without sending any data over the connection, a
  750. "keepalive" packet will be sent (and ignored by the remote host). This
  751. can be useful to keep connections alive over a NAT, for example.
  752. :param int interval:
  753. seconds to wait before sending a keepalive packet (or
  754. 0 to disable keepalives).
  755. """
  756. self.packetizer.set_keepalive(interval,
  757. lambda x=weakref.proxy(self): x.global_request('keepalive@lag.net', wait=False))
  758. def global_request(self, kind, data=None, wait=True):
  759. """
  760. Make a global request to the remote host. These are normally
  761. extensions to the SSH2 protocol.
  762. :param str kind: name of the request.
  763. :param tuple data:
  764. an optional tuple containing additional data to attach to the
  765. request.
  766. :param bool wait:
  767. ``True`` if this method should not return until a response is
  768. received; ``False`` otherwise.
  769. :return:
  770. a `.Message` containing possible additional data if the request was
  771. successful (or an empty `.Message` if ``wait`` was ``False``);
  772. ``None`` if the request was denied.
  773. """
  774. if wait:
  775. self.completion_event = threading.Event()
  776. m = Message()
  777. m.add_byte(cMSG_GLOBAL_REQUEST)
  778. m.add_string(kind)
  779. m.add_boolean(wait)
  780. if data is not None:
  781. m.add(*data)
  782. self._log(DEBUG, 'Sending global request "%s"' % kind)
  783. self._send_user_message(m)
  784. if not wait:
  785. return None
  786. while True:
  787. self.completion_event.wait(0.1)
  788. if not self.active:
  789. return None
  790. if self.completion_event.isSet():
  791. break
  792. return self.global_response
  793. def accept(self, timeout=None):
  794. """
  795. Return the next channel opened by the client over this transport, in
  796. server mode. If no channel is opened before the given timeout, ``None``
  797. is returned.
  798. :param int timeout:
  799. seconds to wait for a channel, or ``None`` to wait forever
  800. :return: a new `.Channel` opened by the client
  801. """
  802. self.lock.acquire()
  803. try:
  804. if len(self.server_accepts) > 0:
  805. chan = self.server_accepts.pop(0)
  806. else:
  807. self.server_accept_cv.wait(timeout)
  808. if len(self.server_accepts) > 0:
  809. chan = self.server_accepts.pop(0)
  810. else:
  811. # timeout
  812. chan = None
  813. finally:
  814. self.lock.release()
  815. return chan
  816. def connect(self, hostkey=None, username='', password=None, pkey=None,
  817. gss_host=None, gss_auth=False, gss_kex=False, gss_deleg_creds=True):
  818. """
  819. Negotiate an SSH2 session, and optionally verify the server's host key
  820. and authenticate using a password or private key. This is a shortcut
  821. for `start_client`, `get_remote_server_key`, and
  822. `Transport.auth_password` or `Transport.auth_publickey`. Use those
  823. methods if you want more control.
  824. You can use this method immediately after creating a Transport to
  825. negotiate encryption with a server. If it fails, an exception will be
  826. thrown. On success, the method will return cleanly, and an encrypted
  827. session exists. You may immediately call `open_channel` or
  828. `open_session` to get a `.Channel` object, which is used for data
  829. transfer.
  830. .. note::
  831. If you fail to supply a password or private key, this method may
  832. succeed, but a subsequent `open_channel` or `open_session` call may
  833. fail because you haven't authenticated yet.
  834. :param .PKey hostkey:
  835. the host key expected from the server, or ``None`` if you don't
  836. want to do host key verification.
  837. :param str username: the username to authenticate as.
  838. :param str password:
  839. a password to use for authentication, if you want to use password
  840. authentication; otherwise ``None``.
  841. :param .PKey pkey:
  842. a private key to use for authentication, if you want to use private
  843. key authentication; otherwise ``None``.
  844. :param str gss_host:
  845. The target's name in the kerberos database. Default: hostname
  846. :param bool gss_auth:
  847. ``True`` if you want to use GSS-API authentication.
  848. :param bool gss_kex:
  849. Perform GSS-API Key Exchange and user authentication.
  850. :param bool gss_deleg_creds:
  851. Whether to delegate GSS-API client credentials.
  852. :raises SSHException: if the SSH2 negotiation fails, the host key
  853. supplied by the server is incorrect, or authentication fails.
  854. """
  855. if hostkey is not None:
  856. self._preferred_keys = [hostkey.get_name()]
  857. self.start_client()
  858. # check host key if we were given one
  859. # If GSS-API Key Exchange was performed, we are not required to check
  860. # the host key.
  861. if (hostkey is not None) and not gss_kex:
  862. key = self.get_remote_server_key()
  863. if (key.get_name() != hostkey.get_name()) or (key.asbytes() != hostkey.asbytes()):
  864. self._log(DEBUG, 'Bad host key from server')
  865. self._log(DEBUG, 'Expected: %s: %s' % (hostkey.get_name(), repr(hostkey.asbytes())))
  866. self._log(DEBUG, 'Got : %s: %s' % (key.get_name(), repr(key.asbytes())))
  867. raise SSHException('Bad host key from server')
  868. self._log(DEBUG, 'Host key verified (%s)' % hostkey.get_name())
  869. if (pkey is not None) or (password is not None) or gss_auth or gss_kex:
  870. if gss_auth:
  871. self._log(DEBUG, 'Attempting GSS-API auth... (gssapi-with-mic)')
  872. self.auth_gssapi_with_mic(username, gss_host, gss_deleg_creds)
  873. elif gss_kex:
  874. self._log(DEBUG, 'Attempting GSS-API auth... (gssapi-keyex)')
  875. self.auth_gssapi_keyex(username)
  876. elif pkey is not None:
  877. self._log(DEBUG, 'Attempting public-key auth...')
  878. self.auth_publickey(username, pkey)
  879. else:
  880. self._log(DEBUG, 'Attempting password auth...')
  881. self.auth_password(username, password)
  882. return
  883. def get_exception(self):
  884. """
  885. Return any exception that happened during the last server request.
  886. This can be used to fetch more specific error information after using
  887. calls like `start_client`. The exception (if any) is cleared after
  888. this call.
  889. :return:
  890. an exception, or ``None`` if there is no stored exception.
  891. .. versionadded:: 1.1
  892. """
  893. self.lock.acquire()
  894. try:
  895. e = self.saved_exception
  896. self.saved_exception = None
  897. return e
  898. finally:
  899. self.lock.release()
  900. def set_subsystem_handler(self, name, handler, *larg, **kwarg):
  901. """
  902. Set the handler class for a subsystem in server mode. If a request
  903. for this subsystem is made on an open ssh channel later, this handler
  904. will be constructed and called -- see `.SubsystemHandler` for more
  905. detailed documentation.
  906. Any extra parameters (including keyword arguments) are saved and
  907. passed to the `.SubsystemHandler` constructor later.
  908. :param str name: name of the subsystem.
  909. :param class handler:
  910. subclass of `.SubsystemHandler` that handles this subsystem.
  911. """
  912. try:
  913. self.lock.acquire()
  914. self.subsystem_table[name] = (handler, larg, kwarg)
  915. finally:
  916. self.lock.release()
  917. def is_authenticated(self):
  918. """
  919. Return true if this session is active and authenticated.
  920. :return:
  921. True if the session is still open and has been authenticated
  922. successfully; False if authentication failed and/or the session is
  923. closed.
  924. """
  925. return self.active and (self.auth_handler is not None) and self.auth_handler.is_authenticated()
  926. def get_username(self):
  927. """
  928. Return the username this connection is authenticated for. If the
  929. session is not authenticated (or authentication failed), this method
  930. returns ``None``.
  931. :return: username that was authenticated (a `str`), or ``None``.
  932. """
  933. if not self.active or (self.auth_handler is None):
  934. return None
  935. return self.auth_handler.get_username()
  936. def get_banner(self):
  937. """
  938. Return the banner supplied by the server upon connect. If no banner is
  939. supplied, this method returns ``None``.
  940. :returns: server supplied banner (`str`), or ``None``.
  941. """
  942. if not self.active or (self.auth_handler is None):
  943. return None
  944. return self.auth_handler.banner
  945. def auth_none(self, username):
  946. """
  947. Try to authenticate to the server using no authentication at all.
  948. This will almost always fail. It may be useful for determining the
  949. list of authentication types supported by the server, by catching the
  950. `.BadAuthenticationType` exception raised.
  951. :param str username: the username to authenticate as
  952. :return:
  953. `list` of auth types permissible for the next stage of
  954. authentication (normally empty)
  955. :raises BadAuthenticationType: if "none" authentication isn't allowed
  956. by the server for this user
  957. :raises SSHException: if the authentication failed due to a network
  958. error
  959. .. versionadded:: 1.5
  960. """
  961. if (not self.active) or (not self.initial_kex_done):
  962. raise SSHException('No existing session')
  963. my_event = threading.Event()
  964. self.auth_handler = AuthHandler(self)
  965. self.auth_handler.auth_none(username, my_event)
  966. return self.auth_handler.wait_for_response(my_event)
  967. def auth_password(self, username, password, event=None, fallback=True):
  968. """
  969. Authenticate to the server using a password. The username and password
  970. are sent over an encrypted link.
  971. If an ``event`` is passed in, this method will return immediately, and
  972. the event will be triggered once authentication succeeds or fails. On
  973. success, `is_authenticated` will return ``True``. On failure, you may
  974. use `get_exception` to get more detailed error information.
  975. Since 1.1, if no event is passed, this method will block until the
  976. authentication succeeds or fails. On failure, an exception is raised.
  977. Otherwise, the method simply returns.
  978. Since 1.5, if no event is passed and ``fallback`` is ``True`` (the
  979. default), if the server doesn't support plain password authentication
  980. but does support so-called "keyboard-interactive" mode, an attempt
  981. will be made to authenticate using this interactive mode. If it fails,
  982. the normal exception will be thrown as if the attempt had never been
  983. made. This is useful for some recent Gentoo and Debian distributions,
  984. which turn off plain password authentication in a misguided belief
  985. that interactive authentication is "more secure". (It's not.)
  986. If the server requires multi-step authentication (which is very rare),
  987. this method will return a list of auth types permissible for the next
  988. step. Otherwise, in the normal case, an empty list is returned.
  989. :param str username: the username to authenticate as
  990. :param basestring password: the password to authenticate with
  991. :param .threading.Event event:
  992. an event to trigger when the authentication attempt is complete
  993. (whether it was successful or not)
  994. :param bool fallback:
  995. ``True`` if an attempt at an automated "interactive" password auth
  996. should be made if the server doesn't support normal password auth
  997. :return:
  998. `list` of auth types permissible for the next stage of
  999. authentication (normally empty)
  1000. :raises BadAuthenticationType: if password authentication isn't
  1001. allowed by the server for this user (and no event was passed in)
  1002. :raises AuthenticationException: if the authentication failed (and no
  1003. event was passed in)
  1004. :raises SSHException: if there was a network error
  1005. """
  1006. if (not self.active) or (not self.initial_kex_done):
  1007. # we should never try to send the password unless we're on a secure link
  1008. raise SSHException('No existing session')
  1009. if event is None:
  1010. my_event = threading.Event()
  1011. else:
  1012. my_event = event
  1013. self.auth_handler = AuthHandler(self)
  1014. self.auth_handler.auth_password(username, password, my_event)
  1015. if event is not None:
  1016. # caller wants to wait for event themselves
  1017. return []
  1018. try:
  1019. return self.auth_handler.wait_for_response(my_event)
  1020. except BadAuthenticationType as e:
  1021. # if password auth isn't allowed, but keyboard-interactive *is*, try to fudge it
  1022. if not fallback or ('keyboard-interactive' not in e.allowed_types):
  1023. raise
  1024. try:
  1025. def handler(title, instructions, fields):
  1026. if len(fields) > 1:
  1027. raise SSHException('Fallback authentication failed.')
  1028. if len(fields) == 0:
  1029. # for some reason, at least on os x, a 2nd request will
  1030. # be made with zero fields requested. maybe it's just
  1031. # to try to fake out automated scripting of the exact
  1032. # type we're doing here. *shrug* :)
  1033. return []
  1034. return [password]
  1035. return self.auth_interactive(username, handler)
  1036. except SSHException:
  1037. # attempt failed; just raise the original exception
  1038. raise e
  1039. def auth_publickey(self, username, key, event=None):
  1040. """
  1041. Authenticate to the server using a private key. The key is used to
  1042. sign data from the server, so it must include the private part.
  1043. If an ``event`` is passed in, this method will return immediately, and
  1044. the event will be triggered once authentication succeeds or fails. On
  1045. success, `is_authenticated` will return ``True``. On failure, you may
  1046. use `get_exception` to get more detailed error informat