PageRenderTime 330ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/code/python/paramiko-1.6.1/paramiko/transport.py

http://sb-scripts.googlecode.com/
Python | 1584 lines | 1532 code | 14 blank | 38 comment | 20 complexity | d53c3b9ea0b2e113eea621783d530946 MD5 | raw file
Possible License(s): LGPL-2.1

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

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

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