You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

780 lines
30 KiB

7 years ago
  1. # Copyright (C) 2006-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 distributed 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. SSH client & key policies
  20. """
  21. from binascii import hexlify
  22. import getpass
  23. import inspect
  24. import os
  25. import socket
  26. import warnings
  27. from errno import ECONNREFUSED, EHOSTUNREACH
  28. from paramiko.agent import Agent
  29. from paramiko.common import DEBUG
  30. from paramiko.config import SSH_PORT
  31. from paramiko.dsskey import DSSKey
  32. from paramiko.ecdsakey import ECDSAKey
  33. from paramiko.ed25519key import Ed25519Key
  34. from paramiko.hostkeys import HostKeys
  35. from paramiko.py3compat import string_types
  36. from paramiko.rsakey import RSAKey
  37. from paramiko.ssh_exception import (
  38. SSHException, BadHostKeyException, NoValidConnectionsError
  39. )
  40. from paramiko.transport import Transport
  41. from paramiko.util import retry_on_signal, ClosingContextManager
  42. class SSHClient (ClosingContextManager):
  43. """
  44. A high-level representation of a session with an SSH server. This class
  45. wraps `.Transport`, `.Channel`, and `.SFTPClient` to take care of most
  46. aspects of authenticating and opening channels. A typical use case is::
  47. client = SSHClient()
  48. client.load_system_host_keys()
  49. client.connect('ssh.example.com')
  50. stdin, stdout, stderr = client.exec_command('ls -l')
  51. You may pass in explicit overrides for authentication and server host key
  52. checking. The default mechanism is to try to use local key files or an
  53. SSH agent (if one is running).
  54. Instances of this class may be used as context managers.
  55. .. versionadded:: 1.6
  56. """
  57. def __init__(self):
  58. """
  59. Create a new SSHClient.
  60. """
  61. self._system_host_keys = HostKeys()
  62. self._host_keys = HostKeys()
  63. self._host_keys_filename = None
  64. self._log_channel = None
  65. self._policy = RejectPolicy()
  66. self._transport = None
  67. self._agent = None
  68. def load_system_host_keys(self, filename=None):
  69. """
  70. Load host keys from a system (read-only) file. Host keys read with
  71. this method will not be saved back by `save_host_keys`.
  72. This method can be called multiple times. Each new set of host keys
  73. will be merged with the existing set (new replacing old if there are
  74. conflicts).
  75. If ``filename`` is left as ``None``, an attempt will be made to read
  76. keys from the user's local "known hosts" file, as used by OpenSSH,
  77. and no exception will be raised if the file can't be read. This is
  78. probably only useful on posix.
  79. :param str filename: the filename to read, or ``None``
  80. :raises: ``IOError`` --
  81. if a filename was provided and the file could not be read
  82. """
  83. if filename is None:
  84. # try the user's .ssh key file, and mask exceptions
  85. filename = os.path.expanduser('~/.ssh/known_hosts')
  86. try:
  87. self._system_host_keys.load(filename)
  88. except IOError:
  89. pass
  90. return
  91. self._system_host_keys.load(filename)
  92. def load_host_keys(self, filename):
  93. """
  94. Load host keys from a local host-key file. Host keys read with this
  95. method will be checked after keys loaded via `load_system_host_keys`,
  96. but will be saved back by `save_host_keys` (so they can be modified).
  97. The missing host key policy `.AutoAddPolicy` adds keys to this set and
  98. saves them, when connecting to a previously-unknown server.
  99. This method can be called multiple times. Each new set of host keys
  100. will be merged with the existing set (new replacing old if there are
  101. conflicts). When automatically saving, the last hostname is used.
  102. :param str filename: the filename to read
  103. :raises: ``IOError`` -- if the filename could not be read
  104. """
  105. self._host_keys_filename = filename
  106. self._host_keys.load(filename)
  107. def save_host_keys(self, filename):
  108. """
  109. Save the host keys back to a file. Only the host keys loaded with
  110. `load_host_keys` (plus any added directly) will be saved -- not any
  111. host keys loaded with `load_system_host_keys`.
  112. :param str filename: the filename to save to
  113. :raises: ``IOError`` -- if the file could not be written
  114. """
  115. # update local host keys from file (in case other SSH clients
  116. # have written to the known_hosts file meanwhile.
  117. if self._host_keys_filename is not None:
  118. self.load_host_keys(self._host_keys_filename)
  119. with open(filename, 'w') as f:
  120. for hostname, keys in self._host_keys.items():
  121. for keytype, key in keys.items():
  122. f.write('{} {} {}\n'.format(
  123. hostname, keytype, key.get_base64()
  124. ))
  125. def get_host_keys(self):
  126. """
  127. Get the local `.HostKeys` object. This can be used to examine the
  128. local host keys or change them.
  129. :return: the local host keys as a `.HostKeys` object.
  130. """
  131. return self._host_keys
  132. def set_log_channel(self, name):
  133. """
  134. Set the channel for logging. The default is ``"paramiko.transport"``
  135. but it can be set to anything you want.
  136. :param str name: new channel name for logging
  137. """
  138. self._log_channel = name
  139. def set_missing_host_key_policy(self, policy):
  140. """
  141. Set policy to use when connecting to servers without a known host key.
  142. Specifically:
  143. * A **policy** is a "policy class" (or instance thereof), namely some
  144. subclass of `.MissingHostKeyPolicy` such as `.RejectPolicy` (the
  145. default), `.AutoAddPolicy`, `.WarningPolicy`, or a user-created
  146. subclass.
  147. * A host key is **known** when it appears in the client object's cached
  148. host keys structures (those manipulated by `load_system_host_keys`
  149. and/or `load_host_keys`).
  150. :param .MissingHostKeyPolicy policy:
  151. the policy to use when receiving a host key from a
  152. previously-unknown server
  153. """
  154. if inspect.isclass(policy):
  155. policy = policy()
  156. self._policy = policy
  157. def _families_and_addresses(self, hostname, port):
  158. """
  159. Yield pairs of address families and addresses to try for connecting.
  160. :param str hostname: the server to connect to
  161. :param int port: the server port to connect to
  162. :returns: Yields an iterable of ``(family, address)`` tuples
  163. """
  164. guess = True
  165. addrinfos = socket.getaddrinfo(
  166. hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
  167. for (family, socktype, proto, canonname, sockaddr) in addrinfos:
  168. if socktype == socket.SOCK_STREAM:
  169. yield family, sockaddr
  170. guess = False
  171. # some OS like AIX don't indicate SOCK_STREAM support, so just
  172. # guess. :( We only do this if we did not get a single result marked
  173. # as socktype == SOCK_STREAM.
  174. if guess:
  175. for family, _, _, _, sockaddr in addrinfos:
  176. yield family, sockaddr
  177. def connect(
  178. self,
  179. hostname,
  180. port=SSH_PORT,
  181. username=None,
  182. password=None,
  183. pkey=None,
  184. key_filename=None,
  185. timeout=None,
  186. allow_agent=True,
  187. look_for_keys=True,
  188. compress=False,
  189. sock=None,
  190. gss_auth=False,
  191. gss_kex=False,
  192. gss_deleg_creds=True,
  193. gss_host=None,
  194. banner_timeout=None,
  195. auth_timeout=None,
  196. gss_trust_dns=True,
  197. passphrase=None,
  198. ):
  199. """
  200. Connect to an SSH server and authenticate to it. The server's host key
  201. is checked against the system host keys (see `load_system_host_keys`)
  202. and any local host keys (`load_host_keys`). If the server's hostname
  203. is not found in either set of host keys, the missing host key policy
  204. is used (see `set_missing_host_key_policy`). The default policy is
  205. to reject the key and raise an `.SSHException`.
  206. Authentication is attempted in the following order of priority:
  207. - The ``pkey`` or ``key_filename`` passed in (if any)
  208. - ``key_filename`` may contain OpenSSH public certificate paths
  209. as well as regular private-key paths; when files ending in
  210. ``-cert.pub`` are found, they are assumed to match a private
  211. key, and both components will be loaded. (The private key
  212. itself does *not* need to be listed in ``key_filename`` for
  213. this to occur - *just* the certificate.)
  214. - Any key we can find through an SSH agent
  215. - Any "id_rsa", "id_dsa" or "id_ecdsa" key discoverable in
  216. ``~/.ssh/``
  217. - When OpenSSH-style public certificates exist that match an
  218. existing such private key (so e.g. one has ``id_rsa`` and
  219. ``id_rsa-cert.pub``) the certificate will be loaded alongside
  220. the private key and used for authentication.
  221. - Plain username/password auth, if a password was given
  222. If a private key requires a password to unlock it, and a password is
  223. passed in, that password will be used to attempt to unlock the key.
  224. :param str hostname: the server to connect to
  225. :param int port: the server port to connect to
  226. :param str username:
  227. the username to authenticate as (defaults to the current local
  228. username)
  229. :param str password:
  230. Used for password authentication; is also used for private key
  231. decryption if ``passphrase`` is not given.
  232. :param str passphrase:
  233. Used for decrypting private keys.
  234. :param .PKey pkey: an optional private key to use for authentication
  235. :param str key_filename:
  236. the filename, or list of filenames, of optional private key(s)
  237. and/or certs to try for authentication
  238. :param float timeout:
  239. an optional timeout (in seconds) for the TCP connect
  240. :param bool allow_agent:
  241. set to False to disable connecting to the SSH agent
  242. :param bool look_for_keys:
  243. set to False to disable searching for discoverable private key
  244. files in ``~/.ssh/``
  245. :param bool compress: set to True to turn on compression
  246. :param socket sock:
  247. an open socket or socket-like object (such as a `.Channel`) to use
  248. for communication to the target host
  249. :param bool gss_auth:
  250. ``True`` if you want to use GSS-API authentication
  251. :param bool gss_kex:
  252. Perform GSS-API Key Exchange and user authentication
  253. :param bool gss_deleg_creds: Delegate GSS-API client credentials or not
  254. :param str gss_host:
  255. The targets name in the kerberos database. default: hostname
  256. :param bool gss_trust_dns:
  257. Indicates whether or not the DNS is trusted to securely
  258. canonicalize the name of the host being connected to (default
  259. ``True``).
  260. :param float banner_timeout: an optional timeout (in seconds) to wait
  261. for the SSH banner to be presented.
  262. :param float auth_timeout: an optional timeout (in seconds) to wait for
  263. an authentication response.
  264. :raises:
  265. `.BadHostKeyException` -- if the server's host key could not be
  266. verified
  267. :raises: `.AuthenticationException` -- if authentication failed
  268. :raises:
  269. `.SSHException` -- if there was any other error connecting or
  270. establishing an SSH session
  271. :raises socket.error: if a socket error occurred while connecting
  272. .. versionchanged:: 1.15
  273. Added the ``banner_timeout``, ``gss_auth``, ``gss_kex``,
  274. ``gss_deleg_creds`` and ``gss_host`` arguments.
  275. .. versionchanged:: 2.3
  276. Added the ``gss_trust_dns`` argument.
  277. .. versionchanged:: 2.4
  278. Added the ``passphrase`` argument.
  279. """
  280. if not sock:
  281. errors = {}
  282. # Try multiple possible address families (e.g. IPv4 vs IPv6)
  283. to_try = list(self._families_and_addresses(hostname, port))
  284. for af, addr in to_try:
  285. try:
  286. sock = socket.socket(af, socket.SOCK_STREAM)
  287. if timeout is not None:
  288. try:
  289. sock.settimeout(timeout)
  290. except:
  291. pass
  292. retry_on_signal(lambda: sock.connect(addr))
  293. # Break out of the loop on success
  294. break
  295. except socket.error as e:
  296. # Raise anything that isn't a straight up connection error
  297. # (such as a resolution error)
  298. if e.errno not in (ECONNREFUSED, EHOSTUNREACH):
  299. raise
  300. # Capture anything else so we know how the run looks once
  301. # iteration is complete. Retain info about which attempt
  302. # this was.
  303. errors[addr] = e
  304. # Make sure we explode usefully if no address family attempts
  305. # succeeded. We've no way of knowing which error is the "right"
  306. # one, so we construct a hybrid exception containing all the real
  307. # ones, of a subclass that client code should still be watching for
  308. # (socket.error)
  309. if len(errors) == len(to_try):
  310. raise NoValidConnectionsError(errors)
  311. t = self._transport = Transport(
  312. sock, gss_kex=gss_kex, gss_deleg_creds=gss_deleg_creds
  313. )
  314. t.use_compression(compress=compress)
  315. t.set_gss_host(
  316. # t.hostname may be None, but GSS-API requires a target name.
  317. # Therefore use hostname as fallback.
  318. gss_host=gss_host or hostname,
  319. trust_dns=gss_trust_dns,
  320. gssapi_requested=gss_auth or gss_kex,
  321. )
  322. if self._log_channel is not None:
  323. t.set_log_channel(self._log_channel)
  324. if banner_timeout is not None:
  325. t.banner_timeout = banner_timeout
  326. if auth_timeout is not None:
  327. t.auth_timeout = auth_timeout
  328. if port == SSH_PORT:
  329. server_hostkey_name = hostname
  330. else:
  331. server_hostkey_name = "[{}]:{}".format(hostname, port)
  332. our_server_keys = None
  333. our_server_keys = self._system_host_keys.get(server_hostkey_name)
  334. if our_server_keys is None:
  335. our_server_keys = self._host_keys.get(server_hostkey_name)
  336. if our_server_keys is not None:
  337. keytype = our_server_keys.keys()[0]
  338. sec_opts = t.get_security_options()
  339. other_types = [x for x in sec_opts.key_types if x != keytype]
  340. sec_opts.key_types = [keytype] + other_types
  341. t.start_client(timeout=timeout)
  342. # If GSS-API Key Exchange is performed we are not required to check the
  343. # host key, because the host is authenticated via GSS-API / SSPI as
  344. # well as our client.
  345. if not self._transport.gss_kex_used:
  346. server_key = t.get_remote_server_key()
  347. if our_server_keys is None:
  348. # will raise exception if the key is rejected
  349. self._policy.missing_host_key(
  350. self, server_hostkey_name, server_key
  351. )
  352. else:
  353. our_key = our_server_keys.get(server_key.get_name())
  354. if our_key != server_key:
  355. if our_key is None:
  356. our_key = list(our_server_keys.values())[0]
  357. raise BadHostKeyException(hostname, server_key, our_key)
  358. if username is None:
  359. username = getpass.getuser()
  360. if key_filename is None:
  361. key_filenames = []
  362. elif isinstance(key_filename, string_types):
  363. key_filenames = [key_filename]
  364. else:
  365. key_filenames = key_filename
  366. self._auth(
  367. username, password, pkey, key_filenames, allow_agent,
  368. look_for_keys, gss_auth, gss_kex, gss_deleg_creds, t.gss_host,
  369. passphrase,
  370. )
  371. def close(self):
  372. """
  373. Close this SSHClient and its underlying `.Transport`.
  374. .. warning::
  375. Failure to do this may, in some situations, cause your Python
  376. interpreter to hang at shutdown (often due to race conditions).
  377. It's good practice to `close` your client objects anytime you're
  378. done using them, instead of relying on garbage collection.
  379. """
  380. if self._transport is None:
  381. return
  382. self._transport.close()
  383. self._transport = None
  384. if self._agent is not None:
  385. self._agent.close()
  386. self._agent = None
  387. def exec_command(
  388. self,
  389. command,
  390. bufsize=-1,
  391. timeout=None,
  392. get_pty=False,
  393. environment=None,
  394. ):
  395. """
  396. Execute a command on the SSH server. A new `.Channel` is opened and
  397. the requested command is executed. The command's input and output
  398. streams are returned as Python ``file``-like objects representing
  399. stdin, stdout, and stderr.
  400. :param str command: the command to execute
  401. :param int bufsize:
  402. interpreted the same way as by the built-in ``file()`` function in
  403. Python
  404. :param int timeout:
  405. set command's channel timeout. See `.Channel.settimeout`
  406. :param dict environment:
  407. a dict of shell environment variables, to be merged into the
  408. default environment that the remote command executes within.
  409. .. warning::
  410. Servers may silently reject some environment variables; see the
  411. warning in `.Channel.set_environment_variable` for details.
  412. :return:
  413. the stdin, stdout, and stderr of the executing command, as a
  414. 3-tuple
  415. :raises: `.SSHException` -- if the server fails to execute the command
  416. """
  417. chan = self._transport.open_session(timeout=timeout)
  418. if get_pty:
  419. chan.get_pty()
  420. chan.settimeout(timeout)
  421. if environment:
  422. chan.update_environment(environment)
  423. chan.exec_command(command)
  424. stdin = chan.makefile('wb', bufsize)
  425. stdout = chan.makefile('r', bufsize)
  426. stderr = chan.makefile_stderr('r', bufsize)
  427. return stdin, stdout, stderr
  428. def invoke_shell(self, term='vt100', width=80, height=24, width_pixels=0,
  429. height_pixels=0, environment=None):
  430. """
  431. Start an interactive shell session on the SSH server. A new `.Channel`
  432. is opened and connected to a pseudo-terminal using the requested
  433. terminal type and size.
  434. :param str term:
  435. the terminal type to emulate (for example, ``"vt100"``)
  436. :param int width: the width (in characters) of the terminal window
  437. :param int height: the height (in characters) of the terminal window
  438. :param int width_pixels: the width (in pixels) of the terminal window
  439. :param int height_pixels: the height (in pixels) of the terminal window
  440. :param dict environment: the command's environment
  441. :return: a new `.Channel` connected to the remote shell
  442. :raises: `.SSHException` -- if the server fails to invoke a shell
  443. """
  444. chan = self._transport.open_session()
  445. chan.get_pty(term, width, height, width_pixels, height_pixels)
  446. chan.invoke_shell()
  447. return chan
  448. def open_sftp(self):
  449. """
  450. Open an SFTP session on the SSH server.
  451. :return: a new `.SFTPClient` session object
  452. """
  453. return self._transport.open_sftp_client()
  454. def get_transport(self):
  455. """
  456. Return the underlying `.Transport` object for this SSH connection.
  457. This can be used to perform lower-level tasks, like opening specific
  458. kinds of channels.
  459. :return: the `.Transport` for this connection
  460. """
  461. return self._transport
  462. def _key_from_filepath(self, filename, klass, password):
  463. """
  464. Attempt to derive a `.PKey` from given string path ``filename``:
  465. - If ``filename`` appears to be a cert, the matching private key is
  466. loaded.
  467. - Otherwise, the filename is assumed to be a private key, and the
  468. matching public cert will be loaded if it exists.
  469. """
  470. cert_suffix = '-cert.pub'
  471. # Assume privkey, not cert, by default
  472. if filename.endswith(cert_suffix):
  473. key_path = filename[:-len(cert_suffix)]
  474. cert_path = filename
  475. else:
  476. key_path = filename
  477. cert_path = filename + cert_suffix
  478. # Blindly try the key path; if no private key, nothing will work.
  479. key = klass.from_private_key_file(key_path, password)
  480. # TODO: change this to 'Loading' instead of 'Trying' sometime; probably
  481. # when #387 is released, since this is a critical log message users are
  482. # likely testing/filtering for (bah.)
  483. msg = "Trying discovered key {} in {}".format(
  484. hexlify(key.get_fingerprint()), key_path,
  485. )
  486. self._log(DEBUG, msg)
  487. # Attempt to load cert if it exists.
  488. if os.path.isfile(cert_path):
  489. key.load_certificate(cert_path)
  490. self._log(DEBUG, "Adding public certificate {}".format(cert_path))
  491. return key
  492. def _auth(
  493. self, username, password, pkey, key_filenames, allow_agent,
  494. look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host,
  495. passphrase,
  496. ):
  497. """
  498. Try, in order:
  499. - The key(s) passed in, if one was passed in.
  500. - Any key we can find through an SSH agent (if allowed).
  501. - Any "id_rsa", "id_dsa" or "id_ecdsa" key discoverable in ~/.ssh/
  502. (if allowed).
  503. - Plain username/password auth, if a password was given.
  504. (The password might be needed to unlock a private key [if 'passphrase'
  505. isn't also given], or for two-factor authentication [for which it is
  506. required].)
  507. """
  508. saved_exception = None
  509. two_factor = False
  510. allowed_types = set()
  511. two_factor_types = {'keyboard-interactive', 'password'}
  512. if passphrase is None and password is not None:
  513. passphrase = password
  514. # If GSS-API support and GSS-PI Key Exchange was performed, we attempt
  515. # authentication with gssapi-keyex.
  516. if gss_kex and self._transport.gss_kex_used:
  517. try:
  518. self._transport.auth_gssapi_keyex(username)
  519. return
  520. except Exception as e:
  521. saved_exception = e
  522. # Try GSS-API authentication (gssapi-with-mic) only if GSS-API Key
  523. # Exchange is not performed, because if we use GSS-API for the key
  524. # exchange, there is already a fully established GSS-API context, so
  525. # why should we do that again?
  526. if gss_auth:
  527. try:
  528. return self._transport.auth_gssapi_with_mic(
  529. username, gss_host, gss_deleg_creds,
  530. )
  531. except Exception as e:
  532. saved_exception = e
  533. if pkey is not None:
  534. try:
  535. self._log(
  536. DEBUG,
  537. 'Trying SSH key {}'.format(hexlify(pkey.get_fingerprint()))
  538. )
  539. allowed_types = set(
  540. self._transport.auth_publickey(username, pkey))
  541. two_factor = (allowed_types & two_factor_types)
  542. if not two_factor:
  543. return
  544. except SSHException as e:
  545. saved_exception = e
  546. if not two_factor:
  547. for key_filename in key_filenames:
  548. for pkey_class in (RSAKey, DSSKey, ECDSAKey, Ed25519Key):
  549. try:
  550. key = self._key_from_filepath(
  551. key_filename, pkey_class, passphrase,
  552. )
  553. allowed_types = set(
  554. self._transport.auth_publickey(username, key))
  555. two_factor = (allowed_types & two_factor_types)
  556. if not two_factor:
  557. return
  558. break
  559. except SSHException as e:
  560. saved_exception = e
  561. if not two_factor and allow_agent:
  562. if self._agent is None:
  563. self._agent = Agent()
  564. for key in self._agent.get_keys():
  565. try:
  566. id_ = hexlify(key.get_fingerprint())
  567. self._log(DEBUG, 'Trying SSH agent key {}'.format(id_))
  568. # for 2-factor auth a successfully auth'd key password
  569. # will return an allowed 2fac auth method
  570. allowed_types = set(
  571. self._transport.auth_publickey(username, key))
  572. two_factor = (allowed_types & two_factor_types)
  573. if not two_factor:
  574. return
  575. break
  576. except SSHException as e:
  577. saved_exception = e
  578. if not two_factor:
  579. keyfiles = []
  580. for keytype, name in [
  581. (RSAKey, "rsa"),
  582. (DSSKey, "dsa"),
  583. (ECDSAKey, "ecdsa"),
  584. (Ed25519Key, "ed25519"),
  585. ]:
  586. # ~/ssh/ is for windows
  587. for directory in [".ssh", "ssh"]:
  588. full_path = os.path.expanduser(
  589. "~/{}/id_{}".format(directory, name)
  590. )
  591. if os.path.isfile(full_path):
  592. # TODO: only do this append if below did not run
  593. keyfiles.append((keytype, full_path))
  594. if os.path.isfile(full_path + '-cert.pub'):
  595. keyfiles.append((keytype, full_path + '-cert.pub'))
  596. if not look_for_keys:
  597. keyfiles = []
  598. for pkey_class, filename in keyfiles:
  599. try:
  600. key = self._key_from_filepath(
  601. filename, pkey_class, passphrase,
  602. )
  603. # for 2-factor auth a successfully auth'd key will result
  604. # in ['password']
  605. allowed_types = set(
  606. self._transport.auth_publickey(username, key))
  607. two_factor = (allowed_types & two_factor_types)
  608. if not two_factor:
  609. return
  610. break
  611. except (SSHException, IOError) as e:
  612. saved_exception = e
  613. if password is not None:
  614. try:
  615. self._transport.auth_password(username, password)
  616. return
  617. except SSHException as e:
  618. saved_exception = e
  619. elif two_factor:
  620. try:
  621. self._transport.auth_interactive_dumb(username)
  622. return
  623. except SSHException as e:
  624. saved_exception = e
  625. # if we got an auth-failed exception earlier, re-raise it
  626. if saved_exception is not None:
  627. raise saved_exception
  628. raise SSHException('No authentication methods available')
  629. def _log(self, level, msg):
  630. self._transport._log(level, msg)
  631. class MissingHostKeyPolicy (object):
  632. """
  633. Interface for defining the policy that `.SSHClient` should use when the
  634. SSH server's hostname is not in either the system host keys or the
  635. application's keys. Pre-made classes implement policies for automatically
  636. adding the key to the application's `.HostKeys` object (`.AutoAddPolicy`),
  637. and for automatically rejecting the key (`.RejectPolicy`).
  638. This function may be used to ask the user to verify the key, for example.
  639. """
  640. def missing_host_key(self, client, hostname, key):
  641. """
  642. Called when an `.SSHClient` receives a server key for a server that
  643. isn't in either the system or local `.HostKeys` object. To accept
  644. the key, simply return. To reject, raised an exception (which will
  645. be passed to the calling application).
  646. """
  647. pass
  648. class AutoAddPolicy (MissingHostKeyPolicy):
  649. """
  650. Policy for automatically adding the hostname and new host key to the
  651. local `.HostKeys` object, and saving it. This is used by `.SSHClient`.
  652. """
  653. def missing_host_key(self, client, hostname, key):
  654. client._host_keys.add(hostname, key.get_name(), key)
  655. if client._host_keys_filename is not None:
  656. client.save_host_keys(client._host_keys_filename)
  657. client._log(DEBUG, 'Adding {} host key for {}: {}'.format(
  658. key.get_name(), hostname, hexlify(key.get_fingerprint()),
  659. ))
  660. class RejectPolicy (MissingHostKeyPolicy):
  661. """
  662. Policy for automatically rejecting the unknown hostname & key. This is
  663. used by `.SSHClient`.
  664. """
  665. def missing_host_key(self, client, hostname, key):
  666. client._log(DEBUG, 'Rejecting {} host key for {}: {}'.format(
  667. key.get_name(), hostname, hexlify(key.get_fingerprint()),
  668. ))
  669. raise SSHException(
  670. 'Server {!r} not found in known_hosts'.format(hostname)
  671. )
  672. class WarningPolicy (MissingHostKeyPolicy):
  673. """
  674. Policy for logging a Python-style warning for an unknown host key, but
  675. accepting it. This is used by `.SSHClient`.
  676. """
  677. def missing_host_key(self, client, hostname, key):
  678. warnings.warn('Unknown {} host key for {}: {}'.format(
  679. key.get_name(), hostname, hexlify(key.get_fingerprint()),
  680. ))

Powered by TurnKey Linux.