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

/paramiko/transport.py

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