/usr/lib/python3/dist-packages/asyncssh/auth.py is in python3-asyncssh 1.3.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 | # Copyright (c) 2013-2015 by Ron Frederick <ronf@timeheart.net>.
# All rights reserved.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v1.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# Ron Frederick - initial implementation, API, and documentation
"""SSH authentication handlers"""
import asyncio
from .constants import DISC_PROTOCOL_ERROR
from .misc import DisconnectError
from .packet import Boolean, Byte, String, UInt32, SSHPacketHandler
from .saslprep import saslprep, SASLPrepError
# pylint: disable=bad-whitespace
# SSH message values for public key auth
MSG_USERAUTH_PK_OK = 60
# SSH message values for password auth
MSG_USERAUTH_PASSWD_CHANGEREQ = 60
# SSH message values for 'keyboard-interactive' auth
MSG_USERAUTH_INFO_REQUEST = 60
MSG_USERAUTH_INFO_RESPONSE = 61
# pylint: enable=bad-whitespace
_auth_methods = []
_client_auth_handlers = {}
_server_auth_handlers = {}
class _Auth(SSHPacketHandler):
"""Parent class for authentication"""
def __init__(self):
self._coro = None
def cancel(self):
"""Cancel any authentication in progress"""
if self._coro:
self._coro.cancel()
self._coro = None
class _ClientAuth(_Auth):
"""Parent class for client authentication"""
def __init__(self, conn, method):
super().__init__()
self._conn = conn
self._method = method
self._coro = asyncio.async(self._start())
@asyncio.coroutine
def _start(self):
"""Abstract method for starting client authentication"""
# Provided by subclass
raise NotImplementedError
def auth_succeeded(self):
"""Callback when auth succeeds"""
def auth_failed(self):
"""Callback when auth fails"""
def send_request(self, *args, key=None):
"""Send a user authentication request"""
self._conn.send_userauth_request(self._method, *args, key=key)
class _ClientNullAuth(_ClientAuth):
"""Client side implementation of null auth"""
@asyncio.coroutine
def _start(self):
"""Start client null authentication"""
self.send_request()
packet_handlers = {}
class _ClientPublicKeyAuth(_ClientAuth):
"""Client side implementation of public key auth"""
@asyncio.coroutine
def _start(self):
"""Start client public key authentication"""
self._alg, self._key, self._key_data = \
yield from self._conn.public_key_auth_requested()
if self._alg is None:
self._conn.try_next_auth()
return
self.send_request(Boolean(False), String(self._alg),
String(self._key_data))
def _process_public_key_ok(self, pkttype, packet):
"""Process a public key ok response"""
# pylint: disable=unused-argument
algorithm = packet.get_string()
key_data = packet.get_string()
packet.check_end()
if algorithm != self._alg or key_data != self._key_data:
raise DisconnectError(DISC_PROTOCOL_ERROR, 'Key mismatch')
self.send_request(Boolean(True), String(algorithm),
String(key_data), key=self._key)
return True
packet_handlers = {
MSG_USERAUTH_PK_OK: _process_public_key_ok
}
class _ClientKbdIntAuth(_ClientAuth):
"""Client side implementation of keyboard-interactive auth"""
@asyncio.coroutine
def _start(self):
"""Start client keyboard interactive authentication"""
submethods = yield from self._conn.kbdint_auth_requested()
if submethods is None:
self._conn.try_next_auth()
return
self.send_request(String(''), String(submethods))
@asyncio.coroutine
def _receive_challenge(self, name, instruction, lang, prompts):
"""Receive and respond to a keyboard interactive challenge"""
responses = \
yield from self._conn.kbdint_challenge_received(name, instruction,
lang, prompts)
if responses is None:
self._conn.try_next_auth()
return
self._conn.send_packet(Byte(MSG_USERAUTH_INFO_RESPONSE),
UInt32(len(responses)),
b''.join(String(r) for r in responses))
def _process_info_request(self, pkttype, packet):
"""Process a keyboard interactive authentication request"""
# pylint: disable=unused-argument
name = packet.get_string()
instruction = packet.get_string()
lang = packet.get_string()
try:
name = name.decode('utf-8')
instruction = instruction.decode('utf-8')
lang = lang.decode('ascii')
except UnicodeDecodeError:
raise DisconnectError(DISC_PROTOCOL_ERROR, 'Invalid keyboard '
'interactive info request') from None
num_prompts = packet.get_uint32()
prompts = []
for _ in range(num_prompts):
prompt = packet.get_string()
echo = packet.get_boolean()
try:
prompt = prompt.decode('utf-8')
except UnicodeDecodeError:
raise DisconnectError(DISC_PROTOCOL_ERROR, 'Invalid keyboard '
'interactive info request') from None
prompts.append((prompt, echo))
self.cancel()
self._coro = asyncio.async(self._receive_challenge(name, instruction,
lang, prompts))
return True
packet_handlers = {
MSG_USERAUTH_INFO_REQUEST: _process_info_request
}
class _ClientPasswordAuth(_ClientAuth):
"""Client side implementation of password auth"""
def __init__(self, conn, method):
super().__init__(conn, method)
self._password_change = False
@asyncio.coroutine
def _start(self):
"""Start client password authentication"""
password = yield from self._conn.password_auth_requested()
if password is None:
self._conn.try_next_auth()
return
self.send_request(Boolean(False), String(password))
@asyncio.coroutine
def _change_password(self):
"""Start password change"""
result = yield from self._conn.password_change_requested()
if result == NotImplemented:
# Password change not supported - move on to the next auth method
self._conn.try_next_auth()
return
old_password, new_password = result
self._password_change = True
self.send_request(Boolean(True),
String(old_password.encode('utf-8')),
String(new_password.encode('utf-8')))
def auth_succeeded(self):
if self._password_change:
self._password_change = False
self._conn.password_changed()
def auth_failed(self):
if self._password_change:
self._password_change = False
self._conn.password_change_failed()
def _process_password_change(self, pkttype, packet):
"""Process a password change request"""
# pylint: disable=unused-argument
prompt = packet.get_string()
lang = packet.get_string()
try:
prompt = prompt.decode('utf-8')
lang = lang.decode('ascii')
except UnicodeDecodeError:
raise DisconnectError(DISC_PROTOCOL_ERROR,
'Invalid password change request') from None
self.cancel()
self._coro = asyncio.async(self._change_password())
return True
packet_handlers = {
MSG_USERAUTH_PASSWD_CHANGEREQ: _process_password_change
}
class _ServerAuth(_Auth):
"""Parent class for server authentication"""
def __init__(self, conn, username, packet):
super().__init__()
self._conn = conn
self._username = username
self._coro = asyncio.async(self._start(packet))
@asyncio.coroutine
def _start(self, packet):
"""Abstract method for starting server authentication"""
# Provided by subclass
raise NotImplementedError
def send_failure(self, partial_success=False):
"""Send a user authentication failure response"""
self._conn.send_userauth_failure(partial_success)
def send_success(self):
"""Send a user authentication success response"""
self._conn.send_userauth_success()
class _ServerNullAuth(_ServerAuth):
"""Server side implementation of null auth"""
@classmethod
def supported(cls, conn):
"""Return that null authentication is never a supported auth mode"""
# pylint: disable=unused-argument
return False
@asyncio.coroutine
def _start(self, packet):
"""Always fail null server authentication"""
packet.check_end()
self.send_failure()
class _ServerPublicKeyAuth(_ServerAuth):
"""Server side implementation of public key auth"""
@classmethod
def supported(cls, conn):
"""Return whether public key authentication is supported"""
return conn.public_key_auth_supported()
@asyncio.coroutine
def _start(self, packet):
"""Start server public key authentication"""
sig_present = packet.get_boolean()
algorithm = packet.get_string()
key_data = packet.get_string()
if sig_present:
msg = packet.get_consumed_payload()
signature = packet.get_string()
else:
msg = None
signature = None
packet.check_end()
if (yield from self._conn.validate_public_key(self._username, key_data,
msg, signature)):
if sig_present:
self.send_success()
else:
self._conn.send_packet(Byte(MSG_USERAUTH_PK_OK),
String(algorithm), String(key_data))
else:
self.send_failure()
class _ServerKbdIntAuth(_ServerAuth):
"""Server side implementation of keyboard-interactive auth"""
@classmethod
def supported(cls, conn):
"""Return whether keyboard interactive authentication is supported"""
return conn.kbdint_auth_supported()
@asyncio.coroutine
def _start(self, packet):
"""Start server keyboard interactive authentication"""
lang = packet.get_string()
submethods = packet.get_string()
packet.check_end()
try:
lang = lang.decode('ascii')
submethods = submethods.decode('utf-8')
except UnicodeDecodeError:
raise DisconnectError(DISC_PROTOCOL_ERROR, 'Invalid keyboard '
'interactive auth request') from None
challenge = yield from self._conn.get_kbdint_challenge(self._username,
lang,
submethods)
self._send_challenge(challenge)
def _send_challenge(self, challenge):
"""Send a keyboard interactive authentication request"""
if isinstance(challenge, (tuple, list)):
name, instruction, lang, prompts = challenge
num_prompts = len(prompts)
prompts = (String(prompt) + Boolean(echo)
for prompt, echo in prompts)
self._conn.send_packet(Byte(MSG_USERAUTH_INFO_REQUEST),
String(name), String(instruction),
String(lang), UInt32(num_prompts),
*prompts)
elif challenge:
self.send_success()
else:
self.send_failure()
@asyncio.coroutine
def _validate_response(self, responses):
"""Validate a keyboard interactive authentication response"""
next_challenge = \
yield from self._conn.validate_kbdint_response(self._username,
responses)
self._send_challenge(next_challenge)
def _process_info_response(self, pkttype, packet):
"""Process a keyboard interactive authentication response"""
# pylint: disable=unused-argument
num_responses = packet.get_uint32()
responses = []
for _ in range(num_responses):
response = packet.get_string()
try:
response = response.decode('utf-8')
except UnicodeDecodeError:
raise DisconnectError(DISC_PROTOCOL_ERROR, 'Invalid keyboard '
'interactive info response') from None
responses.append(response)
packet.check_end()
self.cancel()
self._coro = asyncio.async(self._validate_response(responses))
packet_handlers = {
MSG_USERAUTH_INFO_RESPONSE: _process_info_response
}
class _ServerPasswordAuth(_ServerAuth):
"""Server side implementation of password auth"""
@classmethod
def supported(cls, conn):
"""Return whether password authentication is supported"""
return conn.password_auth_supported()
@asyncio.coroutine
def _start(self, packet):
"""Start server password authentication"""
password_change = packet.get_boolean()
password = packet.get_string()
new_password = packet.get_string() if password_change else b''
packet.check_end()
try:
password = saslprep(password.decode('utf-8'))
new_password = saslprep(new_password.decode('utf-8'))
except (UnicodeDecodeError, SASLPrepError):
raise DisconnectError(DISC_PROTOCOL_ERROR, 'Invalid password auth '
'request') from None
# TODO: Handle password change request
if (yield from self._conn.validate_password(self._username, password)):
self.send_success()
else:
self.send_failure()
def register_auth_method(alg, client_handler, server_handler):
"""Register an authentication method"""
_auth_methods.append(alg)
_client_auth_handlers[alg] = client_handler
_server_auth_handlers[alg] = server_handler
def lookup_client_auth(conn, method):
"""Look up the client authentication method to use"""
if method in _auth_methods:
return _client_auth_handlers[method](conn, method)
else:
return None
def get_server_auth_methods(conn):
"""Return a list of supported auth methods"""
auth_methods = []
for method in _auth_methods:
if _server_auth_handlers[method].supported(conn):
auth_methods.append(method)
return auth_methods
def lookup_server_auth(conn, username, method, packet):
"""Look up the server authentication method to use"""
if method in _auth_methods:
return _server_auth_handlers[method](conn, username, packet)
else:
conn.send_userauth_failure(False)
return None
# pylint: disable=bad-whitespace
_auth_method_list = (
(b'none', _ClientNullAuth, _ServerNullAuth),
(b'publickey', _ClientPublicKeyAuth, _ServerPublicKeyAuth),
(b'keyboard-interactive', _ClientKbdIntAuth, _ServerKbdIntAuth),
(b'password', _ClientPasswordAuth, _ServerPasswordAuth)
)
# pylint: enable=bad-whitespace
for _args in _auth_method_list:
register_auth_method(*_args)
|