Debian Codegraph @

tests/test_client.py

raw
1 # Copyright (C) 2003-2009 Robey Pointer <[email protected]>
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 """
20 Some unit tests for SSHClient.
21 """
22
23 import gc
24 import os
25 import platform
26 import socket
27 import threading
28 import time
29 import unittest
30 import warnings
31 import weakref
32 from tempfile import mkstemp
33 from unittest.mock import patch
34
35 import pytest
36 from pytest_relaxed import raises
37
38 import paramiko
39 from paramiko import SSHClient
40 from paramiko.pkey import PublicBlob
41 from paramiko.ssh_exception import AuthenticationException, SSHException
42
43 from ._util import _support, slow
44
45 FINGERPRINTS = {
46 # TODO: this should still be ok as it's specifically re: key
47 # type/identity.
48 "ssh-rsa": b"\x60\x73\x38\x44\xcb\x51\x86\x65\x7f\xde\xda\xa2\x2b\x5a\x57\xd5", # noqa
49 "ecdsa-sha2-nistp256": b"\x25\x19\xeb\x55\xe6\xa1\x47\xff\x4f\x38\xd2\x75\x6f\xa5\xd5\x60", # noqa
50 "ssh-ed25519": b'\xb3\xd5"\xaa\xf9u^\xe8\xcd\x0e\xea\x02\xb9)\xa2\x80',
51 }
52
53
54 class NullServer(paramiko.ServerInterface):
55 def __init__(self, *args, **kwargs):
56 # Allow tests to enable/disable specific key types
57 self.__allowed_keys = kwargs.pop("allowed_keys", [])
58 # And allow them to set a (single...meh) expected public blob (cert)
59 self.__expected_public_blob = kwargs.pop("public_blob", None)
60 super().__init__(*args, **kwargs)
61
62 def get_allowed_auths(self, username):
63 if username == "slowdive":
64 return "publickey,password"
65 return "publickey"
66
67 def check_auth_password(self, username, password):
68 if (username == "slowdive") and (password == "pygmalion"):
69 return paramiko.AUTH_SUCCESSFUL
70 if (username == "slowdive") and (password == "unresponsive-server"):
71 time.sleep(5)
72 return paramiko.AUTH_SUCCESSFUL
73 return paramiko.AUTH_FAILED
74
75 def check_auth_publickey(self, username, key):
76 try:
77 expected = FINGERPRINTS[key.get_name()]
78 except KeyError:
79 return paramiko.AUTH_FAILED
80 # Base check: allowed auth type & fingerprint matches
81 happy = (
82 key.get_name() in self.__allowed_keys
83 and key.get_fingerprint() == expected
84 )
85 # Secondary check: if test wants assertions about cert data
86 if (
87 self.__expected_public_blob is not None
88 and key.public_blob != self.__expected_public_blob
89 ):
90 happy = False
91 return paramiko.AUTH_SUCCESSFUL if happy else paramiko.AUTH_FAILED
92
93 def check_channel_request(self, kind, chanid):
94 return paramiko.OPEN_SUCCEEDED
95
96 def check_channel_exec_request(self, channel, command):
97 if command != b"yes":
98 return False
99 return True
100
101 def check_channel_env_request(self, channel, name, value):
102 if name == "INVALID_ENV":
103 return False
104
105 if not hasattr(channel, "env"):
106 setattr(channel, "env", {})
107
108 channel.env[name] = value
109 return True
110
111
112 class ClientTest(unittest.TestCase):
113 def setUp(self):
114 self.sockl = socket.socket()
115 self.sockl.bind(("localhost", 0))
116 self.sockl.listen(1)
117 self.addr, self.port = self.sockl.getsockname()
118 self.connect_kwargs = dict(
119 hostname=self.addr,
120 port=self.port,
121 username="slowdive",
122 look_for_keys=False,
123 )
124 self.event = threading.Event()
125 self.kill_event = threading.Event()
126 host_key = paramiko.RSAKey.from_private_key_file(_support("rsa.key"))
127 self.public_host_key = paramiko.RSAKey(data=host_key.asbytes())
128
129 def tearDown(self):
130 # Shut down client Transport
131 if hasattr(self, "tc"):
132 self.tc.close()
133 # Shut down shared socket
134 if hasattr(self, "sockl"):
135 # Signal to server thread that it should shut down early; it checks
136 # this immediately after accept(). (In scenarios where connection
137 # actually succeeded during the test, this becomes a no-op.)
138 self.kill_event.set()
139 # Forcibly connect to server sock in case the server thread is
140 # hanging out in its accept() (e.g. if the client side of the test
141 # fails before it even gets to connecting); there's no other good
142 # way to force an accept() to exit.
143 put_a_sock_in_it = socket.socket()
144 put_a_sock_in_it.connect((self.addr, self.port))
145 put_a_sock_in_it.close()
146 # Then close "our" end of the socket (which _should_ cause the
147 # accept() to bail out, but does not, for some reason. I blame
148 # threading.)
149 self.sockl.close()
150
151 def _run(
152 self,
153 allowed_keys=None,
154 delay=0,
155 public_blob=None,
156 kill_event=None,
157 server_name=None,
158 ):
159 if allowed_keys is None:
160 allowed_keys = FINGERPRINTS.keys()
161 self.socks, addr = self.sockl.accept()
162 # If the kill event was set at this point, it indicates an early
163 # shutdown, so bail out now and don't even try setting up a Transport
164 # (which will just verbosely die.)
165 if kill_event and kill_event.is_set():
166 self.socks.close()
167 return
168 self.ts = paramiko.Transport(self.socks)
169 if server_name is not None:
170 self.ts.local_version = server_name
171 keypath = _support("rsa.key")
172 host_key = paramiko.RSAKey.from_private_key_file(keypath)
173 self.ts.add_server_key(host_key)
174 keypath = _support("ecdsa-256.key")
175 host_key = paramiko.ECDSAKey.from_private_key_file(keypath)
176 self.ts.add_server_key(host_key)
177 server = NullServer(allowed_keys=allowed_keys, public_blob=public_blob)
178 if delay:
179 time.sleep(delay)
180 self.ts.start_server(self.event, server)
181
182 def _test_connection(self, **kwargs):
183 """
184 (Most) kwargs get passed directly into SSHClient.connect().
185
186 The exceptions are ``allowed_keys``/``public_blob``/``server_name``
187 which are stripped and handed to the ``NullServer`` used for testing.
188 """
189 run_kwargs = {"kill_event": self.kill_event}
190 for key in ("allowed_keys", "public_blob", "server_name"):
191 run_kwargs[key] = kwargs.pop(key, None)
192 # Server setup
193 threading.Thread(target=self._run, kwargs=run_kwargs).start()
194
195 # Client setup
196 self.tc = SSHClient()
197 # Pretend we have a known_hosts file or similar
198 self.tc.get_host_keys().add(
199 f"[{self.addr}]:{self.port}",
200 # TODO: so, this is 'keytype', which is still allowed to be
201 # ssh-rsa, as it "comes from the key itself" per `man sshd`.
202 # TODO: but q is, is part of our pipeline still conflating keytype
203 # with signature algorithm? seems likely?
204 "ssh-rsa",
205 self.public_host_key,
206 )
207
208 # Actual connection
209 self.tc.connect(**dict(self.connect_kwargs, **kwargs))
210
211 # Authentication successful?
212 self.event.wait(1.0)
213 self.assertTrue(self.event.is_set())
214 self.assertTrue(self.ts.is_active())
215 self.assertEqual(
216 self.connect_kwargs["username"], self.ts.get_username()
217 )
218 self.assertEqual(True, self.ts.is_authenticated())
219
220 # Command execution functions?
221 stdin, stdout, stderr = self.tc.exec_command("yes")
222 schan = self.ts.accept(1.0)
223
224 # Nobody else tests the API of exec_command so let's do it here for
225 # now. :weary:
226 assert isinstance(stdin, paramiko.ChannelStdinFile)
227 assert isinstance(stdout, paramiko.ChannelFile)
228 assert isinstance(stderr, paramiko.ChannelStderrFile)
229
230 schan.send("Hello there.\n")
231 schan.send_stderr("This is on stderr.\n")
232 schan.close()
233
234 self.assertEqual("Hello there.\n", stdout.readline())
235 self.assertEqual("", stdout.readline())
236 self.assertEqual("This is on stderr.\n", stderr.readline())
237 self.assertEqual("", stderr.readline())
238
239 # Cleanup
240 stdin.close()
241 stdout.close()
242 stderr.close()
243
244
245 class SSHClientTest(ClientTest):
246 def test_client(self):
247 """
248 verify that the SSHClient stuff works too.
249 """
250 self._test_connection(password="pygmalion")
251
252 def test_client_rsa(self):
253 """
254 verify that SSHClient works with an RSA key.
255 """
256 self._test_connection(key_filename=_support("rsa.key"))
257
258 def test_client_ecdsa(self):
259 """
260 verify that SSHClient works with an ECDSA key.
261 """
262 self._test_connection(key_filename=_support("ecdsa-256.key"))
263
264 def test_client_ed25519(self):
265 self._test_connection(key_filename=_support("ed25519.key"))
266
267 def test_multiple_key_files(self):
268 """
269 verify that SSHClient accepts and tries multiple key files.
270 """
271 # This is dumb :(
272 types_ = {
273 # TODO: this is just about key identity so should be ok
274 "rsa": "ssh-rsa",
275 "ed25519": "ssh-ed25519",
276 "ecdsa": "ecdsa-sha2-nistp256",
277 }
278 # Various combos of attempted & valid keys
279 # TODO: try every possible combo using itertools functions
280 # TODO: use new key(s) fixture(s)
281 for attempt, accept in (
282 (
283 ["rsa", "ed25519"],
284 ["ed25519"],
285 ), # Original test #3 (but s/DSA/Ed25519/)
286 (
287 ["ed25519", "rsa"],
288 ["ed25519"],
289 ), # Ordering matters sometimes, sadly
290 (
291 ["ed25519", "rsa", "ecdsa-256"],
292 ["ed25519"],
293 ), # Try ECDSA but fail
294 (["rsa", "ecdsa-256"], ["ecdsa"]), # ECDSA success
295 ):
296 try:
297 self._test_connection(
298 key_filename=[
299 _support("{}.key".format(x)) for x in attempt
300 ],
301 allowed_keys=[types_[x] for x in accept],
302 )
303 finally:
304 # Clean up to avoid occasional gc-related deadlocks.
305 # TODO: use nose test generators after nose port
306 self.tearDown()
307 self.setUp()
308
309 def test_multiple_key_files_failure(self):
310 """
311 Expect failure when multiple keys in play and none are accepted
312 """
313 # Until #387 is fixed we have to catch a high-up exception since
314 # various platforms trigger different errors here >_<
315 self.assertRaises(
316 SSHException,
317 self._test_connection,
318 key_filename=[_support("rsa.key")],
319 allowed_keys=["ecdsa-sha2-nistp256"],
320 )
321
322 def test_certs_allowed_as_key_filename_values(self):
323 # NOTE: giving cert path here, not key path. (Key path test is below.
324 # They're similar except for which path is given; the expected auth and
325 # server-side behavior is 100% identical.)
326 # NOTE: only bothered whipping up one cert per overall class/family.
327 for type_ in ("rsa", "ecdsa-256", "ed25519"):
328 key_path = _support(f"{type_}.key")
329 self._test_connection(
330 key_filename=key_path,
331 public_blob=PublicBlob.from_file(f"{key_path}-cert.pub"),
332 )
333
334 def test_certs_implicitly_loaded_alongside_key_filename_keys(self):
335 # NOTE: a regular test_connection() w/ rsa.key would incidentally
336 # test this (because test_xxx.key-cert.pub exists) but incidental tests
337 # stink, so NullServer and friends were updated to allow assertions
338 # about the server-side key object's public blob. Thus, we can prove
339 # that a specific cert was found, along with regular authorization
340 # succeeding proving that the overall flow works.
341 for type_ in ("rsa", "ecdsa-256", "ed25519"):
342 key_path = _support(f"{type_}.key")
343 self._test_connection(
344 key_filename=key_path,
345 public_blob=PublicBlob.from_file(f"{key_path}-cert.pub"),
346 )
347
348 def test_default_key_locations_trigger_cert_loads_if_found(self):
349 # TODO: what it says on the tin: ~/.ssh/id_rsa tries to load
350 # ~/.ssh/id_rsa-cert.pub. Right now no other tests actually test that
351 # code path (!) so we're punting too, sob.
352 pytest.skip()
353
354 def test_auto_add_policy(self):
355 """
356 verify that SSHClient's AutoAddPolicy works.
357 """
358 threading.Thread(target=self._run).start()
359 hostname = f"[{self.addr}]:{self.port}"
360 key_file = _support("ecdsa-256.key")
361 public_host_key = paramiko.ECDSAKey.from_private_key_file(key_file)
362
363 self.tc = SSHClient()
364 self.tc.set_missing_host_key_policy(paramiko.AutoAddPolicy())
365 self.assertEqual(0, len(self.tc.get_host_keys()))
366 self.tc.connect(password="pygmalion", **self.connect_kwargs)
367
368 self.event.wait(1.0)
369 self.assertTrue(self.event.is_set())
370 self.assertTrue(self.ts.is_active())
371 self.assertEqual("slowdive", self.ts.get_username())
372 self.assertEqual(True, self.ts.is_authenticated())
373 self.assertEqual(1, len(self.tc.get_host_keys()))
374 new_host_key = list(self.tc.get_host_keys()[hostname].values())[0]
375 self.assertEqual(public_host_key, new_host_key)
376
377 def test_save_host_keys(self):
378 """
379 verify that SSHClient correctly saves a known_hosts file.
380 """
381 warnings.filterwarnings("ignore", "tempnam.*")
382
383 host_key = paramiko.RSAKey.from_private_key_file(_support("rsa.key"))
384 public_host_key = paramiko.RSAKey(data=host_key.asbytes())
385 fd, localname = mkstemp()
386 os.close(fd)
387
388 client = SSHClient()
389 assert len(client.get_host_keys()) == 0
390
391 host_id = f"[{self.addr}]:{self.port}"
392
393 # TODO: this should still be okay, host keys -> keytype -> is not
394 # directly tied to algo -> but need to see if guts do that
395 client.get_host_keys().add(host_id, "ssh-rsa", public_host_key)
396 assert len(client.get_host_keys()) == 1
397 assert public_host_key == client.get_host_keys()[host_id]["ssh-rsa"]
398
399 client.save_host_keys(localname)
400
401 with open(localname) as fd:
402 assert host_id in fd.read()
403
404 os.unlink(localname)
405
406 def test_cleanup(self):
407 """
408 verify that when an SSHClient is collected, its transport (and the
409 transport's packetizer) is closed.
410 """
411 # Skipped on PyPy because it fails on CI for unknown reasons
412 if platform.python_implementation() == "PyPy":
413 return
414
415 threading.Thread(target=self._run).start()
416
417 self.tc = SSHClient()
418 self.tc.set_missing_host_key_policy(paramiko.AutoAddPolicy())
419 assert len(self.tc.get_host_keys()) == 0
420 self.tc.connect(**dict(self.connect_kwargs, password="pygmalion"))
421
422 self.event.wait(1.0)
423 assert self.event.is_set()
424 assert self.ts.is_active()
425
426 p = weakref.ref(self.tc._transport.packetizer)
427 assert p() is not None
428 self.tc.close()
429 del self.tc
430
431 # force a collection to see whether the SSHClient object is deallocated
432 # 2 GCs are needed on PyPy, time is needed for Python 3
433 # TODO (backwards incompat): this still fails randomly under CircleCI
434 # under Python 3.7,
435 # 3.8 at the very least. bumped sleep 0.3->1.0s but the underlying
436 # functionality should get reevaluated now we've dropped Python 2.
437 time.sleep(1)
438 gc.collect()
439 gc.collect()
440
441 assert p() is None
442
443 @patch("paramiko.client.socket.socket")
444 @patch("paramiko.client.socket.getaddrinfo")
445 def test_closes_socket_on_socket_errors(self, getaddrinfo, mocket):
446 getaddrinfo.return_value = (
447 ("irrelevant", None, None, None, "whatever"),
448 )
449
450 class SocksToBeYou(socket.error):
451 pass
452
453 my_socket = mocket.return_value
454 my_socket.connect.side_effect = SocksToBeYou
455 client = SSHClient()
456 with pytest.raises(SocksToBeYou):
457 client.connect(hostname="nope")
458 my_socket.close.assert_called_once_with()
459
460 def test_client_can_be_used_as_context_manager(self):
461 """
462 verify that an SSHClient can be used a context manager
463 """
464 threading.Thread(target=self._run).start()
465
466 with SSHClient() as tc:
467 self.tc = tc
468 self.tc.set_missing_host_key_policy(paramiko.AutoAddPolicy())
469 assert len(self.tc.get_host_keys()) == 0
470 self.tc.connect(**dict(self.connect_kwargs, password="pygmalion"))
471
472 self.event.wait(1.0)
473 self.assertTrue(self.event.is_set())
474 self.assertTrue(self.ts.is_active())
475
476 self.assertTrue(self.tc._transport is not None)
477
478 self.assertTrue(self.tc._transport is None)
479
480 def test_banner_timeout(self):
481 """
482 verify that the SSHClient has a configurable banner timeout.
483 """
484 # Start the thread with a 1 second wait.
485 threading.Thread(target=self._run, kwargs={"delay": 1}).start()
486 host_key = paramiko.RSAKey.from_private_key_file(_support("rsa.key"))
487 public_host_key = paramiko.RSAKey(data=host_key.asbytes())
488
489 self.tc = SSHClient()
490 self.tc.get_host_keys().add(
491 f"[{self.addr}]:{self.port}",
492 # TODO: hostkey keytype == ok-ish
493 "ssh-rsa",
494 public_host_key,
495 )
496 # Connect with a half second banner timeout.
497 kwargs = dict(self.connect_kwargs, banner_timeout=0.5)
498 self.assertRaises(paramiko.SSHException, self.tc.connect, **kwargs)
499
500 def test_auth_trickledown(self):
501 """
502 Failed key auth doesn't prevent subsequent pw auth from succeeding
503 """
504 # NOTE: re #387, re #394
505 # If pkey module used within Client._auth isn't correctly handling auth
506 # errors (e.g. if it allows things like ValueError to bubble up as per
507 # midway through #394) client.connect() will fail (at key load step)
508 # instead of succeeding (at password step)
509 kwargs = dict(
510 # Password-protected key whose passphrase is not 'pygmalion' (it's
511 # 'television' as per tests/test_pkey.py). NOTE: must use
512 # key_filename, loading the actual key here with PKey will except
513 # immediately; we're testing the try/except crap within Client.
514 key_filename=[_support("test_rsa_password.key")],
515 # Actual password for default 'slowdive' user
516 password="pygmalion",
517 )
518 self._test_connection(**kwargs)
519
520 @slow
521 def test_auth_timeout(self):
522 """
523 verify that the SSHClient has a configurable auth timeout
524 """
525 # Connect with a half second auth timeout
526 self.assertRaises(
527 AuthenticationException,
528 self._test_connection,
529 password="unresponsive-server",
530 auth_timeout=0.5,
531 )
532
533 @patch.object(
534 paramiko.Channel,
535 "_set_remote_channel",
536 lambda *args, **kwargs: time.sleep(100),
537 )
538 def test_channel_timeout(self):
539 """
540 verify that the SSHClient has a configurable channel timeout
541 """
542 threading.Thread(target=self._run).start()
543 # Client setup
544 self.tc = SSHClient()
545 self.tc.set_missing_host_key_policy(paramiko.AutoAddPolicy())
546
547 # Actual connection
548 self.tc.connect(
549 **dict(
550 self.connect_kwargs, password="pygmalion", channel_timeout=0.5
551 )
552 )
553 self.event.wait(1.0)
554
555 self.assertRaises(paramiko.SSHException, self.tc.open_sftp)
556
557 def test_reject_policy(self):
558 """
559 verify that SSHClient's RejectPolicy works.
560 """
561 threading.Thread(target=self._run).start()
562
563 self.tc = SSHClient()
564 self.tc.set_missing_host_key_policy(paramiko.RejectPolicy())
565 self.assertEqual(0, len(self.tc.get_host_keys()))
566 self.assertRaises(
567 paramiko.SSHException,
568 self.tc.connect,
569 password="pygmalion",
570 **self.connect_kwargs,
571 )
572
573 def _client_host_key_bad(self, host_key):
574 threading.Thread(target=self._run).start()
575 hostname = f"[{self.addr}]:{self.port}"
576
577 self.tc = SSHClient()
578 self.tc.set_missing_host_key_policy(paramiko.WarningPolicy())
579 known_hosts = self.tc.get_host_keys()
580 known_hosts.add(hostname, host_key.get_name(), host_key)
581
582 self.assertRaises(
583 paramiko.BadHostKeyException,
584 self.tc.connect,
585 password="pygmalion",
586 **self.connect_kwargs,
587 )
588
589 def _client_host_key_good(self, ktype, kfile):
590 threading.Thread(target=self._run).start()
591 hostname = f"[{self.addr}]:{self.port}"
592
593 self.tc = SSHClient()
594 self.tc.set_missing_host_key_policy(paramiko.RejectPolicy())
595 host_key = ktype.from_private_key_file(_support(kfile))
596 known_hosts = self.tc.get_host_keys()
597 known_hosts.add(hostname, host_key.get_name(), host_key)
598
599 self.tc.connect(password="pygmalion", **self.connect_kwargs)
600 self.event.wait(1.0)
601 self.assertTrue(self.event.is_set())
602 self.assertTrue(self.ts.is_active())
603 self.assertEqual(True, self.ts.is_authenticated())
604
605 def test_host_key_negotiation_1(self):
606 host_key = paramiko.ECDSAKey.generate()
607 self._client_host_key_bad(host_key)
608
609 def test_host_key_negotiation_2(self):
610 # TODO: this may now be too small for audit recco, dlbcheck
611 host_key = paramiko.RSAKey.generate(2048)
612 self._client_host_key_bad(host_key)
613
614 def test_host_key_negotiation_3(self):
615 self._client_host_key_good(paramiko.ECDSAKey, "ecdsa-256.key")
616
617 def test_host_key_negotiation_4(self):
618 self._client_host_key_good(paramiko.RSAKey, "rsa.key")
619
620 def _setup_for_env(self):
621 threading.Thread(target=self._run).start()
622
623 self.tc = SSHClient()
624 self.tc.set_missing_host_key_policy(paramiko.AutoAddPolicy())
625 self.assertEqual(0, len(self.tc.get_host_keys()))
626 self.tc.connect(
627 self.addr, self.port, username="slowdive", password="pygmalion"
628 )
629
630 self.event.wait(1.0)
631 self.assertTrue(self.event.is_set())
632 self.assertTrue(self.ts.is_active())
633
634 def test_update_environment(self):
635 """
636 Verify that environment variables can be set by the client.
637 """
638 self._setup_for_env()
639 target_env = {b"A": b"B", b"C": b"d"}
640
641 self.tc.exec_command("yes", environment=target_env)
642 schan = self.ts.accept(1.0)
643 self.assertEqual(target_env, getattr(schan, "env", {}))
644 schan.close()
645
646 @unittest.skip("Clients normally fail silently, thus so do we, for now")
647 def test_env_update_failures(self):
648 self._setup_for_env()
649 with self.assertRaises(SSHException) as manager:
650 # Verify that a rejection by the server can be detected
651 self.tc.exec_command("yes", environment={b"INVALID_ENV": b""})
652 self.assertTrue(
653 "INVALID_ENV" in str(manager.exception),
654 "Expected variable name in error message",
655 )
656 self.assertTrue(
657 isinstance(manager.exception.args[1], SSHException),
658 "Expected original SSHException in exception",
659 )
660
661 def test_missing_key_policy_accepts_classes_or_instances(self):
662 """
663 Client.missing_host_key_policy() can take classes or instances.
664 """
665 # AN ACTUAL UNIT TEST?! GOOD LORD
666 # (But then we have to test a private API...meh.)
667 client = SSHClient()
668 # Default
669 assert isinstance(client._policy, paramiko.RejectPolicy)
670 # Hand in an instance (classic behavior)
671 client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
672 assert isinstance(client._policy, paramiko.AutoAddPolicy)
673 # Hand in just the class (new behavior)
674 client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
675 assert isinstance(client._policy, paramiko.AutoAddPolicy)
676
677 def test_disabled_algorithms_defaults_to_None(self):
678 self._test_connection(password="pygmalion")
679 assert self.tc._transport.disabled_algorithms == {}
680
681 def test_disabled_algorithms_passed_directly_if_given(self):
682 self._test_connection(
683 password="pygmalion", disabled_algorithms={"keys": ["ed25519"]}
684 )
685 assert self.tc._transport.disabled_algorithms == {"keys": ["ed25519"]}
686
687 def test_transport_factory_defaults_to_Transport(self):
688 self._test_connection(password="pygmalion")
689 assert isinstance(self.tc._transport, paramiko.Transport)
690
691 def test_transport_factory_may_be_specified(self):
692 class MyTransport(paramiko.Transport):
693 pass
694
695 self._test_connection(
696 password="pygmalion", transport_factory=MyTransport
697 )
698 assert isinstance(self.tc._transport, MyTransport)
699
700
701 class PasswordPassphraseTests(ClientTest):
702 # TODO: most of these could reasonably be set up to use mocks/assertions
703 # (e.g. "gave passphrase -> expect PKey was given it as the passphrase")
704 # instead of suffering a real connection cycle.
705 # TODO: in that case, move the below to be part of an integration suite?
706
707 def test_password_kwarg_works_for_password_auth(self):
708 # Straightforward / duplicate of earlier basic password test.
709 self._test_connection(password="pygmalion")
710
711 # TODO: more granular exception pending #387; should be signaling "no auth
712 # methods available" because no key and no password
713 @raises(SSHException)
714 def test_passphrase_kwarg_not_used_for_password_auth(self):
715 # Using the "right" password in the "wrong" field shouldn't work.
716 self._test_connection(passphrase="pygmalion")
717
718 def test_passphrase_kwarg_used_for_key_passphrase(self):
719 # Straightforward again, with new passphrase kwarg.
720 self._test_connection(
721 key_filename=_support("test_rsa_password.key"),
722 passphrase="television",
723 )
724
725 def test_password_kwarg_used_for_passphrase_when_no_passphrase_kwarg_given(
726 self,
727 ): # noqa
728 # Backwards compatibility: passphrase in the password field.
729 self._test_connection(
730 key_filename=_support("test_rsa_password.key"),
731 password="television",
732 )
733
734 @raises(AuthenticationException) # TODO: more granular
735 def test_password_kwarg_not_used_for_passphrase_when_passphrase_kwarg_given( # noqa
736 self,
737 ):
738 # Sanity: if we're given both fields, the password field is NOT used as
739 # a passphrase.
740 self._test_connection(
741 key_filename=_support("test_rsa_password.key"),
742 password="television",
743 passphrase="wat? lol no",
744 )