PageRenderTime 88ms CodeModel.GetById 36ms RepoModel.GetById 0ms app.codeStats 1ms

/paramiko/transport.py

https://github.com/himikof/paramiko
Python | 2107 lines | 2055 code | 14 blank | 38 comment | 24 complexity | edb4404368a1d86319ec591278c80098 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 distrubuted 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. L{Transport} handles the core SSH2 protocol.
  20. """
  21. import os
  22. import socket
  23. import string
  24. import struct
  25. import sys
  26. import threading
  27. import time
  28. import weakref
  29. from paramiko import util
  30. from paramiko.auth_handler import AuthHandler
  31. from paramiko.channel import Channel
  32. from paramiko.common import *
  33. from paramiko.compress import ZlibCompressor, ZlibDecompressor
  34. from paramiko.dsskey import DSSKey
  35. from paramiko.kex_gex import KexGex
  36. from paramiko.kex_group1 import KexGroup1
  37. from paramiko.message import Message
  38. from paramiko.packet import Packetizer, NeedRekeyException
  39. from paramiko.primes import ModulusPack
  40. from paramiko.rsakey import RSAKey
  41. from paramiko.server import ServerInterface
  42. from paramiko.sftp_client import SFTPClient
  43. from paramiko.ssh_exception import SSHException, BadAuthenticationType, ChannelException
  44. # these come from PyCrypt
  45. # http://www.amk.ca/python/writing/pycrypt/
  46. # i believe this on the standards track.
  47. # PyCrypt compiled for Win32 can be downloaded from the HashTar homepage:
  48. # http://nitace.bsd.uchicago.edu:8080/hashtar
  49. from Crypto.Cipher import Blowfish, AES, DES3, ARC4
  50. from Crypto.Hash import SHA, MD5
  51. try:
  52. from Crypto.Util import Counter
  53. except ImportError:
  54. from paramiko.util import Counter
  55. # for thread cleanup
  56. _active_threads = []
  57. def _join_lingering_threads():
  58. for thr in _active_threads:
  59. thr.stop_thread()
  60. import atexit
  61. atexit.register(_join_lingering_threads)
  62. class SecurityOptions (object):
  63. """
  64. Simple object containing the security preferences of an ssh transport.
  65. These are tuples of acceptable ciphers, digests, key types, and key
  66. exchange algorithms, listed in order of preference.
  67. Changing the contents and/or order of these fields affects the underlying
  68. L{Transport} (but only if you change them before starting the session).
  69. If you try to add an algorithm that paramiko doesn't recognize,
  70. C{ValueError} will be raised. If you try to assign something besides a
  71. tuple to one of the fields, C{TypeError} will be raised.
  72. """
  73. __slots__ = [ 'ciphers', 'digests', 'key_types', 'kex', 'compression', '_transport' ]
  74. def __init__(self, transport):
  75. self._transport = transport
  76. def __repr__(self):
  77. """
  78. Returns a string representation of this object, for debugging.
  79. @rtype: str
  80. """
  81. return '<paramiko.SecurityOptions for %s>' % repr(self._transport)
  82. def _get_ciphers(self):
  83. return self._transport._preferred_ciphers
  84. def _get_digests(self):
  85. return self._transport._preferred_macs
  86. def _get_key_types(self):
  87. return self._transport._preferred_keys
  88. def _get_kex(self):
  89. return self._transport._preferred_kex
  90. def _get_compression(self):
  91. return self._transport._preferred_compression
  92. def _set(self, name, orig, x):
  93. if type(x) is list:
  94. x = tuple(x)
  95. if type(x) is not tuple:
  96. raise TypeError('expected tuple or list')
  97. possible = getattr(self._transport, orig).keys()
  98. forbidden = filter(lambda n: n not in possible, x)
  99. if len(forbidden) > 0:
  100. raise ValueError('unknown cipher')
  101. setattr(self._transport, name, x)
  102. def _set_ciphers(self, x):
  103. self._set('_preferred_ciphers', '_cipher_info', x)
  104. def _set_digests(self, x):
  105. self._set('_preferred_macs', '_mac_info', x)
  106. def _set_key_types(self, x):
  107. self._set('_preferred_keys', '_key_info', x)
  108. def _set_kex(self, x):
  109. self._set('_preferred_kex', '_kex_info', x)
  110. def _set_compression(self, x):
  111. self._set('_preferred_compression', '_compression_info', x)
  112. ciphers = property(_get_ciphers, _set_ciphers, None,
  113. "Symmetric encryption ciphers")
  114. digests = property(_get_digests, _set_digests, None,
  115. "Digest (one-way hash) algorithms")
  116. key_types = property(_get_key_types, _set_key_types, None,
  117. "Public-key algorithms")
  118. kex = property(_get_kex, _set_kex, None, "Key exchange algorithms")
  119. compression = property(_get_compression, _set_compression, None,
  120. "Compression algorithms")
  121. class ChannelMap (object):
  122. def __init__(self):
  123. # (id -> Channel)
  124. self._map = weakref.WeakValueDictionary()
  125. self._lock = threading.Lock()
  126. def put(self, chanid, chan):
  127. self._lock.acquire()
  128. try:
  129. self._map[chanid] = chan
  130. finally:
  131. self._lock.release()
  132. def get(self, chanid):
  133. self._lock.acquire()
  134. try:
  135. return self._map.get(chanid, None)
  136. finally:
  137. self._lock.release()
  138. def delete(self, chanid):
  139. self._lock.acquire()
  140. try:
  141. try:
  142. del self._map[chanid]
  143. except KeyError:
  144. pass
  145. finally:
  146. self._lock.release()
  147. def values(self):
  148. self._lock.acquire()
  149. try:
  150. return self._map.values()
  151. finally:
  152. self._lock.release()
  153. def __len__(self):
  154. self._lock.acquire()
  155. try:
  156. return len(self._map)
  157. finally:
  158. self._lock.release()
  159. class Transport (threading.Thread):
  160. """
  161. An SSH Transport attaches to a stream (usually a socket), negotiates an
  162. encrypted session, authenticates, and then creates stream tunnels, called
  163. L{Channel}s, across the session. Multiple channels can be multiplexed
  164. across a single session (and often are, in the case of port forwardings).
  165. """
  166. _PROTO_ID = '2.0'
  167. _CLIENT_ID = 'paramiko_1.7.6'
  168. _preferred_ciphers = ( 'aes128-ctr', 'aes256-ctr', 'aes128-cbc', 'blowfish-cbc', 'aes256-cbc', '3des-cbc',
  169. 'arcfour128', 'arcfour256' )
  170. _preferred_macs = ( 'hmac-sha1', 'hmac-md5', 'hmac-sha1-96', 'hmac-md5-96' )
  171. _preferred_keys = ( 'ssh-rsa', 'ssh-dss' )
  172. _preferred_kex = ( 'diffie-hellman-group1-sha1', 'diffie-hellman-group-exchange-sha1' )
  173. _preferred_compression = ( 'none', )
  174. _cipher_info = {
  175. 'aes128-ctr': { 'class': AES, 'mode': AES.MODE_CTR, 'block-size': 16, 'key-size': 16 },
  176. 'aes256-ctr': { 'class': AES, 'mode': AES.MODE_CTR, 'block-size': 16, 'key-size': 32 },
  177. 'blowfish-cbc': { 'class': Blowfish, 'mode': Blowfish.MODE_CBC, 'block-size': 8, 'key-size': 16 },
  178. 'aes128-cbc': { 'class': AES, 'mode': AES.MODE_CBC, 'block-size': 16, 'key-size': 16 },
  179. 'aes256-cbc': { 'class': AES, 'mode': AES.MODE_CBC, 'block-size': 16, 'key-size': 32 },
  180. '3des-cbc': { 'class': DES3, 'mode': DES3.MODE_CBC, 'block-size': 8, 'key-size': 24 },
  181. 'arcfour128': { 'class': ARC4, 'mode': None, 'block-size': 8, 'key-size': 16 },
  182. 'arcfour256': { 'class': ARC4, 'mode': None, 'block-size': 8, 'key-size': 32 },
  183. }
  184. _mac_info = {
  185. 'hmac-sha1': { 'class': SHA, 'size': 20 },
  186. 'hmac-sha1-96': { 'class': SHA, 'size': 12 },
  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. }
  194. _kex_info = {
  195. 'diffie-hellman-group1-sha1': KexGroup1,
  196. 'diffie-hellman-group-exchange-sha1': KexGex,
  197. }
  198. _compression_info = {
  199. # zlib@openssh.com is just zlib, but only turned on after a successful
  200. # authentication. openssh servers may only offer this type because
  201. # they've had troubles with security holes in zlib in the past.
  202. 'zlib@openssh.com': ( ZlibCompressor, ZlibDecompressor ),
  203. 'zlib': ( ZlibCompressor, ZlibDecompressor ),
  204. 'none': ( None, None ),
  205. }
  206. _modulus_pack = None
  207. def __init__(self, sock):
  208. """
  209. Create a new SSH session over an existing socket, or socket-like
  210. object. This only creates the Transport object; it doesn't begin the
  211. SSH session yet. Use L{connect} or L{start_client} to begin a client
  212. session, or L{start_server} to begin a server session.
  213. If the object is not actually a socket, it must have the following
  214. methods:
  215. - C{send(str)}: Writes from 1 to C{len(str)} bytes, and
  216. returns an int representing the number of bytes written. Returns
  217. 0 or raises C{EOFError} if the stream has been closed.
  218. - C{recv(int)}: Reads from 1 to C{int} bytes and returns them as a
  219. string. Returns 0 or raises C{EOFError} if the stream has been
  220. closed.
  221. - C{close()}: Closes the socket.
  222. - C{settimeout(n)}: Sets a (float) timeout on I/O operations.
  223. For ease of use, you may also pass in an address (as a tuple) or a host
  224. string as the C{sock} argument. (A host string is a hostname with an
  225. optional port (separated by C{":"}) which will be converted into a
  226. tuple of C{(hostname, port)}.) A socket will be connected to this
  227. address and used for communication. Exceptions from the C{socket} call
  228. may be thrown in this case.
  229. @param sock: a socket or socket-like object to create the session over.
  230. @type sock: socket
  231. """
  232. if isinstance(sock, (str, unicode)):
  233. # convert "host:port" into (host, port)
  234. hl = sock.split(':', 1)
  235. if len(hl) == 1:
  236. sock = (hl[0], 22)
  237. else:
  238. sock = (hl[0], int(hl[1]))
  239. if type(sock) is tuple:
  240. # connect to the given (host, port)
  241. hostname, port = sock
  242. reason = 'No suitable address family'
  243. for (family, socktype, proto, canonname, sockaddr) in socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM):
  244. if socktype == socket.SOCK_STREAM:
  245. af = family
  246. addr = sockaddr
  247. sock = socket.socket(af, socket.SOCK_STREAM)
  248. try:
  249. sock.connect((hostname, port))
  250. except socket.error, e:
  251. reason = str(e)
  252. else:
  253. break
  254. else:
  255. raise SSHException(
  256. 'Unable to connect to %s: %s' % (hostname, reason))
  257. # okay, normal socket-ish flow here...
  258. threading.Thread.__init__(self)
  259. self.setDaemon(True)
  260. self.rng = rng
  261. self.sock = sock
  262. # Python < 2.3 doesn't have the settimeout method - RogerB
  263. try:
  264. # we set the timeout so we can check self.active periodically to
  265. # see if we should bail. socket.timeout exception is never
  266. # propagated.
  267. self.sock.settimeout(0.1)
  268. except AttributeError:
  269. pass
  270. # negotiated crypto parameters
  271. self.packetizer = Packetizer(sock)
  272. self.local_version = 'SSH-' + self._PROTO_ID + '-' + self._CLIENT_ID
  273. self.remote_version = ''
  274. self.local_cipher = self.remote_cipher = ''
  275. self.local_kex_init = self.remote_kex_init = None
  276. self.local_mac = self.remote_mac = None
  277. self.local_compression = self.remote_compression = None
  278. self.session_id = None
  279. self.host_key_type = None
  280. self.host_key = None
  281. # state used during negotiation
  282. self.kex_engine = None
  283. self.H = None
  284. self.K = None
  285. self.active = False
  286. self.initial_kex_done = False
  287. self.in_kex = False
  288. self.authenticated = False
  289. self._expected_packet = tuple()
  290. self.lock = threading.Lock() # synchronization (always higher level than write_lock)
  291. # tracking open channels
  292. self._channels = ChannelMap()
  293. self.channel_events = { } # (id -> Event)
  294. self.channels_seen = { } # (id -> True)
  295. self._channel_counter = 1
  296. self.window_size = 65536
  297. self.max_packet_size = 34816
  298. self._x11_handler = None
  299. self._tcp_handler = None
  300. self.saved_exception = None
  301. self.clear_to_send = threading.Event()
  302. self.clear_to_send_lock = threading.Lock()
  303. self.clear_to_send_timeout = 30.0
  304. self.log_name = 'paramiko.transport'
  305. self.logger = util.get_logger(self.log_name)
  306. self.packetizer.set_log(self.logger)
  307. self.auth_handler = None
  308. self.global_response = None # response Message from an arbitrary global request
  309. self.completion_event = None # user-defined event callbacks
  310. self.banner_timeout = 15 # how long (seconds) to wait for the SSH banner
  311. # server mode:
  312. self.server_mode = False
  313. self.server_object = None
  314. self.server_key_dict = { }
  315. self.server_accepts = [ ]
  316. self.server_accept_cv = threading.Condition(self.lock)
  317. self.subsystem_table = { }
  318. def __repr__(self):
  319. """
  320. Returns a string representation of this object, for debugging.
  321. @rtype: str
  322. """
  323. out = '<paramiko.Transport at %s' % hex(long(id(self)) & 0xffffffffL)
  324. if not self.active:
  325. out += ' (unconnected)'
  326. else:
  327. if self.local_cipher != '':
  328. out += ' (cipher %s, %d bits)' % (self.local_cipher,
  329. self._cipher_info[self.local_cipher]['key-size'] * 8)
  330. if self.is_authenticated():
  331. out += ' (active; %d open channel(s))' % len(self._channels)
  332. elif self.initial_kex_done:
  333. out += ' (connected; awaiting auth)'
  334. else:
  335. out += ' (connecting)'
  336. out += '>'
  337. return out
  338. def atfork(self):
  339. """
  340. Terminate this Transport without closing the session. On posix
  341. systems, if a Transport is open during process forking, both parent
  342. and child will share the underlying socket, but only one process can
  343. use the connection (without corrupting the session). Use this method
  344. to clean up a Transport object without disrupting the other process.
  345. @since: 1.5.3
  346. """
  347. self.sock.close()
  348. self.close()
  349. def get_security_options(self):
  350. """
  351. Return a L{SecurityOptions} object which can be used to tweak the
  352. encryption algorithms this transport will permit, and the order of
  353. preference for them.
  354. @return: an object that can be used to change the preferred algorithms
  355. for encryption, digest (hash), public key, and key exchange.
  356. @rtype: L{SecurityOptions}
  357. """
  358. return SecurityOptions(self)
  359. def start_client(self, event=None):
  360. """
  361. Negotiate a new SSH2 session as a client. This is the first step after
  362. creating a new L{Transport}. A separate thread is created for protocol
  363. negotiation.
  364. If an event is passed in, this method returns immediately. When
  365. negotiation is done (successful or not), the given C{Event} will
  366. be triggered. On failure, L{is_active} will return C{False}.
  367. (Since 1.4) If C{event} is C{None}, this method will not return until
  368. negotation is done. On success, the method returns normally.
  369. Otherwise an SSHException is raised.
  370. After a successful negotiation, you will usually want to authenticate,
  371. calling L{auth_password <Transport.auth_password>} or
  372. L{auth_publickey <Transport.auth_publickey>}.
  373. @note: L{connect} is a simpler method for connecting as a client.
  374. @note: After calling this method (or L{start_server} or L{connect}),
  375. you should no longer directly read from or write to the original
  376. socket object.
  377. @param event: an event to trigger when negotiation is complete
  378. (optional)
  379. @type event: threading.Event
  380. @raise SSHException: if negotiation fails (and no C{event} was passed
  381. in)
  382. """
  383. self.active = True
  384. if event is not None:
  385. # async, return immediately and let the app poll for completion
  386. self.completion_event = event
  387. self.start()
  388. return
  389. # synchronous, wait for a result
  390. self.completion_event = event = threading.Event()
  391. self.start()
  392. while True:
  393. event.wait(0.1)
  394. if not self.active:
  395. e = self.get_exception()
  396. if e is not None:
  397. raise e
  398. raise SSHException('Negotiation failed.')
  399. if event.isSet():
  400. break
  401. def start_server(self, event=None, server=None):
  402. """
  403. Negotiate a new SSH2 session as a server. This is the first step after
  404. creating a new L{Transport} and setting up your server host key(s). A
  405. separate thread is created for protocol negotiation.
  406. If an event is passed in, this method returns immediately. When
  407. negotiation is done (successful or not), the given C{Event} will
  408. be triggered. On failure, L{is_active} will return C{False}.
  409. (Since 1.4) If C{event} is C{None}, this method will not return until
  410. negotation is done. On success, the method returns normally.
  411. Otherwise an SSHException is raised.
  412. After a successful negotiation, the client will need to authenticate.
  413. Override the methods
  414. L{get_allowed_auths <ServerInterface.get_allowed_auths>},
  415. L{check_auth_none <ServerInterface.check_auth_none>},
  416. L{check_auth_password <ServerInterface.check_auth_password>}, and
  417. L{check_auth_publickey <ServerInterface.check_auth_publickey>} in the
  418. given C{server} object to control the authentication process.
  419. After a successful authentication, the client should request to open
  420. a channel. Override
  421. L{check_channel_request <ServerInterface.check_channel_request>} in the
  422. given C{server} object to allow channels to be opened.
  423. @note: After calling this method (or L{start_client} or L{connect}),
  424. you should no longer directly read from or write to the original
  425. socket object.
  426. @param event: an event to trigger when negotiation is complete.
  427. @type event: threading.Event
  428. @param server: an object used to perform authentication and create
  429. L{Channel}s.
  430. @type server: L{server.ServerInterface}
  431. @raise SSHException: if negotiation fails (and no C{event} was passed
  432. in)
  433. """
  434. if server is None:
  435. server = ServerInterface()
  436. self.server_mode = True
  437. self.server_object = server
  438. self.active = True
  439. if event is not None:
  440. # async, return immediately and let the app poll for completion
  441. self.completion_event = event
  442. self.start()
  443. return
  444. # synchronous, wait for a result
  445. self.completion_event = event = threading.Event()
  446. self.start()
  447. while True:
  448. event.wait(0.1)
  449. if not self.active:
  450. e = self.get_exception()
  451. if e is not None:
  452. raise e
  453. raise SSHException('Negotiation failed.')
  454. if event.isSet():
  455. break
  456. def add_server_key(self, key):
  457. """
  458. Add a host key to the list of keys used for server mode. When behaving
  459. as a server, the host key is used to sign certain packets during the
  460. SSH2 negotiation, so that the client can trust that we are who we say
  461. we are. Because this is used for signing, the key must contain private
  462. key info, not just the public half. Only one key of each type (RSA or
  463. DSS) is kept.
  464. @param key: the host key to add, usually an L{RSAKey <rsakey.RSAKey>} or
  465. L{DSSKey <dsskey.DSSKey>}.
  466. @type key: L{PKey <pkey.PKey>}
  467. """
  468. self.server_key_dict[key.get_name()] = key
  469. def get_server_key(self):
  470. """
  471. Return the active host key, in server mode. After negotiating with the
  472. client, this method will return the negotiated host key. If only one
  473. type of host key was set with L{add_server_key}, that's the only key
  474. that will ever be returned. But in cases where you have set more than
  475. one type of host key (for example, an RSA key and a DSS key), the key
  476. type will be negotiated by the client, and this method will return the
  477. key of the type agreed on. If the host key has not been negotiated
  478. yet, C{None} is returned. In client mode, the behavior is undefined.
  479. @return: host key of the type negotiated by the client, or C{None}.
  480. @rtype: L{PKey <pkey.PKey>}
  481. """
  482. try:
  483. return self.server_key_dict[self.host_key_type]
  484. except KeyError:
  485. pass
  486. return None
  487. def load_server_moduli(filename=None):
  488. """
  489. I{(optional)}
  490. Load a file of prime moduli for use in doing group-exchange key
  491. negotiation in server mode. It's a rather obscure option and can be
  492. safely ignored.
  493. In server mode, the remote client may request "group-exchange" key
  494. negotiation, which asks the server to send a random prime number that
  495. fits certain criteria. These primes are pretty difficult to compute,
  496. so they can't be generated on demand. But many systems contain a file
  497. of suitable primes (usually named something like C{/etc/ssh/moduli}).
  498. If you call C{load_server_moduli} and it returns C{True}, then this
  499. file of primes has been loaded and we will support "group-exchange" in
  500. server mode. Otherwise server mode will just claim that it doesn't
  501. support that method of key negotiation.
  502. @param filename: optional path to the moduli file, if you happen to
  503. know that it's not in a standard location.
  504. @type filename: str
  505. @return: True if a moduli file was successfully loaded; False
  506. otherwise.
  507. @rtype: bool
  508. @note: This has no effect when used in client mode.
  509. """
  510. Transport._modulus_pack = ModulusPack(rng)
  511. # places to look for the openssh "moduli" file
  512. file_list = [ '/etc/ssh/moduli', '/usr/local/etc/moduli' ]
  513. if filename is not None:
  514. file_list.insert(0, filename)
  515. for fn in file_list:
  516. try:
  517. Transport._modulus_pack.read_file(fn)
  518. return True
  519. except IOError:
  520. pass
  521. # none succeeded
  522. Transport._modulus_pack = None
  523. return False
  524. load_server_moduli = staticmethod(load_server_moduli)
  525. def close(self):
  526. """
  527. Close this session, and any open channels that are tied to it.
  528. """
  529. if not self.active:
  530. return
  531. self.active = False
  532. self.packetizer.close()
  533. self.join()
  534. for chan in self._channels.values():
  535. chan._unlink()
  536. def get_remote_server_key(self):
  537. """
  538. Return the host key of the server (in client mode).
  539. @note: Previously this call returned a tuple of (key type, key string).
  540. You can get the same effect by calling
  541. L{PKey.get_name <pkey.PKey.get_name>} for the key type, and
  542. C{str(key)} for the key string.
  543. @raise SSHException: if no session is currently active.
  544. @return: public key of the remote server
  545. @rtype: L{PKey <pkey.PKey>}
  546. """
  547. if (not self.active) or (not self.initial_kex_done):
  548. raise SSHException('No existing session')
  549. return self.host_key
  550. def is_active(self):
  551. """
  552. Return true if this session is active (open).
  553. @return: True if the session is still active (open); False if the
  554. session is closed
  555. @rtype: bool
  556. """
  557. return self.active
  558. def open_session(self):
  559. """
  560. Request a new channel to the server, of type C{"session"}. This
  561. is just an alias for C{open_channel('session')}.
  562. @return: a new L{Channel}
  563. @rtype: L{Channel}
  564. @raise SSHException: if the request is rejected or the session ends
  565. prematurely
  566. """
  567. return self.open_channel('session')
  568. def open_x11_channel(self, src_addr=None):
  569. """
  570. Request a new channel to the client, of type C{"x11"}. This
  571. is just an alias for C{open_channel('x11', src_addr=src_addr)}.
  572. @param src_addr: the source address of the x11 server (port is the
  573. x11 port, ie. 6010)
  574. @type src_addr: (str, int)
  575. @return: a new L{Channel}
  576. @rtype: L{Channel}
  577. @raise SSHException: if the request is rejected or the session ends
  578. prematurely
  579. """
  580. return self.open_channel('x11', src_addr=src_addr)
  581. def open_forwarded_tcpip_channel(self, (src_addr, src_port), (dest_addr, dest_port)):
  582. """
  583. Request a new channel back to the client, of type C{"forwarded-tcpip"}.
  584. This is used after a client has requested port forwarding, for sending
  585. incoming connections back to the client.
  586. @param src_addr: originator's address
  587. @param src_port: originator's port
  588. @param dest_addr: local (server) connected address
  589. @param dest_port: local (server) connected port
  590. """
  591. return self.open_channel('forwarded-tcpip', (dest_addr, dest_port), (src_addr, src_port))
  592. def open_channel(self, kind, dest_addr=None, src_addr=None):
  593. """
  594. Request a new channel to the server. L{Channel}s are socket-like
  595. objects used for the actual transfer of data across the session.
  596. You may only request a channel after negotiating encryption (using
  597. L{connect} or L{start_client}) and authenticating.
  598. @param kind: the kind of channel requested (usually C{"session"},
  599. C{"forwarded-tcpip"}, C{"direct-tcpip"}, or C{"x11"})
  600. @type kind: str
  601. @param dest_addr: the destination address of this port forwarding,
  602. if C{kind} is C{"forwarded-tcpip"} or C{"direct-tcpip"} (ignored
  603. for other channel types)
  604. @type dest_addr: (str, int)
  605. @param src_addr: the source address of this port forwarding, if
  606. C{kind} is C{"forwarded-tcpip"}, C{"direct-tcpip"}, or C{"x11"}
  607. @type src_addr: (str, int)
  608. @return: a new L{Channel} on success
  609. @rtype: L{Channel}
  610. @raise SSHException: if the request is rejected or the session ends
  611. prematurely
  612. """
  613. if not self.active:
  614. raise SSHException('SSH session not active')
  615. self.lock.acquire()
  616. try:
  617. chanid = self._next_channel()
  618. m = Message()
  619. m.add_byte(chr(MSG_CHANNEL_OPEN))
  620. m.add_string(kind)
  621. m.add_int(chanid)
  622. m.add_int(self.window_size)
  623. m.add_int(self.max_packet_size)
  624. if (kind == 'forwarded-tcpip') or (kind == 'direct-tcpip'):
  625. m.add_string(dest_addr[0])
  626. m.add_int(dest_addr[1])
  627. m.add_string(src_addr[0])
  628. m.add_int(src_addr[1])
  629. elif kind == 'x11':
  630. m.add_string(src_addr[0])
  631. m.add_int(src_addr[1])
  632. chan = Channel(chanid)
  633. self._channels.put(chanid, chan)
  634. self.channel_events[chanid] = event = threading.Event()
  635. self.channels_seen[chanid] = True
  636. chan._set_transport(self)
  637. chan._set_window(self.window_size, self.max_packet_size)
  638. finally:
  639. self.lock.release()
  640. self._send_user_message(m)
  641. while True:
  642. event.wait(0.1);
  643. if not self.active:
  644. e = self.get_exception()
  645. if e is None:
  646. e = SSHException('Unable to open channel.')
  647. raise e
  648. if event.isSet():
  649. break
  650. chan = self._channels.get(chanid)
  651. if chan is not None:
  652. return chan
  653. e = self.get_exception()
  654. if e is None:
  655. e = SSHException('Unable to open channel.')
  656. raise e
  657. def request_port_forward(self, address, port, handler=None):
  658. """
  659. Ask the server to forward TCP connections from a listening port on
  660. the server, across this SSH session.
  661. If a handler is given, that handler is called from a different thread
  662. whenever a forwarded connection arrives. The handler parameters are::
  663. handler(channel, (origin_addr, origin_port), (server_addr, server_port))
  664. where C{server_addr} and C{server_port} are the address and port that
  665. the server was listening on.
  666. If no handler is set, the default behavior is to send new incoming
  667. forwarded connections into the accept queue, to be picked up via
  668. L{accept}.
  669. @param address: the address to bind when forwarding
  670. @type address: str
  671. @param port: the port to forward, or 0 to ask the server to allocate
  672. any port
  673. @type port: int
  674. @param handler: optional handler for incoming forwarded connections
  675. @type handler: function(Channel, (str, int), (str, int))
  676. @return: the port # allocated by the server
  677. @rtype: int
  678. @raise SSHException: if the server refused the TCP forward request
  679. """
  680. if not self.active:
  681. raise SSHException('SSH session not active')
  682. address = str(address)
  683. port = int(port)
  684. response = self.global_request('tcpip-forward', (address, port), wait=True)
  685. if response is None:
  686. raise SSHException('TCP forwarding request denied')
  687. if port == 0:
  688. port = response.get_int()
  689. if handler is None:
  690. def default_handler(channel, (src_addr, src_port), (dest_addr, dest_port)):
  691. self._queue_incoming_channel(channel)
  692. handler = default_handler
  693. self._tcp_handler = handler
  694. return port
  695. def cancel_port_forward(self, address, port):
  696. """
  697. Ask the server to cancel a previous port-forwarding request. No more
  698. connections to the given address & port will be forwarded across this
  699. ssh connection.
  700. @param address: the address to stop forwarding
  701. @type address: str
  702. @param port: the port to stop forwarding
  703. @type port: int
  704. """
  705. if not self.active:
  706. return
  707. self._tcp_handler = None
  708. self.global_request('cancel-tcpip-forward', (address, port), wait=True)
  709. def open_sftp_client(self):
  710. """
  711. Create an SFTP client channel from an open transport. On success,
  712. an SFTP session will be opened with the remote host, and a new
  713. SFTPClient object will be returned.
  714. @return: a new L{SFTPClient} object, referring to an sftp session
  715. (channel) across this transport
  716. @rtype: L{SFTPClient}
  717. """
  718. return SFTPClient.from_transport(self)
  719. def send_ignore(self, bytes=None):
  720. """
  721. Send a junk packet across the encrypted link. This is sometimes used
  722. to add "noise" to a connection to confuse would-be attackers. It can
  723. also be used as a keep-alive for long lived connections traversing
  724. firewalls.
  725. @param bytes: the number of random bytes to send in the payload of the
  726. ignored packet -- defaults to a random number from 10 to 41.
  727. @type bytes: int
  728. """
  729. m = Message()
  730. m.add_byte(chr(MSG_IGNORE))
  731. if bytes is None:
  732. bytes = (ord(rng.read(1)) % 32) + 10
  733. m.add_bytes(rng.read(bytes))
  734. self._send_user_message(m)
  735. def renegotiate_keys(self):
  736. """
  737. Force this session to switch to new keys. Normally this is done
  738. automatically after the session hits a certain number of packets or
  739. bytes sent or received, but this method gives you the option of forcing
  740. new keys whenever you want. Negotiating new keys causes a pause in
  741. traffic both ways as the two sides swap keys and do computations. This
  742. method returns when the session has switched to new keys.
  743. @raise SSHException: if the key renegotiation failed (which causes the
  744. session to end)
  745. """
  746. self.completion_event = threading.Event()
  747. self._send_kex_init()
  748. while True:
  749. self.completion_event.wait(0.1)
  750. if not self.active:
  751. e = self.get_exception()
  752. if e is not None:
  753. raise e
  754. raise SSHException('Negotiation failed.')
  755. if self.completion_event.isSet():
  756. break
  757. return
  758. def set_keepalive(self, interval):
  759. """
  760. Turn on/off keepalive packets (default is off). If this is set, after
  761. C{interval} seconds without sending any data over the connection, a
  762. "keepalive" packet will be sent (and ignored by the remote host). This
  763. can be useful to keep connections alive over a NAT, for example.
  764. @param interval: seconds to wait before sending a keepalive packet (or
  765. 0 to disable keepalives).
  766. @type interval: int
  767. """
  768. self.packetizer.set_keepalive(interval,
  769. lambda x=weakref.proxy(self): x.global_request('keepalive@lag.net', wait=False))
  770. def global_request(self, kind, data=None, wait=True):
  771. """
  772. Make a global request to the remote host. These are normally
  773. extensions to the SSH2 protocol.
  774. @param kind: name of the request.
  775. @type kind: str
  776. @param data: an optional tuple containing additional data to attach
  777. to the request.
  778. @type data: tuple
  779. @param wait: C{True} if this method should not return until a response
  780. is received; C{False} otherwise.
  781. @type wait: bool
  782. @return: a L{Message} containing possible additional data if the
  783. request was successful (or an empty L{Message} if C{wait} was
  784. C{False}); C{None} if the request was denied.
  785. @rtype: L{Message}
  786. """
  787. if wait:
  788. self.completion_event = threading.Event()
  789. m = Message()
  790. m.add_byte(chr(MSG_GLOBAL_REQUEST))
  791. m.add_string(kind)
  792. m.add_boolean(wait)
  793. if data is not None:
  794. m.add(*data)
  795. self._log(DEBUG, 'Sending global request "%s"' % kind)
  796. self._send_user_message(m)
  797. if not wait:
  798. return None
  799. while True:
  800. self.completion_event.wait(0.1)
  801. if not self.active:
  802. return None
  803. if self.completion_event.isSet():
  804. break
  805. return self.global_response
  806. def accept(self, timeout=None):
  807. """
  808. Return the next channel opened by the client over this transport, in
  809. server mode. If no channel is opened before the given timeout, C{None}
  810. is returned.
  811. @param timeout: seconds to wait for a channel, or C{None} to wait
  812. forever
  813. @type timeout: int
  814. @return: a new Channel opened by the client
  815. @rtype: L{Channel}
  816. """
  817. self.lock.acquire()
  818. try:
  819. if len(self.server_accepts) > 0:
  820. chan = self.server_accepts.pop(0)
  821. else:
  822. self.server_accept_cv.wait(timeout)
  823. if len(self.server_accepts) > 0:
  824. chan = self.server_accepts.pop(0)
  825. else:
  826. # timeout
  827. chan = None
  828. finally:
  829. self.lock.release()
  830. return chan
  831. def connect(self, hostkey=None, username='', password=None, pkey=None):
  832. """
  833. Negotiate an SSH2 session, and optionally verify the server's host key
  834. and authenticate using a password or private key. This is a shortcut
  835. for L{start_client}, L{get_remote_server_key}, and
  836. L{Transport.auth_password} or L{Transport.auth_publickey}. Use those
  837. methods if you want more control.
  838. You can use this method immediately after creating a Transport to
  839. negotiate encryption with a server. If it fails, an exception will be
  840. thrown. On success, the method will return cleanly, and an encrypted
  841. session exists. You may immediately call L{open_channel} or
  842. L{open_session} to get a L{Channel} object, which is used for data
  843. transfer.
  844. @note: If you fail to supply a password or private key, this method may
  845. succeed, but a subsequent L{open_channel} or L{open_session} call may
  846. fail because you haven't authenticated yet.
  847. @param hostkey: the host key expected from the server, or C{None} if
  848. you don't want to do host key verification.
  849. @type hostkey: L{PKey<pkey.PKey>}
  850. @param username: the username to authenticate as.
  851. @type username: str
  852. @param password: a password to use for authentication, if you want to
  853. use password authentication; otherwise C{None}.
  854. @type password: str
  855. @param pkey: a private key to use for authentication, if you want to
  856. use private key authentication; otherwise C{None}.
  857. @type pkey: L{PKey<pkey.PKey>}
  858. @raise SSHException: if the SSH2 negotiation fails, the host key
  859. supplied by the server is incorrect, or authentication fails.
  860. """
  861. if hostkey is not None:
  862. self._preferred_keys = [ hostkey.get_name() ]
  863. self.start_client()
  864. # check host key if we were given one
  865. if (hostkey is not None):
  866. key = self.get_remote_server_key()
  867. if (key.get_name() != hostkey.get_name()) or (str(key) != str(hostkey)):
  868. self._log(DEBUG, 'Bad host key from server')
  869. self._log(DEBUG, 'Expected: %s: %s' % (hostkey.get_name(), repr(str(hostkey))))
  870. self._log(DEBUG, 'Got : %s: %s' % (key.get_name(), repr(str(key))))
  871. raise SSHException('Bad host key from server')
  872. self._log(DEBUG, 'Host key verified (%s)' % hostkey.get_name())
  873. if (pkey is not None) or (password is not None):
  874. if password is not None:
  875. self._log(DEBUG, 'Attempting password auth...')
  876. self.auth_password(username, password)
  877. else:
  878. self._log(DEBUG, 'Attempting public-key auth...')
  879. self.auth_publickey(username, pkey)
  880. return
  881. def get_exception(self):
  882. """
  883. Return any exception that happened during the last server request.
  884. This can be used to fetch more specific error information after using
  885. calls like L{start_client}. The exception (if any) is cleared after
  886. this call.
  887. @return: an exception, or C{None} if there is no stored exception.
  888. @rtype: Exception
  889. @since: 1.1
  890. """
  891. self.lock.acquire()
  892. try:
  893. e = self.saved_exception
  894. self.saved_exception = None
  895. return e
  896. finally:
  897. self.lock.release()
  898. def set_subsystem_handler(self, name, handler, *larg, **kwarg):
  899. """
  900. Set the handler class for a subsystem in server mode. If a request
  901. for this subsystem is made on an open ssh channel later, this handler
  902. will be constructed and called -- see L{SubsystemHandler} for more
  903. detailed documentation. The handler class can be None, in which case
  904. the specified subsystem handler is cleared.
  905. Any extra parameters (including keyword arguments) are saved and
  906. passed to the L{SubsystemHandler} constructor later.
  907. @param name: name of the subsystem.
  908. @type name: str
  909. @param handler: subclass of L{SubsystemHandler} that handles this
  910. subsystem.
  911. @type handler: class
  912. """
  913. try:
  914. self.lock.acquire()
  915. if handler is None:
  916. del self.subsystem_table[name]
  917. else:
  918. self.subsystem_table[name] = (handler, larg, kwarg)
  919. finally:
  920. self.lock.release()
  921. def is_authenticated(self):
  922. """
  923. Return true if this session is active and authenticated.
  924. @return: True if the session is still open and has been authenticated
  925. successfully; False if authentication failed and/or the session is
  926. closed.
  927. @rtype: bool
  928. """
  929. return self.active and (self.auth_handler is not None) and self.auth_handler.is_authenticated()
  930. def get_username(self):
  931. """
  932. Return the username this connection is authenticated for. If the
  933. session is not authenticated (or authentication failed), this method
  934. returns C{None}.
  935. @return: username that was authenticated, or C{None}.
  936. @rtype: string
  937. """
  938. if not self.active or (self.auth_handler is None):
  939. return None
  940. return self.auth_handler.get_username()
  941. def auth_none(self, username):
  942. """
  943. Try to authenticate to the server using no authentication at all.
  944. This will almost always fail. It may be useful for determining the
  945. list of authentication types supported by the server, by catching the
  946. L{BadAuthenticationType} exception raised.
  947. @param username: the username to authenticate as
  948. @type username: string
  949. @return: list of auth types permissible for the next stage of
  950. authentication (normally empty)
  951. @rtype: list
  952. @raise BadAuthenticationType: if "none" authentication isn't allowed
  953. by the server for this user
  954. @raise SSHException: if the authentication failed due to a network
  955. error
  956. @since: 1.5
  957. """
  958. if (not self.active) or (not self.initial_kex_done):
  959. raise SSHException('No existing session')
  960. my_event = threading.Event()
  961. self.auth_handler = AuthHandler(self)
  962. self.auth_handler.auth_none(username, my_event)
  963. return self.auth_handler.wait_for_response(my_event)
  964. def auth_password(self, username, password, event=None, fallback=True):
  965. """
  966. Authenticate to the server using a password. The username and password
  967. are sent over an encrypted link.
  968. If an C{event} is passed in, this method will return immediately, and
  969. the event will be triggered once authentication succeeds or fails. On
  970. success, L{is_authenticated} will return C{True}. On failure, you may
  971. use L{get_exception} to get more detailed error information.
  972. Since 1.1, if no event is passed, this method will block until the
  973. authentication succeeds or fails. On failure, an exception is raised.
  974. Otherwise, the method simply returns.
  975. Since 1.5, if no event is passed and C{fallback} is C{True} (the
  976. default), if the server doesn't support plain password authentication
  977. but does support so-called "keyboard-interactive" mode, an attempt
  978. will be made to authenticate using this interactive mode. If it fails,
  979. the normal exception will be thrown as if the attempt had never been
  980. made. This is useful for some recent Gentoo and Debian distributions,
  981. which turn off plain password authentication in a misguided belief
  982. that interactive authentication is "more secure". (It's not.)
  983. If the server requires multi-step authentication (which is very rare),
  984. this method will return a list of auth types permissible for the next
  985. step. Otherwise, in the normal case, an empty list is returned.
  986. @param username: the username to authenticate as
  987. @type username: str
  988. @param password: the password to authenticate with
  989. @type password: str or unicode
  990. @param event: an event to trigger when the authentication attempt is
  991. complete (whether it was successful or not)
  992. @type event: threading.Event
  993. @param fallback: C{True} if an attempt at an automated "interactive"
  994. password auth should be made if the server doesn't support normal
  995. password auth
  996. @type fallback: bool
  997. @return: list of auth types permissible for the next stage of
  998. authentication (normally empty)
  999. @rtype: list
  1000. @raise BadAuthenticationType: if password authentication isn't
  1001. allowed by the server for this user (and no event was passed in)
  1002. @raise AuthenticationException: if the authentication failed (and no
  1003. event was passed in)
  1004. @raise 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, x:
  1021. # if password auth isn't allowed, but keyboard-interactive *is*, try to fudge it
  1022. if not fallback or ('keyboard-interactive' not in x.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, ignored:
  1037. # attempt failed; just raise the original exception
  1038. raise x
  1039. return None
  1040. def auth_publickey(self, username, key, event=None):
  1041. """
  1042. Authenticate to the server using a private key. The key is used to
  1043. sign data from the server, so it must include the private part.
  1044. If an C{event} is passed in, this method will return immediately, and
  1045. the event will be triggered once authentication succeeds or fails. On
  1046. success, L{is_authenticated} will return C{True}. On failure, you may
  1047. use L{get_exception} to get more detailed error information.
  1048. Since 1.1, if no event is passed, this method will block until the
  1049. authentication succeeds or fails. On failure, an exception is raised.
  1050. Otherwise, the method simply returns.
  1051. If the server requires multi-step authentication (which is very rare),
  1052. this method will return a list of auth types permissible for the next
  1053. step. Otherwise, in the normal case, an empty list is returned.
  1054. @param username: the username to authenticate as
  1055. @type username: string
  1056. @param key: the private key to authenticate with
  1057. @type key: L{PKey <pkey.PKey>}
  1058. @param event: an event to trigger when the authentication attempt is
  1059. complete (whether it was successful or not)
  1060. @type event: threading.Event
  1061. @return: list of auth types permissible for the next stage of
  1062. authentication (normally empty)
  1063. @rtype: list
  1064. @raise BadAuthenticationType: if public-key authentication isn't
  1065. allowed by the server for this user (and no event was passed in)
  1066. @raise AuthenticationException: if the authentication failed (and no
  1067. event was passed in)
  1068. @raise SSHException: if there was a network error
  1069. """
  1070. if (not self.active) or (not self.initial_kex_done):
  1071. # we should never try to authenticate unless we're on a secure link
  1072. raise SSHException('No existing session')
  1073. if event is None:
  1074. my_event = threading.Event()
  1075. else:
  1076. my_event = event
  1077. self.auth_handler = AuthHandler(self)
  1078. self.auth_handler.auth_publickey(username, key, my_event)
  1079. if event is not None:
  1080. # caller wants to wait for event themselves
  1081. return []
  1082. return self.auth_handler.wait_for_response(my_event)
  1083. def auth_interactive(self, username, handler, submethods=''):
  1084. """
  1085. Authenticate to the server interactively. A handler is used to answer
  1086. arbitrary questions from the server. On many servers, this is just a
  1087. dumb wrapper around PAM.
  1088. This method will block until the authentication succeeds or fails,
  1089. peroidically calling the handler asynchronously to get answers to
  1090. authentication questions. The handler may be called more than once
  1091. if the server continues to ask questions.
  1092. The handler is expected to be a callable that will handle calls of the
  1093. form: C{handler(title, instructions, prompt_list)}. The C{title} is
  1094. meant to be a dialog-window title, and the C{instructions} are user
  1095. instructions (both are strings). C{prompt_list} will be a list of
  1096. prompts, each prompt being a tuple of C{(str, bool)}. The string is
  1097. the prompt and the boolean indicates whether the user text should be
  1098. echoed.
  1099. A sample call would thus be:
  1100. C{handler('title', 'instructions', [('Password:', False)])}.
  1101. The handler should return a list or tuple of answers to the server's
  1102. questions.
  1103. If the server requires multi-step authentication (which is very rare),
  1104. this method will return a list of auth types permissible for the next
  1105. step. Otherwise, in the normal case, an empty list is returned.
  1106. @param username: the username to authenticate as
  1107. @type username: string
  1108. @param handler: a handler for responding to server questions
  1109. @type handler: callable
  1110. @param submethods: a string list of desired submethods (optional)
  1111. @type submethods: str
  1112. @return: list of auth types permissible for the next stage of
  1113. authentication (normally empty).
  1114. @rtype: list
  1115. @raise BadAuthenticationType: if public-key authentication isn't
  1116. allowed by the server for this user
  1117. @raise AuthenticationException: if the authentication failed
  1118. @raise SSHException: if there was a network error
  1119. @since: 1.5
  1120. """
  1121. if (not self.active) or (not self.initial_kex_done):
  1122. # we should never try to authenticate unless we're on a secure link
  1123. raise SSHException('No existing session')
  1124. my_event = threading.Event()
  1125. self.auth_handler = AuthHandler(self)
  1126. self.auth_handler.auth_interactive(username, handler, my_event, submethods)
  1127. return self.auth_handler.wait_for_response(my_event)
  1128. def set_log_channel(self, name):
  1129. """
  1130. Set the channel for this transport's logging. The default is
  1131. C{"paramiko.transport"} but it can be set to anything you want.
  1132. (See the C{logging} module for more info.) SSH Channels will log
  1133. to a sub-channel of the one specified.
  1134. @param name: new channel name for logging
  1135. @type name: str
  1136. @since: 1.1
  1137. """
  1138. self.log_name = name
  1139. self.logger = util.get_logger(name)
  1140. self.packetizer.set_log(self.logger)
  1141. def get_log_channel(self):
  1142. """
  1143. Return the channel name used for this transport's logging.
  1144. @return: channel name.
  1145. @rtype: str
  1146. @since: 1.2
  1147. """
  1148. return self.log_name
  1149. def set_hexdump(self, hexdump):
  1150. """
  1151. Turn on/off logging a hex dump of protocol traffic at DEBUG level in
  1152. the logs. Normally you would want this off (which is the default),
  1153. but if you are debugging something, it may be useful.
  1154. @param hexdump: C{True} to log protocol traffix (in hex) to the log;
  1155. C{False} otherwise.
  1156. @type hexdump: bool
  1157. """
  1158. self.packetizer.set_hexdump(hexdump)
  1159. def get_hexdump(self):
  1160. """
  1161. Return C{True} if the transport is currently logging hex dumps of
  1162. protocol traffic.
  1163. @return: C{True} if hex dumps are being logged
  1164. @rtype: bool
  1165. @since: 1.4
  1166. """
  1167. return self.packetizer.get_hexdump()
  1168. def use_compression(self, compress=True):
  1169. """
  1170. Turn on/off compression. This will only have an affect before starting
  1171. the transport (ie before calling L{connect}, etc). By default,
  1172. compression is off since it negatively affects interactive sessions.
  1173. @param compress: C{True} to ask the remote client/server to compress
  1174. traffic; C{False} to refuse compression
  1175. @type compress: bool
  1176. @since: 1.5.2
  1177. """
  1178. if compress:
  1179. self._preferred_compression = ( 'zlib@openssh.com', 'zlib', 'none' )
  1180. else:
  1181. self._preferred_compression = ( 'none', )
  1182. def getpeername(self):
  1183. """
  1184. Return the address of the remote side of this Transport, if possible.
  1185. This is effectively a wrapper around C{'getpeername'} on the underlying
  1186. socket. If the socket-like object has no C{'getpeername'} method,
  1187. then C{("unknown", 0)} is returned.
  1188. @return: the address if the remote host, if known
  1189. @rtype: tuple(str, int)
  1190. """
  1191. gp = getattr(self.sock, 'getpeername', None)
  1192. if gp is None:
  1193. return ('unknown', 0)
  1194. return gp()
  1195. def stop_thread(self):
  1196. self.active = False
  1197. self.packetizer.close()
  1198. ### internals...
  1199. def _log(self, level, msg, *args):
  1200. if issubclass(type(msg), list):
  1201. for m in msg:
  1202. self.logger.log(level, m)
  1203. else:
  1204. self.logger.log(level, msg, *args)
  1205. def _get_modulus_pack(self):
  1206. "used by KexGex to find primes for group exchange"
  1207. return self._modulus_pack
  1208. def _next_channel(self):
  1209. "you are holding the lock"
  1210. chanid = self._channel_counter
  1211. while self._channels.get(chanid) is not None:
  1212. self._channel_counter = (self._channel_counter + 1) & 0xffffff
  1213. chanid = self._channel_counter
  1214. self._channel_counter = (self._channel_counter + 1) & 0xffffff
  1215. return chanid
  1216. def _unlink_channel(self, chanid):
  1217. "used by a Channel to remove itself from the active channel list"
  1218. self._channels.delete(chanid)
  1219. def _send_message(self, data):
  1220. self.packetizer.send_message(data)
  1221. def _send_user_message(self, data):
  1222. """
  1223. send a message, but block if we're in key negotiation. this is used
  1224. for user-initiated requests.
  1225. """
  1226. start = time.time()
  1227. while True:
  1228. self.clear_to_send.wait(0.1)
  1229. if not self.active:
  1230. self._log(DEBUG, 'Dropping user packet because connection is dead.')
  1231. return
  1232. self.clear_to_send_lock.acquire()
  1233. if self.clear_to_send.isSet():
  1234. break
  1235. self.clear_to_send_lock.release()
  1236. if time.time() > start + self.clear_to_send_timeout:
  1237. raise SSHException('Key-exchange timed out waiting for key negotiation')
  1238. try:
  1239. self._send_message(data)
  1240. finally:
  1241. self.clear_to_send_lock.release()
  1242. def _set_K_H(self, k, h):
  1243. "used by a kex object to set the K (root key) and H (exchange hash)"
  1244. self.K = k
  1245. self.H = h
  1246. if self.session_id == None:
  1247. self.session_id = h
  1248. def _expect_packet(self, *ptypes):
  1249. "used by a kex object to register the next packet type it expects to see"
  1250. self._expected_packet = tuple(ptypes)
  1251. def _verify_key(self, host_key, sig):
  1252. key = self._key_info[self.host_key_type](Message(host_key))
  1253. if key is None:
  1254. raise SSHException('Unknown host key type')
  1255. if not key.verify_ssh_sig(self.H, Message(sig)):
  1256. raise SSHException('Signature verification (%s) failed.' % self.host_key_type)
  1257. self.host_key = key
  1258. def _compute_key(self, id, nbytes):
  1259. "id is 'A' - 'F' for the various keys used by ssh"
  1260. m = Message()
  1261. m.add_mpint(self.K)
  1262. m.add_bytes(self.H)
  1263. m.add_byte(id)
  1264. m.add_bytes(self.session_id)
  1265. out = sofar = SHA.new(str(m)).digest()
  1266. while len(out) < nbytes:
  1267. m = Message()
  1268. m.add_mpint(self.K)
  1269. m.add_bytes(self.H)
  1270. m.add_bytes(sofar)
  1271. digest = SHA.new(str(m)).digest()
  1272. out += digest
  1273. sofar += digest
  1274. return out[:nbytes]
  1275. def _get_cipher(self, name, key, iv):
  1276. if name not in self._cipher_info:
  1277. raise SSHException('Unknown client cipher ' + name)
  1278. if name in ('arcfour128', 'arcfour256'):
  1279. # arcfour cipher
  1280. cipher = self._cipher_info[name]['class'].new(key)
  1281. # as per RFC 4345, the first 1536 bytes of keystream
  1282. # generated by the cipher MUST be discarded
  1283. cipher.encrypt(" " * 1536)
  1284. return cipher
  1285. elif name.endswith("-ctr"):
  1286. # CTR modes, we need a counter
  1287. counter = Counter.new(nbits=self._cipher_info[name]['block-size'] * 8, initial_value=util.inflate_long(iv, True))
  1288. return self._cipher_info[name]['class'].new(key, self._cipher_info[name]['mode'], iv, counter)
  1289. else:
  1290. return self._cipher_info[name]['class'].new(key, self._cipher_info[name]['mode'], iv)
  1291. def _set_x11_handler(self, handler):
  1292. # only called if a channel has turned on x11 forwarding
  1293. if handler is None:
  1294. # by default, use the same mechanism as accept()
  1295. def default_handler(channel, (src_addr, src_port)):
  1296. self._queue_incoming_channel(channel)
  1297. self._x11_handler = default_handler
  1298. else:
  1299. self._x11_handler = handler
  1300. def _queue_incoming_channel(self, channel):
  1301. self.lock.acquire()
  1302. try:
  1303. self.server_accepts.append(channel)
  1304. self.server_accept_cv.notify()
  1305. finally:
  1306. self.lock.release()
  1307. def run(self):
  1308. # (use the exposed "run" method, because if we specify a thread target
  1309. # of a private method, threading.Thread will keep a reference to it
  1310. # indefinitely, creating a GC cycle and not letting Transport ever be
  1311. # GC'd. it's a bug in Thread.)
  1312. # active=True occurs before the thread is launched, to avoid a race
  1313. _active_threads.append(self)
  1314. if self.server_mode:
  1315. self._log(DEBUG, 'starting thread (server mode): %s' % hex(long(id(self)) & 0xffffffffL))
  1316. else:
  1317. self._log(DEBUG, 'starting thread (client mode): %s' % hex(long(id(self)) & 0xffffffffL))
  1318. try:
  1319. self.packetizer.write_all(self.local_version + '\r\n')
  1320. self._check_banner()
  1321. self._send_kex_init()
  1322. self._expect_packet(MSG_KEXINIT)
  1323. while self.active:
  1324. if self.packetizer.need_rekey() and not self.in_kex:
  1325. self._send_kex_init()
  1326. try:
  1327. ptype, m = self.packetizer.read_message()
  1328. except NeedRekeyException:
  1329. continue
  1330. if ptype == MSG_IGNORE:
  1331. continue
  1332. elif ptype == MSG_DISCONNECT:
  1333. self._parse_disconnect(m)
  1334. self.active = False
  1335. self.packetizer.close()
  1336. break
  1337. elif ptype == MSG_DEBUG:
  1338. self._parse_debug(m)
  1339. continue
  1340. if len(self._expected_packet) > 0:
  1341. if ptype not in self._expected_packet:
  1342. raise SSHException('Expecting packet from %r, got %d' % (self._expected_packet, ptype))
  1343. self._expected_packet = tuple()
  1344. if (ptype >= 30) and (ptype <= 39):
  1345. self.kex_engine.parse_next(ptype, m)
  1346. continue
  1347. if ptype in self._handler_table:
  1348. self._handler_table[ptype](self, m)
  1349. elif ptype in self._channel_handler_table:
  1350. chanid = m.get_int()
  1351. chan = self._channels.get(chanid)
  1352. if chan is not None:
  1353. self._channel_handler_table[ptype](chan, m)
  1354. elif chanid in self.channels_seen:
  1355. self._log(DEBUG, 'Ignoring message for dead channel %d' % chanid)
  1356. else:
  1357. self._log(ERROR, 'Channel request for unknown channel %d' % chanid)
  1358. self.active = False
  1359. self.packetizer.close()
  1360. elif (self.auth_handler is not None) and (ptype in self.auth_handler._handler_table):
  1361. self.auth_handler._handler_table[ptype](self.auth_handler, m)
  1362. else:
  1363. self._log(WARNING, 'Oops, unhandled type %d' % ptype)
  1364. msg = Message()
  1365. msg.add_byte(chr(MSG_UNIMPLEMENTED))
  1366. msg.add_int(m.seqno)
  1367. self._send_message(msg)
  1368. except SSHException, e:
  1369. self._log(ERROR, 'Exception: ' + str(e))
  1370. self._log(ERROR, util.tb_strings())
  1371. self.saved_exception = e
  1372. except EOFError, e:
  1373. self._log(DEBUG, 'EOF in transport thread')
  1374. #self._log(DEBUG, util.tb_strings())
  1375. self.saved_exception = e
  1376. except socket.error, e:
  1377. if type(e.args) is tuple:
  1378. emsg = '%s (%d)' % (e.args[1], e.args[0])
  1379. else:
  1380. emsg = e.args
  1381. self._log(ERROR, 'Socket exception: ' + emsg)
  1382. self.saved_exception = e
  1383. except Exception, e:
  1384. self._log(ERROR, 'Unknown exception: ' + str(e))
  1385. self._log(ERROR, util.tb_strings())
  1386. self.saved_exception = e
  1387. _active_threads.remove(self)
  1388. for chan in self._channels.values():
  1389. chan._unlink()
  1390. if self.active:
  1391. self.active = False
  1392. if self.server_object is not None:
  1393. self.server_object.handle_disconnect()
  1394. self.packetizer.close()
  1395. if self.completion_event != None:
  1396. self.completion_event.set()
  1397. if self.auth_handler is not None:
  1398. self.auth_handler.abort()
  1399. for event in self.channel_events.values():
  1400. event.set()
  1401. try:
  1402. self.lock.acquire()
  1403. self.server_accept_cv.notify()
  1404. finally:
  1405. self.lock.release()
  1406. self.sock.close()
  1407. ### protocol stages
  1408. def _negotiate_keys(self, m):
  1409. # throws SSHException on anything unusual
  1410. self.clear_to_send_lock.acquire()
  1411. try:
  1412. self.clear_to_send.clear()
  1413. finally:
  1414. self.clear_to_send_lock.release()
  1415. if self.local_kex_init == None:
  1416. # remote side wants to renegotiate
  1417. self._send_kex_init()
  1418. self._parse_kex_init(m)
  1419. self.kex_engine.start_kex()
  1420. def _check_banner(self):
  1421. # this is slow, but we only have to do it once
  1422. for i in range(100):
  1423. # give them 15 seconds for the first line, then just 2 seconds
  1424. # each additional line. (some sites have very high latency.)
  1425. if i == 0:
  1426. timeout = self.banner_timeout
  1427. else:
  1428. timeout = 2
  1429. try:
  1430. buf = self.packetizer.readline(timeout)
  1431. except Exception, x:
  1432. raise SSHException('Error reading SSH protocol banner' + str(x))
  1433. if buf[:4] == 'SSH-':
  1434. break
  1435. self._log(DEBUG, 'Banner: ' + buf)
  1436. if buf[:4] != 'SSH-':
  1437. raise SSHException('Indecipherable protocol version "' + buf + '"')
  1438. # save this server version string for later
  1439. self.remote_version = buf
  1440. # pull off any attached comment
  1441. comment = ''
  1442. i = string.find(buf, ' ')
  1443. if i >= 0:
  1444. comment = buf[i+1:]
  1445. buf = buf[:i]
  1446. # parse out version string and make sure it matches
  1447. segs = buf.split('-', 2)
  1448. if len(segs) < 3:
  1449. raise SSHException('Invalid SSH banner')
  1450. version = segs[1]
  1451. client = segs[2]
  1452. if version != '1.99' and version != '2.0':
  1453. raise SSHException('Incompatible version (%s instead of 2.0)' % (version,))
  1454. self._log(INFO, 'Connected (version %s, client %s)' % (version, client))
  1455. def _send_kex_init(self):
  1456. """
  1457. announce to the other side that we'd like to negotiate keys, and what
  1458. kind of key negotiation we support.
  1459. """
  1460. self.clear_to_send_lock.acquire()
  1461. try:
  1462. self.clear_to_send.clear()
  1463. finally:
  1464. self.clear_to_send_lock.release()
  1465. self.in_kex = True
  1466. if self.server_mode:
  1467. if (self._modulus_pack is None) and ('diffie-hellman-group-exchange-sha1' in self._preferred_kex):
  1468. # can't do group-exchange if we don't have a pack of potential primes
  1469. pkex = list(self.get_security_options().kex)
  1470. pkex.remove('diffie-hellman-group-exchange-sha1')
  1471. self.get_security_options().kex = pkex
  1472. available_server_keys = filter(self.server_key_dict.keys().__contains__,
  1473. self._preferred_keys)
  1474. else:
  1475. available_server_keys = self._preferred_keys
  1476. m = Message()
  1477. m.add_byte(chr(MSG_KEXINIT))
  1478. m.add_bytes(rng.read(16))
  1479. m.add_list(self._preferred_kex)
  1480. m.add_list(available_server_keys)
  1481. m.add_list(self._preferred_ciphers)
  1482. m.add_list(self._preferred_ciphers)
  1483. m.add_list(self._preferred_macs)
  1484. m.add_list(self._preferred_macs)
  1485. m.add_list(self._preferred_compression)
  1486. m.add_list(self._preferred_compression)
  1487. m.add_string('')
  1488. m.add_string('')
  1489. m.add_boolean(False)
  1490. m.add_int(0)
  1491. # save a copy for later (needed to compute a hash)
  1492. self.local_kex_init = str(m)
  1493. self._send_message(m)
  1494. def _parse_kex_init(self, m):
  1495. cookie = m.get_bytes(16)
  1496. kex_algo_list = m.get_list()
  1497. server_key_algo_list = m.get_list()
  1498. client_encrypt_algo_list = m.get_list()
  1499. server_encrypt_algo_list = m.get_list()
  1500. client_mac_algo_list = m.get_list()
  1501. server_mac_algo_list = m.get_list()
  1502. client_compress_algo_list = m.get_list()
  1503. server_compress_algo_list = m.get_list()
  1504. client_lang_list = m.get_list()
  1505. server_lang_list = m.get_list()
  1506. kex_follows = m.get_boolean()
  1507. unused = m.get_int()
  1508. self._log(DEBUG, 'kex algos:' + str(kex_algo_list) + ' server key:' + str(server_key_algo_list) + \
  1509. ' client encrypt:' + str(client_encrypt_algo_list) + \
  1510. ' server encrypt:' + str(server_encrypt_algo_list) + \
  1511. ' client mac:' + str(client_mac_algo_list) + \
  1512. ' server mac:' + str(server_mac_algo_list) + \
  1513. ' client compress:' + str(client_compress_algo_list) + \
  1514. ' server compress:' + str(server_compress_algo_list) + \
  1515. ' client lang:' + str(client_lang_list) + \
  1516. ' server lang:' + str(server_lang_list) + \
  1517. ' kex follows?' + str(kex_follows))
  1518. # as a server, we pick the first item in the client's list that we support.
  1519. # as a client, we pick the first item in our list that the server supports.
  1520. if self.server_mode:
  1521. agreed_kex = filter(self._preferred_kex.__contains__, kex_algo_list)
  1522. else:
  1523. agreed_kex = filter(kex_algo_list.__contains__, self._preferred_kex)
  1524. if len(agreed_kex) == 0:
  1525. raise SSHException('Incompatible ssh peer (no acceptable kex algorithm)')
  1526. self.kex_engine = self._kex_info[agreed_kex[0]](self)
  1527. if self.server_mode:
  1528. available_server_keys = filter(self.server_key_dict.keys().__contains__,
  1529. self._preferred_keys)
  1530. agreed_keys = filter(available_server_keys.__contains__, server_key_algo_list)
  1531. else:
  1532. agreed_keys = filter(server_key_algo_list.__contains__, self._preferred_keys)
  1533. if len(agreed_keys) == 0:
  1534. raise SSHException('Incompatible ssh peer (no acceptable host key)')
  1535. self.host_key_type = agreed_keys[0]
  1536. if self.server_mode and (self.get_server_key() is None):
  1537. raise SSHException('Incompatible ssh peer (can\'t match requested host key type)')
  1538. if self.server_mode:
  1539. agreed_local_ciphers = filter(self._preferred_ciphers.__contains__,
  1540. server_encrypt_algo_list)
  1541. agreed_remote_ciphers = filter(self._preferred_ciphers.__contains__,
  1542. client_encrypt_algo_list)
  1543. else:
  1544. agreed_local_ciphers = filter(client_encrypt_algo_list.__contains__,
  1545. self._preferred_ciphers)
  1546. agreed_remote_ciphers = filter(server_encrypt_algo_list.__contains__,
  1547. self._preferred_ciphers)
  1548. if (len(agreed_local_ciphers) == 0) or (len(agreed_remote_ciphers) == 0):
  1549. raise SSHException('Incompatible ssh server (no acceptable ciphers)')
  1550. self.local_cipher = agreed_local_ciphers[0]
  1551. self.remote_cipher = agreed_remote_ciphers[0]
  1552. self._log(DEBUG, 'Ciphers agreed: local=%s, remote=%s' % (self.local_cipher, self.remote_cipher))
  1553. if self.server_mode:
  1554. agreed_remote_macs = filter(self._preferred_macs.__contains__, client_mac_algo_list)
  1555. agreed_local_macs = filter(self._preferred_macs.__contains__, server_mac_algo_list)
  1556. else:
  1557. agreed_local_macs = filter(client_mac_algo_list.__contains__, self._preferred_macs)
  1558. agreed_remote_macs = filter(server_mac_algo_list.__contains__, self._preferred_macs)
  1559. if (len(agreed_local_macs) == 0) or (len(agreed_remote_macs) == 0):
  1560. raise SSHException('Incompatible ssh server (no acceptable macs)')
  1561. self.local_mac = agreed_local_macs[0]
  1562. self.remote_mac = agreed_remote_macs[0]
  1563. if self.server_mode:
  1564. agreed_remote_compression = filter(self._preferred_compression.__contains__, client_compress_algo_list)
  1565. agreed_local_compression = filter(self._preferred_compression.__contains__, server_compress_algo_list)
  1566. else:
  1567. agreed_local_compression = filter(client_compress_algo_list.__contains__, self._preferred_compression)
  1568. agreed_remote_compression = filter(server_compress_algo_list.__contains__, self._preferred_compression)
  1569. if (len(agreed_local_compression) == 0) or (len(agreed_remote_compression) == 0):
  1570. raise SSHException('Incompatible ssh server (no acceptable compression) %r %r %r' % (agreed_local_compression, agreed_remote_compression, self._preferred_compression))
  1571. self.local_compression = agreed_local_compression[0]
  1572. self.remote_compression = agreed_remote_compression[0]
  1573. self._log(DEBUG, 'using kex %s; server key type %s; cipher: local %s, remote %s; mac: local %s, remote %s; compression: local %s, remote %s' %
  1574. (agreed_kex[0], self.host_key_type, self.local_cipher, self.remote_cipher, self.local_mac,
  1575. self.remote_mac, self.local_compression, self.remote_compression))
  1576. # save for computing hash later...
  1577. # now wait! openssh has a bug (and others might too) where there are
  1578. # actually some extra bytes (one NUL byte in openssh's case) added to
  1579. # the end of the packet but not parsed. turns out we need to throw
  1580. # away those bytes because they aren't part of the hash.
  1581. self.remote_kex_init = chr(MSG_KEXINIT) + m.get_so_far()
  1582. def _activate_inbound(self):
  1583. "switch on newly negotiated encryption parameters for inbound traffic"
  1584. block_size = self._cipher_info[self.remote_cipher]['block-size']
  1585. if self.server_mode:
  1586. IV_in = self._compute_key('A', block_size)
  1587. key_in = self._compute_key('C', self._cipher_info[self.remote_cipher]['key-size'])
  1588. else:
  1589. IV_in = self._compute_key('B', block_size)
  1590. key_in = self._compute_key('D', self._cipher_info[self.remote_cipher]['key-size'])
  1591. engine = self._get_cipher(self.remote_cipher, key_in, IV_in)
  1592. mac_size = self._mac_info[self.remote_mac]['size']
  1593. mac_engine = self._mac_info[self.remote_mac]['class']
  1594. # initial mac keys are done in the hash's natural size (not the potentially truncated
  1595. # transmission size)
  1596. if self.server_mode:
  1597. mac_key = self._compute_key('E', mac_engine.digest_size)
  1598. else:
  1599. mac_key = self._compute_key('F', mac_engine.digest_size)
  1600. self.packetizer.set_inbound_cipher(engine, block_size, mac_engine, mac_size, mac_key)
  1601. compress_in = self._compression_info[self.remote_compression][1]
  1602. if (compress_in is not None) and ((self.remote_compression != 'zlib@openssh.com') or self.authenticated):
  1603. self._log(DEBUG, 'Switching on inbound compression ...')
  1604. self.packetizer.set_inbound_compressor(compress_in())
  1605. def _activate_outbound(self):
  1606. "switch on newly negotiated encryption parameters for outbound traffic"
  1607. m = Message()
  1608. m.add_byte(chr(MSG_NEWKEYS))
  1609. self._send_message(m)
  1610. block_size = self._cipher_info[self.local_cipher]['block-size']
  1611. if self.server_mode:
  1612. IV_out = self._compute_key('B', block_size)
  1613. key_out = self._compute_key('D', self._cipher_info[self.local_cipher]['key-size'])
  1614. else:
  1615. IV_out = self._compute_key('A', block_size)
  1616. key_out = self._compute_key('C', self._cipher_info[self.local_cipher]['key-size'])
  1617. engine = self._get_cipher(self.local_cipher, key_out, IV_out)
  1618. mac_size = self._mac_info[self.local_mac]['size']
  1619. mac_engine = self._mac_info[self.local_mac]['class']
  1620. # initial mac keys are done in the hash's natural size (not the potentially truncated
  1621. # transmission size)
  1622. if self.server_mode:
  1623. mac_key = self._compute_key('F', mac_engine.digest_size)
  1624. else:
  1625. mac_key = self._compute_key('E', mac_engine.digest_size)
  1626. self.packetizer.set_outbound_cipher(engine, block_size, mac_engine, mac_size, mac_key)
  1627. compress_out = self._compression_info[self.local_compression][0]
  1628. if (compress_out is not None) and ((self.local_compression != 'zlib@openssh.com') or self.authenticated):
  1629. self._log(DEBUG, 'Switching on outbound compression ...')
  1630. self.packetizer.set_outbound_compressor(compress_out())
  1631. if not self.packetizer.need_rekey():
  1632. self.in_kex = False
  1633. # we always expect to receive NEWKEYS now
  1634. self._expect_packet(MSG_NEWKEYS)
  1635. def _auth_trigger(self):
  1636. self.authenticated = True
  1637. # delayed initiation of compression
  1638. if self.local_compression == 'zlib@openssh.com':
  1639. compress_out = self._compression_info[self.local_compression][0]
  1640. self._log(DEBUG, 'Switching on outbound compression ...')
  1641. self.packetizer.set_outbound_compressor(compress_out())
  1642. if self.remote_compression == 'zlib@openssh.com':
  1643. compress_in = self._compression_info[self.remote_compression][1]
  1644. self._log(DEBUG, 'Switching on inbound compression ...')
  1645. self.packetizer.set_inbound_compressor(compress_in())
  1646. def _parse_newkeys(self, m):
  1647. self._log(DEBUG, 'Switch to new keys ...')
  1648. self._activate_inbound()
  1649. # can also free a bunch of stuff here
  1650. self.local_kex_init = self.remote_kex_init = None
  1651. self.K = None
  1652. self.kex_engine = None
  1653. if self.server_mode and (self.auth_handler is None):
  1654. # create auth handler for server mode
  1655. self.auth_handler = AuthHandler(self)
  1656. if not self.initial_kex_done:
  1657. # this was the first key exchange
  1658. self.initial_kex_done = True
  1659. # send an event?
  1660. if self.completion_event != None:
  1661. self.completion_event.set()
  1662. # it's now okay to send data again (if this was a re-key)
  1663. if not self.packetizer.need_rekey():
  1664. self.in_kex = False
  1665. self.clear_to_send_lock.acquire()
  1666. try:
  1667. self.clear_to_send.set()
  1668. finally:
  1669. self.clear_to_send_lock.release()
  1670. return
  1671. def _parse_disconnect(self, m):
  1672. code = m.get_int()
  1673. desc = m.get_string()
  1674. self._log(INFO, 'Disconnect (code %d): %s' % (code, desc))
  1675. def _parse_global_request(self, m):
  1676. kind = m.get_string()
  1677. self._log(DEBUG, 'Received global request "%s"' % kind)
  1678. want_reply = m.get_boolean()
  1679. if not self.server_mode:
  1680. self._log(DEBUG, 'Rejecting "%s" global request from server.' % kind)
  1681. ok = False
  1682. elif kind == 'tcpip-forward':
  1683. address = m.get_string()
  1684. port = m.get_int()
  1685. ok = self.server_object.check_port_forward_request(address, port)
  1686. if ok != False:
  1687. ok = (ok,)
  1688. elif kind == 'cancel-tcpip-forward':
  1689. address = m.get_string()
  1690. port = m.get_int()
  1691. self.server_object.cancel_port_forward_request(address, port)
  1692. ok = True
  1693. else:
  1694. ok = self.server_object.check_global_request(kind, m)
  1695. extra = ()
  1696. if type(ok) is tuple:
  1697. extra = ok
  1698. ok = True
  1699. if want_reply:
  1700. msg = Message()
  1701. if ok:
  1702. msg.add_byte(chr(MSG_REQUEST_SUCCESS))
  1703. msg.add(*extra)
  1704. else:
  1705. msg.add_byte(chr(MSG_REQUEST_FAILURE))
  1706. self._send_message(msg)
  1707. def _parse_request_success(self, m):
  1708. self._log(DEBUG, 'Global request successful.')
  1709. self.global_response = m
  1710. if self.completion_event is not None:
  1711. self.completion_event.set()
  1712. def _parse_request_failure(self, m):
  1713. self._log(DEBUG, 'Global request denied.')
  1714. self.global_response = None
  1715. if self.completion_event is not None:
  1716. self.completion_event.set()
  1717. def _parse_channel_open_success(self, m):
  1718. chanid = m.get_int()
  1719. server_chanid = m.get_int()
  1720. server_window_size = m.get_int()
  1721. server_max_packet_size = m.get_int()
  1722. chan = self._channels.get(chanid)
  1723. if chan is None:
  1724. self._log(WARNING, 'Success for unrequested channel! [??]')
  1725. return
  1726. self.lock.acquire()
  1727. try:
  1728. chan._set_remote_channel(server_chanid, server_window_size, server_max_packet_size)
  1729. self._log(INFO, 'Secsh channel %d opened.' % chanid)
  1730. if chanid in self.channel_events:
  1731. self.channel_events[chanid].set()
  1732. del self.channel_events[chanid]
  1733. finally:
  1734. self.lock.release()
  1735. return
  1736. def _parse_channel_open_failure(self, m):
  1737. chanid = m.get_int()
  1738. reason = m.get_int()
  1739. reason_str = m.get_string()
  1740. lang = m.get_string()
  1741. reason_text = CONNECTION_FAILED_CODE.get(reason, '(unknown code)')
  1742. self._log(INFO, 'Secsh channel %d open FAILED: %s: %s' % (chanid, reason_str, reason_text))
  1743. self.lock.acquire()
  1744. try:
  1745. self.saved_exception = ChannelException(reason, reason_text)
  1746. if chanid in self.channel_events:
  1747. self._channels.delete(chanid)
  1748. if chanid in self.channel_events:
  1749. self.channel_events[chanid].set()
  1750. del self.channel_events[chanid]
  1751. finally:
  1752. self.lock.release()
  1753. return
  1754. def _parse_channel_open(self, m):
  1755. kind = m.get_string()
  1756. chanid = m.get_int()
  1757. initial_window_size = m.get_int()
  1758. max_packet_size = m.get_int()
  1759. reject = False
  1760. if (kind == 'x11') and (self._x11_handler is not None):
  1761. origin_addr = m.get_string()
  1762. origin_port = m.get_int()
  1763. self._log(DEBUG, 'Incoming x11 connection from %s:%d' % (origin_addr, origin_port))
  1764. self.lock.acquire()
  1765. try:
  1766. my_chanid = self._next_channel()
  1767. finally:
  1768. self.lock.release()
  1769. elif (kind == 'forwarded-tcpip') and (self._tcp_handler is not None):
  1770. server_addr = m.get_string()
  1771. server_port = m.get_int()
  1772. origin_addr = m.get_string()
  1773. origin_port = m.get_int()
  1774. self._log(DEBUG, 'Incoming tcp forwarded connection from %s:%d' % (origin_addr, origin_port))
  1775. self.lock.acquire()
  1776. try:
  1777. my_chanid = self._next_channel()
  1778. finally:
  1779. self.lock.release()
  1780. elif not self.server_mode:
  1781. self._log(DEBUG, 'Rejecting "%s" channel request from server.' % kind)
  1782. reject = True
  1783. reason = OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
  1784. else:
  1785. self.lock.acquire()
  1786. try:
  1787. my_chanid = self._next_channel()
  1788. finally:
  1789. self.lock.release()
  1790. if kind == 'direct-tcpip':
  1791. # handle direct-tcpip requests comming from the client
  1792. dest_addr = m.get_string()
  1793. dest_port = m.get_int()
  1794. origin_addr = m.get_string()
  1795. origin_port = m.get_int()
  1796. reason = self.server_object.check_channel_direct_tcpip_request(
  1797. my_chanid, (origin_addr, origin_port),
  1798. (dest_addr, dest_port))
  1799. else:
  1800. reason = self.server_object.check_channel_request(kind, my_chanid)
  1801. if reason != OPEN_SUCCEEDED:
  1802. self._log(DEBUG, 'Rejecting "%s" channel request from client.' % kind)
  1803. reject = True
  1804. if reject:
  1805. msg = Message()
  1806. msg.add_byte(chr(MSG_CHANNEL_OPEN_FAILURE))
  1807. msg.add_int(chanid)
  1808. msg.add_int(reason)
  1809. msg.add_string('')
  1810. msg.add_string('en')
  1811. self._send_message(msg)
  1812. return
  1813. chan = Channel(my_chanid)
  1814. self.lock.acquire()
  1815. try:
  1816. self._channels.put(my_chanid, chan)
  1817. self.channels_seen[my_chanid] = True
  1818. chan._set_transport(self)
  1819. chan._set_window(self.window_size, self.max_packet_size)
  1820. chan._set_remote_channel(chanid, initial_window_size, max_packet_size)
  1821. finally:
  1822. self.lock.release()
  1823. m = Message()
  1824. m.add_byte(chr(MSG_CHANNEL_OPEN_SUCCESS))
  1825. m.add_int(chanid)
  1826. m.add_int(my_chanid)
  1827. m.add_int(self.window_size)
  1828. m.add_int(self.max_packet_size)
  1829. self._send_message(m)
  1830. self._log(INFO, 'Secsh channel %d (%s) opened.', my_chanid, kind)
  1831. if kind == 'x11':
  1832. self._x11_handler(chan, (origin_addr, origin_port))
  1833. elif kind == 'forwarded-tcpip':
  1834. chan.origin_addr = (origin_addr, origin_port)
  1835. self._tcp_handler(chan, (origin_addr, origin_port), (server_addr, server_port))
  1836. else:
  1837. self._queue_incoming_channel(chan)
  1838. def _parse_debug(self, m):
  1839. always_display = m.get_boolean()
  1840. msg = m.get_string()
  1841. lang = m.get_string()
  1842. self._log(DEBUG, 'Debug msg: ' + util.safe_string(msg))
  1843. def _get_subsystem_handler(self, name):
  1844. try:
  1845. self.lock.acquire()
  1846. if name not in self.subsystem_table:
  1847. return (None, [], {})
  1848. return self.subsystem_table[name]
  1849. finally:
  1850. self.lock.release()
  1851. _handler_table = {
  1852. MSG_NEWKEYS: _parse_newkeys,
  1853. MSG_GLOBAL_REQUEST: _parse_global_request,
  1854. MSG_REQUEST_SUCCESS: _parse_request_success,
  1855. MSG_REQUEST_FAILURE: _parse_request_failure,
  1856. MSG_CHANNEL_OPEN_SUCCESS: _parse_channel_open_success,
  1857. MSG_CHANNEL_OPEN_FAILURE: _parse_channel_open_failure,
  1858. MSG_CHANNEL_OPEN: _parse_channel_open,
  1859. MSG_KEXINIT: _negotiate_keys,
  1860. }
  1861. _channel_handler_table = {
  1862. MSG_CHANNEL_SUCCESS: Channel._request_success,
  1863. MSG_CHANNEL_FAILURE: Channel._request_failed,
  1864. MSG_CHANNEL_DATA: Channel._feed,
  1865. MSG_CHANNEL_EXTENDED_DATA: Channel._feed_extended,
  1866. MSG_CHANNEL_WINDOW_ADJUST: Channel._window_adjust,
  1867. MSG_CHANNEL_REQUEST: Channel._handle_request,
  1868. MSG_CHANNEL_EOF: Channel._handle_eof,
  1869. MSG_CHANNEL_CLOSE: Channel._handle_close,
  1870. }