PageRenderTime 83ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/paramiko/transport.py

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