PageRenderTime 66ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/paramiko/transport.py

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