PageRenderTime 460ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/paramiko/transport.py

https://github.com/himikof/paramiko
Python | 2107 lines | 2055 code | 14 blank | 38 comment | 24 complexity | edb4404368a1d86319ec591278c80098 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file