|
8 | 8 | import datetime
|
9 | 9 | import enum
|
10 | 10 | import functools
|
| 11 | +import hashlib |
11 | 12 | import inspect
|
12 | 13 | import netrc
|
13 | 14 | import os
|
|
53 | 54 | from propcache.api import under_cached_property as reify
|
54 | 55 | from yarl import URL
|
55 | 56 |
|
56 |
| -from . import hdrs |
| 57 | +from . import client_exceptions, hdrs |
57 | 58 | from .log import client_logger
|
58 | 59 | from .typedefs import PathLike # noqa
|
59 | 60 |
|
|
71 | 72 | dataclasses.dataclass, frozen=True, slots=True
|
72 | 73 | )
|
73 | 74 |
|
74 |
| -__all__ = ("BasicAuth", "ChainMapProxy", "ETag", "frozen_dataclass_decorator", "reify") |
| 75 | +__all__ = ( |
| 76 | + "BasicAuth", |
| 77 | + "ChainMapProxy", |
| 78 | + "ETag", |
| 79 | + "frozen_dataclass_decorator", |
| 80 | + "reify", |
| 81 | + "DigestAuth", |
| 82 | +) |
75 | 83 |
|
76 | 84 | PY_310 = sys.version_info >= (3, 10)
|
77 | 85 |
|
@@ -279,6 +287,172 @@ def basicauth_from_netrc(netrc_obj: Optional[netrc.netrc], host: str) -> BasicAu
|
279 | 287 | return BasicAuth(username, password)
|
280 | 288 |
|
281 | 289 |
|
| 290 | +def parse_pair(pair): |
| 291 | + key, value = pair.split("=", 1) |
| 292 | + |
| 293 | + # If it has a trailing comma, remove it. |
| 294 | + if value[-1] == ",": |
| 295 | + value = value[:-1] |
| 296 | + |
| 297 | + # If it is quoted, then remove them. |
| 298 | + if value[0] == value[-1] == '"': |
| 299 | + value = value[1:-1] |
| 300 | + |
| 301 | + return key, value |
| 302 | + |
| 303 | + |
| 304 | +def parse_key_value_list(header): |
| 305 | + return { |
| 306 | + key: value |
| 307 | + for key, value in [parse_pair(header_pair) for header_pair in header.split(" ")] |
| 308 | + } |
| 309 | + |
| 310 | + |
| 311 | +class DigestAuth: |
| 312 | + """ |
| 313 | + HTTP digest authentication helper. |
| 314 | +
|
| 315 | + The work here is based off of |
| 316 | + https://github.com/requests/requests/blob/v2.18.4/requests/auth.py. |
| 317 | + """ |
| 318 | + |
| 319 | + def __init__(self, username, password, session, previous=None): |
| 320 | + if previous is None: |
| 321 | + previous = {} |
| 322 | + |
| 323 | + self.username = username |
| 324 | + self.password = password |
| 325 | + self.last_nonce = previous.get("last_nonce", "") |
| 326 | + self.nonce_count = previous.get("nonce_count", 0) |
| 327 | + self.challenge = previous.get("challenge") |
| 328 | + self.args = {} |
| 329 | + self.session = session |
| 330 | + |
| 331 | + async def request(self, method, url, *, headers=None, **kwargs): |
| 332 | + if headers is None: |
| 333 | + headers = {} |
| 334 | + |
| 335 | + # Save the args so we can re-run the request |
| 336 | + self.args = {"method": method, "url": url, "headers": headers, "kwargs": kwargs} |
| 337 | + |
| 338 | + if self.challenge: |
| 339 | + headers[hdrs.AUTHORIZATION] = self._build_digest_header(method.upper(), url) |
| 340 | + |
| 341 | + response = await self.session.request(method, url, headers=headers, **kwargs) |
| 342 | + |
| 343 | + # Only try performing digest authentication if the response status is |
| 344 | + # from 400 to 500. |
| 345 | + if 400 <= response.status < 500: |
| 346 | + return await self._handle_401(response) |
| 347 | + |
| 348 | + return response |
| 349 | + |
| 350 | + def _build_digest_header(self, method, url): |
| 351 | + """ |
| 352 | + Build digest header |
| 353 | +
|
| 354 | + :rtype: str |
| 355 | + """ |
| 356 | + realm = self.challenge["realm"] |
| 357 | + nonce = self.challenge["nonce"] |
| 358 | + qop = self.challenge.get("qop") |
| 359 | + algorithm = self.challenge.get("algorithm", "MD5").upper() |
| 360 | + opaque = self.challenge.get("opaque") |
| 361 | + |
| 362 | + if qop and not (qop == "auth" or "auth" in qop.split(",")): |
| 363 | + raise client_exceptions.ClientError("Unsupported qop value: %s" % qop) |
| 364 | + |
| 365 | + # lambdas assume digest modules are imported at the top level |
| 366 | + if algorithm == "MD5" or algorithm == "MD5-SESS": |
| 367 | + hash_fn = hashlib.md5 |
| 368 | + elif algorithm == "SHA": |
| 369 | + hash_fn = hashlib.sha1 |
| 370 | + else: |
| 371 | + return "" |
| 372 | + |
| 373 | + def H(x): |
| 374 | + return hash_fn(x.encode()).hexdigest() |
| 375 | + |
| 376 | + def KD(s, d): |
| 377 | + return H(f"{s}:{d}") |
| 378 | + |
| 379 | + path = URL(url).path_qs |
| 380 | + A1 = f"{self.username}:{realm}:{self.password}" |
| 381 | + A2 = f"{method}:{path}" |
| 382 | + |
| 383 | + HA1 = H(A1) |
| 384 | + HA2 = H(A2) |
| 385 | + |
| 386 | + if nonce == self.last_nonce: |
| 387 | + self.nonce_count += 1 |
| 388 | + else: |
| 389 | + self.nonce_count = 1 |
| 390 | + |
| 391 | + self.last_nonce = nonce |
| 392 | + |
| 393 | + ncvalue = "%08x" % self.nonce_count |
| 394 | + |
| 395 | + # cnonce is just a random string generated by the client. |
| 396 | + cnonce_data = "".join( |
| 397 | + [ |
| 398 | + str(self.nonce_count), |
| 399 | + nonce, |
| 400 | + time.ctime(), |
| 401 | + os.urandom(8).decode(errors="ignore"), |
| 402 | + ] |
| 403 | + ).encode() |
| 404 | + cnonce = hashlib.sha1(cnonce_data).hexdigest()[:16] |
| 405 | + |
| 406 | + if algorithm == "MD5-SESS": |
| 407 | + HA1 = H(f"{HA1}:{nonce}:{cnonce}") |
| 408 | + |
| 409 | + # This assumes qop was validated to be 'auth' above. If 'auth-int' |
| 410 | + # support is added this will need to change. |
| 411 | + if qop: |
| 412 | + noncebit = ":".join([nonce, ncvalue, cnonce, "auth", HA2]) |
| 413 | + response_digest = KD(HA1, noncebit) |
| 414 | + else: |
| 415 | + response_digest = KD(HA1, f"{nonce}:{HA2}") |
| 416 | + |
| 417 | + base = ", ".join( |
| 418 | + [ |
| 419 | + 'username="%s"' % self.username, |
| 420 | + 'realm="%s"' % realm, |
| 421 | + 'nonce="%s"' % nonce, |
| 422 | + 'uri="%s"' % path, |
| 423 | + 'response="%s"' % response_digest, |
| 424 | + 'algorithm="%s"' % algorithm, |
| 425 | + ] |
| 426 | + ) |
| 427 | + if opaque: |
| 428 | + base += ', opaque="%s"' % opaque |
| 429 | + if qop: |
| 430 | + base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"' |
| 431 | + |
| 432 | + return "Digest %s" % base |
| 433 | + |
| 434 | + async def _handle_401(self, response): |
| 435 | + """ |
| 436 | + Takes the given response and tries digest-auth, if needed. |
| 437 | +
|
| 438 | + :rtype: ClientResponse |
| 439 | + """ |
| 440 | + auth_header = response.headers.get("www-authenticate", "") |
| 441 | + |
| 442 | + parts = auth_header.split(" ", 1) |
| 443 | + if "digest" == parts[0].lower() and len(parts) > 1: |
| 444 | + self.challenge = parse_key_value_list(parts[1]) |
| 445 | + |
| 446 | + return await self.request( |
| 447 | + self.args["method"], |
| 448 | + self.args["url"], |
| 449 | + headers=self.args["headers"], |
| 450 | + **self.args["kwargs"], |
| 451 | + ) |
| 452 | + |
| 453 | + return response |
| 454 | + |
| 455 | + |
282 | 456 | def proxies_from_env() -> Dict[str, ProxyInfo]:
|
283 | 457 | proxy_urls = {
|
284 | 458 | k: URL(v)
|
|
0 commit comments