PageRenderTime 95ms CodeModel.GetById 7ms RepoModel.GetById 0ms app.codeStats 0ms

/paramiko/transport.py

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