PageRenderTime 60ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/build/paramiko/paramiko/transport.py

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