| 1 |
""" |
| 2 |
Tests focusing primarily on the authentication step. |
| 3 |
|
| 4 |
Thus, they concern AuthHandler and AuthStrategy, with a side of Transport. |
| 5 |
""" |
| 6 |
|
| 7 |
from logging import Logger |
| 8 |
from unittest.mock import Mock |
| 9 |
|
| 10 |
from pytest import raises |
| 11 |
|
| 12 |
from paramiko import ( |
| 13 |
AgentKey, |
| 14 |
AuthenticationException, |
| 15 |
AuthFailure, |
| 16 |
AuthResult, |
| 17 |
AuthSource, |
| 18 |
AuthStrategy, |
| 19 |
BadAuthenticationType, |
| 20 |
Ed25519Key, |
| 21 |
InMemoryPrivateKey, |
| 22 |
NoneAuth, |
| 23 |
OnDiskPrivateKey, |
| 24 |
Password, |
| 25 |
PKey, |
| 26 |
PrivateKey, |
| 27 |
RSAKey, |
| 28 |
SourceResult, |
| 29 |
SSHException, |
| 30 |
) |
| 31 |
|
| 32 |
from ._util import ( |
| 33 |
_support, |
| 34 |
server, |
| 35 |
unicodey, |
| 36 |
) |
| 37 |
|
| 38 |
|
| 39 |
class AuthHandler_: |
| 40 |
""" |
| 41 |
Most of these tests are explicit about the auth method they call. |
| 42 |
|
| 43 |
This is because not too many other tests do so (they rely on the implicit |
| 44 |
auth trigger of various connect() kwargs). |
| 45 |
""" |
| 46 |
|
| 47 |
def bad_auth_type(self): |
| 48 |
""" |
| 49 |
verify that we get the right exception when an unsupported auth |
| 50 |
type is requested. |
| 51 |
""" |
| 52 |
# Server won't allow password auth for this user, so should fail |
| 53 |
# and return just publickey allowed types |
| 54 |
with server( |
| 55 |
connect=dict(username="unknown", password="error"), |
| 56 |
catch_error=True, |
| 57 |
) as (_, _, err): |
| 58 |
assert isinstance(err, BadAuthenticationType) |
| 59 |
assert err.allowed_types == ["publickey"] |
| 60 |
|
| 61 |
def bad_password(self): |
| 62 |
""" |
| 63 |
verify that a bad password gets the right exception, and that a retry |
| 64 |
with the right password works. |
| 65 |
""" |
| 66 |
# NOTE: Transport.connect doesn't do any auth upfront if no userauth |
| 67 |
# related kwargs given. |
| 68 |
with server(defer=True) as (tc, ts): |
| 69 |
# Auth once, badly |
| 70 |
with raises(AuthenticationException): |
| 71 |
tc.auth_password(username="slowdive", password="error") |
| 72 |
# And again, correctly |
| 73 |
tc.auth_password(username="slowdive", password="pygmalion") |
| 74 |
|
| 75 |
def multipart_auth(self): |
| 76 |
""" |
| 77 |
verify that multipart auth works. |
| 78 |
""" |
| 79 |
with server(defer=True) as (tc, ts): |
| 80 |
assert tc.auth_password( |
| 81 |
username="paranoid", password="paranoid" |
| 82 |
) == ["publickey"] |
| 83 |
key = Ed25519Key.from_private_key_file(_support("ed25519.key")) |
| 84 |
assert tc.auth_publickey(username="paranoid", key=key) == [] |
| 85 |
|
| 86 |
def interactive_auth(self): |
| 87 |
""" |
| 88 |
verify keyboard-interactive auth works. |
| 89 |
""" |
| 90 |
|
| 91 |
def handler(title, instructions, prompts): |
| 92 |
self.got_title = title |
| 93 |
self.got_instructions = instructions |
| 94 |
self.got_prompts = prompts |
| 95 |
return ["cat"] |
| 96 |
|
| 97 |
with server(defer=True) as (tc, ts): |
| 98 |
assert tc.auth_interactive("commie", handler) == [] |
| 99 |
assert self.got_title == "password" |
| 100 |
assert self.got_prompts == [("Password", False)] |
| 101 |
|
| 102 |
def interactive_fallback(self): |
| 103 |
""" |
| 104 |
verify that a password auth attempt will fallback to "interactive" |
| 105 |
if password auth isn't supported but interactive is. |
| 106 |
""" |
| 107 |
with server(defer=True) as (tc, ts): |
| 108 |
# This username results in an allowed_auth of just kbd-int, |
| 109 |
# and has a configured interactive->response on the server. |
| 110 |
assert tc.auth_password("commie", "cat") == [] |
| 111 |
|
| 112 |
def utf8(self): |
| 113 |
""" |
| 114 |
verify that utf-8 encoding happens in authentication. |
| 115 |
""" |
| 116 |
with server(defer=True) as (tc, ts): |
| 117 |
assert tc.auth_password("utf8", unicodey) == [] |
| 118 |
|
| 119 |
def non_utf8(self): |
| 120 |
""" |
| 121 |
verify that non-utf-8 encoded passwords can be used for broken |
| 122 |
servers. |
| 123 |
""" |
| 124 |
with server(defer=True) as (tc, ts): |
| 125 |
assert tc.auth_password("non-utf8", "\xff") == [] |
| 126 |
|
| 127 |
def auth_exception_when_disconnected(self): |
| 128 |
""" |
| 129 |
verify that we catch a server disconnecting during auth, and report |
| 130 |
it as an auth failure. |
| 131 |
""" |
| 132 |
with ( |
| 133 |
server(defer=True, skip_verify=True) as (tc, ts), |
| 134 |
raises(AuthenticationException), |
| 135 |
): |
| 136 |
tc.auth_password("bad-server", "hello") |
| 137 |
|
| 138 |
def non_responsive_triggers_auth_exception(self): |
| 139 |
""" |
| 140 |
verify that authentication times out if server takes to long to |
| 141 |
respond (or never responds). |
| 142 |
""" |
| 143 |
with ( |
| 144 |
server(defer=True, skip_verify=True) as (tc, ts), |
| 145 |
raises(AuthenticationException) as info, |
| 146 |
): |
| 147 |
tc.auth_timeout = 1 # 1 second, to speed up test |
| 148 |
tc.auth_password("unresponsive-server", "hello") |
| 149 |
assert "Authentication timeout" in str(info.value) |
| 150 |
|
| 151 |
|
| 152 |
class SHA2SignaturePubkeys: |
| 153 |
def pubkey_auth_honors_disabled_algorithms(self): |
| 154 |
privkey = RSAKey.from_private_key_file(_support("rsa.key")) |
| 155 |
with server( |
| 156 |
pubkeys=[privkey], |
| 157 |
connect=dict(pkey=privkey), |
| 158 |
init=dict( |
| 159 |
disabled_algorithms=dict( |
| 160 |
pubkeys=["rsa-sha2-256", "rsa-sha2-512"] |
| 161 |
) |
| 162 |
), |
| 163 |
catch_error=True, |
| 164 |
) as (_, _, err): |
| 165 |
assert isinstance(err, SSHException) |
| 166 |
assert "no RSA pubkey algorithms" in str(err) |
| 167 |
|
| 168 |
def first_client_preferred_algo_used_when_no_server_sig_algs(self): |
| 169 |
privkey = RSAKey.from_private_key_file(_support("rsa.key")) |
| 170 |
with server( |
| 171 |
pubkeys=[privkey], |
| 172 |
connect=dict(username="slowdive", pkey=privkey), |
| 173 |
server_init=dict( |
| 174 |
disabled_algorithms=dict( |
| 175 |
# Disable both SHA2 just to keep previous theme of this |
| 176 |
# test alive (auth failure but w/ proof we tried offering |
| 177 |
# something) |
| 178 |
pubkeys=["rsa-sha2-256", "rsa-sha2-512"] |
| 179 |
), |
| 180 |
# Don't publish server-sig-algs, forcing use of fallback on the |
| 181 |
# client side |
| 182 |
server_sig_algs=False, |
| 183 |
), |
| 184 |
# Incidentally prove we're using the filtered algorithm list on the |
| 185 |
# client side - taking out 512 means we should offer 256 |
| 186 |
client_init=dict( |
| 187 |
disabled_algorithms=dict(pubkeys=["rsa-sha2-512"]) |
| 188 |
), |
| 189 |
catch_error=True, |
| 190 |
) as (tc, ts, err): |
| 191 |
# There was no agreement, we threw an exception... |
| 192 |
assert not tc.is_authenticated() |
| 193 |
assert isinstance(err, AuthenticationException) |
| 194 |
# ...but we can observe the client did their best guess at what an |
| 195 |
# agreement /could/ have been, and it was 256 |
| 196 |
assert tc._agreed_pubkey_algorithm == "rsa-sha2-256" |
| 197 |
|
| 198 |
def sha2_512(self): |
| 199 |
privkey = RSAKey.from_private_key_file(_support("rsa.key")) |
| 200 |
with server( |
| 201 |
pubkeys=[privkey], |
| 202 |
connect=dict(pkey=privkey), |
| 203 |
init=dict(disabled_algorithms=dict(pubkeys=["rsa-sha2-256"])), |
| 204 |
) as (tc, ts): |
| 205 |
assert tc.is_authenticated() |
| 206 |
assert tc._agreed_pubkey_algorithm == "rsa-sha2-512" |
| 207 |
|
| 208 |
def sha2_256(self): |
| 209 |
privkey = RSAKey.from_private_key_file(_support("rsa.key")) |
| 210 |
with server( |
| 211 |
pubkeys=[privkey], |
| 212 |
connect=dict(pkey=privkey), |
| 213 |
init=dict(disabled_algorithms=dict(pubkeys=["rsa-sha2-512"])), |
| 214 |
) as (tc, ts): |
| 215 |
assert tc.is_authenticated() |
| 216 |
assert tc._agreed_pubkey_algorithm == "rsa-sha2-256" |
| 217 |
|
| 218 |
|
| 219 |
class AuthSource_: |
| 220 |
class base_class: |
| 221 |
def init_requires_and_saves_username(self): |
| 222 |
with raises(TypeError): |
| 223 |
AuthSource() |
| 224 |
assert AuthSource(username="foo").username == "foo" |
| 225 |
|
| 226 |
def dunder_repr_delegates_to_helper(self): |
| 227 |
source = AuthSource("foo") |
| 228 |
source._repr = Mock(wraps=lambda: "whatever") |
| 229 |
repr(source) |
| 230 |
source._repr.assert_called_once_with() |
| 231 |
|
| 232 |
def repr_helper_prints_basic_kv_pairs(self): |
| 233 |
assert repr(AuthSource("foo")) == "AuthSource()" |
| 234 |
assert ( |
| 235 |
AuthSource("foo")._repr(bar="open") == "AuthSource(bar='open')" |
| 236 |
) |
| 237 |
|
| 238 |
def authenticate_takes_transport_and_is_abstract(self): |
| 239 |
# TODO: this test kinda just goes away once we're typed? |
| 240 |
with raises(TypeError): |
| 241 |
AuthSource("foo").authenticate() |
| 242 |
with raises(NotImplementedError): |
| 243 |
AuthSource("foo").authenticate(None) |
| 244 |
|
| 245 |
class NoneAuth_: |
| 246 |
def authenticate_auths_none(self): |
| 247 |
trans = Mock() |
| 248 |
result = NoneAuth("foo").authenticate(trans) |
| 249 |
trans.auth_none.assert_called_once_with("foo") |
| 250 |
assert result is trans.auth_none.return_value |
| 251 |
|
| 252 |
def repr_shows_class(self): |
| 253 |
assert repr(NoneAuth("foo")) == "NoneAuth()" |
| 254 |
|
| 255 |
class Password_: |
| 256 |
def init_takes_and_stores_password_getter(self): |
| 257 |
with raises(TypeError): |
| 258 |
Password("foo") |
| 259 |
getter = Mock() |
| 260 |
pw = Password("foo", password_getter=getter) |
| 261 |
assert pw.password_getter is getter |
| 262 |
|
| 263 |
def repr_adds_username(self): |
| 264 |
pw = Password("foo", password_getter=Mock()) |
| 265 |
assert repr(pw) == "Password(user='foo')" |
| 266 |
|
| 267 |
def authenticate_gets_and_supplies_password(self): |
| 268 |
getter = Mock(return_value="bar") |
| 269 |
trans = Mock() |
| 270 |
pw = Password("foo", password_getter=getter) |
| 271 |
result = pw.authenticate(trans) |
| 272 |
trans.auth_password.assert_called_once_with("foo", "bar") |
| 273 |
assert result is trans.auth_password.return_value |
| 274 |
|
| 275 |
class PrivateKey_: |
| 276 |
def authenticate_calls_publickey_with_pkey(self): |
| 277 |
source = PrivateKey(username="foo") |
| 278 |
source.pkey = Mock() # set by subclasses |
| 279 |
trans = Mock() |
| 280 |
result = source.authenticate(trans) |
| 281 |
trans.auth_publickey.assert_called_once_with("foo", source.pkey) |
| 282 |
assert result is trans.auth_publickey.return_value |
| 283 |
|
| 284 |
class InMemoryPrivateKey_: |
| 285 |
def init_takes_pkey_object(self): |
| 286 |
with raises(TypeError): |
| 287 |
InMemoryPrivateKey("foo") |
| 288 |
pkey = Mock() |
| 289 |
source = InMemoryPrivateKey(username="foo", pkey=pkey) |
| 290 |
assert source.pkey is pkey |
| 291 |
|
| 292 |
def repr_shows_pkey_repr(self): |
| 293 |
pkey = PKey.from_path(_support("ed25519.key")) |
| 294 |
source = InMemoryPrivateKey("foo", pkey) |
| 295 |
assert ( |
| 296 |
repr(source) |
| 297 |
== "InMemoryPrivateKey(pkey=PKey(alg=ED25519, bits=256, fp=SHA256:J6VESFdD3xSChn8y9PzWzeF+1tl892mOy2TqkMLO4ow))" # noqa |
| 298 |
) |
| 299 |
|
| 300 |
def repr_appends_agent_flag_when_AgentKey(self): |
| 301 |
real_key = PKey.from_path(_support("ed25519.key")) |
| 302 |
pkey = AgentKey(agent=None, blob=bytes(real_key)) |
| 303 |
source = InMemoryPrivateKey("foo", pkey) |
| 304 |
assert ( |
| 305 |
repr(source) |
| 306 |
== "InMemoryPrivateKey(pkey=PKey(alg=ED25519, bits=256, fp=SHA256:J6VESFdD3xSChn8y9PzWzeF+1tl892mOy2TqkMLO4ow)) [agent]" # noqa |
| 307 |
) |
| 308 |
|
| 309 |
class OnDiskPrivateKey_: |
| 310 |
def init_takes_source_path_and_pkey(self): |
| 311 |
with raises(TypeError): |
| 312 |
OnDiskPrivateKey("foo") |
| 313 |
with raises(TypeError): |
| 314 |
OnDiskPrivateKey("foo", "bar") |
| 315 |
with raises(TypeError): |
| 316 |
OnDiskPrivateKey("foo", "bar", "biz") |
| 317 |
source = OnDiskPrivateKey( |
| 318 |
username="foo", |
| 319 |
source="ssh-config", |
| 320 |
path="of-exile", |
| 321 |
pkey="notreally", |
| 322 |
) |
| 323 |
assert source.username == "foo" |
| 324 |
assert source.source == "ssh-config" |
| 325 |
assert source.path == "of-exile" |
| 326 |
assert source.pkey == "notreally" |
| 327 |
|
| 328 |
def init_requires_specific_value_for_source(self): |
| 329 |
with raises( |
| 330 |
ValueError, |
| 331 |
match=r"source argument must be one of: \('ssh-config', 'python-config', 'implicit-home'\)", # noqa |
| 332 |
): |
| 333 |
OnDiskPrivateKey("foo", source="what?", path="meh", pkey="no") |
| 334 |
|
| 335 |
def repr_reflects_source_path_and_pkey(self): |
| 336 |
source = OnDiskPrivateKey( |
| 337 |
username="foo", |
| 338 |
source="ssh-config", |
| 339 |
path="of-exile", |
| 340 |
pkey="notreally", |
| 341 |
) |
| 342 |
assert ( |
| 343 |
repr(source) |
| 344 |
== "OnDiskPrivateKey(key='notreally', source='ssh-config', path='of-exile')" # noqa |
| 345 |
) |
| 346 |
|
| 347 |
|
| 348 |
class AuthResult_: |
| 349 |
def setup_method(self): |
| 350 |
self.strat = AuthStrategy(None) |
| 351 |
|
| 352 |
def acts_like_list_with_strategy_attribute(self): |
| 353 |
with raises(TypeError): |
| 354 |
AuthResult() |
| 355 |
# kwarg works by itself |
| 356 |
AuthResult(strategy=self.strat) |
| 357 |
# or can be given as posarg w/ regular list() args after |
| 358 |
result = AuthResult(self.strat, [1, 2, 3]) |
| 359 |
assert result.strategy is self.strat |
| 360 |
assert result == [1, 2, 3] |
| 361 |
assert isinstance(result, list) |
| 362 |
|
| 363 |
def repr_is_list_repr_untouched(self): |
| 364 |
result = AuthResult(self.strat, [1, 2, 3]) |
| 365 |
assert repr(result) == "[1, 2, 3]" |
| 366 |
|
| 367 |
class dunder_str: |
| 368 |
def is_multiline_display_of_sourceresult_tuples(self): |
| 369 |
result = AuthResult(self.strat) |
| 370 |
result.append(SourceResult("foo", "bar")) |
| 371 |
result.append(SourceResult("biz", "baz")) |
| 372 |
assert str(result) == "foo -> bar\nbiz -> baz" |
| 373 |
|
| 374 |
def shows_str_not_repr_of_auth_source_and_result(self): |
| 375 |
result = AuthResult(self.strat) |
| 376 |
result.append( |
| 377 |
SourceResult(NoneAuth("foo"), ["password", "pubkey"]) |
| 378 |
) |
| 379 |
assert str(result) == "NoneAuth() -> ['password', 'pubkey']" |
| 380 |
|
| 381 |
def empty_list_result_values_show_success_string(self): |
| 382 |
result = AuthResult(self.strat) |
| 383 |
result.append(SourceResult(NoneAuth("foo"), [])) |
| 384 |
assert str(result) == "NoneAuth() -> success" |
| 385 |
|
| 386 |
|
| 387 |
class AuthFailure_: |
| 388 |
def is_an_AuthenticationException(self): |
| 389 |
assert isinstance(AuthFailure(None), AuthenticationException) |
| 390 |
|
| 391 |
def init_requires_result(self): |
| 392 |
with raises(TypeError): |
| 393 |
AuthFailure() |
| 394 |
result = AuthResult(None) |
| 395 |
fail = AuthFailure(result=result) |
| 396 |
assert fail.result is result |
| 397 |
|
| 398 |
def str_is_newline_plus_result_str(self): |
| 399 |
result = AuthResult(None) |
| 400 |
result.append(SourceResult(NoneAuth("foo"), Exception("onoz"))) |
| 401 |
fail = AuthFailure(result) |
| 402 |
assert str(fail) == "\nNoneAuth() -> onoz" |
| 403 |
|
| 404 |
|
| 405 |
class AuthStrategy_: |
| 406 |
def init_requires_ssh_config_param_and_sets_up_a_logger(self): |
| 407 |
with raises(TypeError): |
| 408 |
AuthStrategy() |
| 409 |
conf = object() |
| 410 |
strat = AuthStrategy(ssh_config=conf) |
| 411 |
assert strat.ssh_config is conf |
| 412 |
assert isinstance(strat.log, Logger) |
| 413 |
assert strat.log.name == "paramiko.auth_strategy" |
| 414 |
|
| 415 |
def get_sources_is_abstract(self): |
| 416 |
with raises(NotImplementedError): |
| 417 |
AuthStrategy(None).get_sources() |
| 418 |
|
| 419 |
class authenticate: |
| 420 |
def setup_method(self): |
| 421 |
self.strat = AuthStrategy(None) # ssh_config not used directly |
| 422 |
self.source, self.transport = NoneAuth(None), Mock() |
| 423 |
self.source.authenticate = Mock() |
| 424 |
self.strat.get_sources = Mock(return_value=[self.source]) |
| 425 |
|
| 426 |
def requires_and_uses_transport_with_methods_returning_result(self): |
| 427 |
with raises(TypeError): |
| 428 |
self.strat.authenticate() |
| 429 |
result = self.strat.authenticate(self.transport) |
| 430 |
self.strat.get_sources.assert_called_once_with() |
| 431 |
self.source.authenticate.assert_called_once_with(self.transport) |
| 432 |
assert isinstance(result, AuthResult) |
| 433 |
assert result.strategy is self.strat |
| 434 |
assert len(result) == 1 |
| 435 |
source_res = result[0] |
| 436 |
assert isinstance(source_res, SourceResult) |
| 437 |
assert source_res.source is self.source |
| 438 |
assert source_res.result is self.source.authenticate.return_value |
| 439 |
|
| 440 |
def logs_sources_attempted(self): |
| 441 |
self.strat.log = Mock() |
| 442 |
self.strat.authenticate(self.transport) |
| 443 |
self.strat.log.debug.assert_called_once_with("Trying NoneAuth()") |
| 444 |
|
| 445 |
def raises_AuthFailure_if_no_successes(self): |
| 446 |
self.strat.log = Mock() |
| 447 |
oops = Exception("onoz") |
| 448 |
self.source.authenticate.side_effect = oops |
| 449 |
with raises(AuthFailure) as info: |
| 450 |
self.strat.authenticate(self.transport) |
| 451 |
result = info.value.result |
| 452 |
assert isinstance(result, AuthResult) |
| 453 |
assert len(result) == 1 |
| 454 |
source_res = result[0] |
| 455 |
assert isinstance(source_res, SourceResult) |
| 456 |
assert source_res.source is self.source |
| 457 |
assert source_res.result is oops |
| 458 |
self.strat.log.info.assert_called_once_with( |
| 459 |
"Authentication via NoneAuth() failed with Exception" |
| 460 |
) |
| 461 |
|
| 462 |
def short_circuits_on_successful_auth(self): |
| 463 |
kaboom = Mock(authenticate=Mock(side_effect=Exception("onoz"))) |
| 464 |
self.strat.get_sources.return_value = [self.source, kaboom] |
| 465 |
result = self.strat.authenticate(self.transport) |
| 466 |
# No exception, and it's just a regular ol Result |
| 467 |
assert isinstance(result, AuthResult) |
| 468 |
# And it did not capture any attempt to execute the 2nd source |
| 469 |
assert len(result) == 1 |
| 470 |
assert result[0].source is self.source |