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

/lib/paramiko/transport.py

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