client.py 31 KB

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