auth.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. # -*- coding: utf-8 -*-
  2. """
  3. requests.auth
  4. ~~~~~~~~~~~~~
  5. This module contains the authentication handlers for Requests.
  6. """
  7. import os
  8. import re
  9. import time
  10. import hashlib
  11. from base64 import b64encode
  12. from .compat import urlparse, str
  13. from .cookies import extract_cookies_to_jar
  14. from .utils import parse_dict_header, to_native_string
  15. from .status_codes import codes
  16. CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'
  17. CONTENT_TYPE_MULTI_PART = 'multipart/form-data'
  18. def _basic_auth_str(username, password):
  19. """Returns a Basic Auth string."""
  20. authstr = 'Basic ' + to_native_string(
  21. b64encode(('%s:%s' % (username, password)).encode('latin1')).strip()
  22. )
  23. return authstr
  24. class AuthBase(object):
  25. """Base class that all auth implementations derive from"""
  26. def __call__(self, r):
  27. raise NotImplementedError('Auth hooks must be callable.')
  28. class HTTPBasicAuth(AuthBase):
  29. """Attaches HTTP Basic Authentication to the given Request object."""
  30. def __init__(self, username, password):
  31. self.username = username
  32. self.password = password
  33. def __call__(self, r):
  34. r.headers['Authorization'] = _basic_auth_str(self.username, self.password)
  35. return r
  36. class HTTPProxyAuth(HTTPBasicAuth):
  37. """Attaches HTTP Proxy Authentication to a given Request object."""
  38. def __call__(self, r):
  39. r.headers['Proxy-Authorization'] = _basic_auth_str(self.username, self.password)
  40. return r
  41. class HTTPDigestAuth(AuthBase):
  42. """Attaches HTTP Digest Authentication to the given Request object."""
  43. def __init__(self, username, password):
  44. self.username = username
  45. self.password = password
  46. self.last_nonce = ''
  47. self.nonce_count = 0
  48. self.chal = {}
  49. self.pos = None
  50. self.num_401_calls = 1
  51. def build_digest_header(self, method, url):
  52. realm = self.chal['realm']
  53. nonce = self.chal['nonce']
  54. qop = self.chal.get('qop')
  55. algorithm = self.chal.get('algorithm')
  56. opaque = self.chal.get('opaque')
  57. if algorithm is None:
  58. _algorithm = 'MD5'
  59. else:
  60. _algorithm = algorithm.upper()
  61. # lambdas assume digest modules are imported at the top level
  62. if _algorithm == 'MD5' or _algorithm == 'MD5-SESS':
  63. def md5_utf8(x):
  64. if isinstance(x, str):
  65. x = x.encode('utf-8')
  66. return hashlib.md5(x).hexdigest()
  67. hash_utf8 = md5_utf8
  68. elif _algorithm == 'SHA':
  69. def sha_utf8(x):
  70. if isinstance(x, str):
  71. x = x.encode('utf-8')
  72. return hashlib.sha1(x).hexdigest()
  73. hash_utf8 = sha_utf8
  74. KD = lambda s, d: hash_utf8("%s:%s" % (s, d))
  75. if hash_utf8 is None:
  76. return None
  77. # XXX not implemented yet
  78. entdig = None
  79. p_parsed = urlparse(url)
  80. path = p_parsed.path
  81. if p_parsed.query:
  82. path += '?' + p_parsed.query
  83. A1 = '%s:%s:%s' % (self.username, realm, self.password)
  84. A2 = '%s:%s' % (method, path)
  85. HA1 = hash_utf8(A1)
  86. HA2 = hash_utf8(A2)
  87. if nonce == self.last_nonce:
  88. self.nonce_count += 1
  89. else:
  90. self.nonce_count = 1
  91. ncvalue = '%08x' % self.nonce_count
  92. s = str(self.nonce_count).encode('utf-8')
  93. s += nonce.encode('utf-8')
  94. s += time.ctime().encode('utf-8')
  95. s += os.urandom(8)
  96. cnonce = (hashlib.sha1(s).hexdigest()[:16])
  97. if _algorithm == 'MD5-SESS':
  98. HA1 = hash_utf8('%s:%s:%s' % (HA1, nonce, cnonce))
  99. if qop is None:
  100. respdig = KD(HA1, "%s:%s" % (nonce, HA2))
  101. elif qop == 'auth' or 'auth' in qop.split(','):
  102. noncebit = "%s:%s:%s:%s:%s" % (
  103. nonce, ncvalue, cnonce, 'auth', HA2
  104. )
  105. respdig = KD(HA1, noncebit)
  106. else:
  107. # XXX handle auth-int.
  108. return None
  109. self.last_nonce = nonce
  110. # XXX should the partial digests be encoded too?
  111. base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
  112. 'response="%s"' % (self.username, realm, nonce, path, respdig)
  113. if opaque:
  114. base += ', opaque="%s"' % opaque
  115. if algorithm:
  116. base += ', algorithm="%s"' % algorithm
  117. if entdig:
  118. base += ', digest="%s"' % entdig
  119. if qop:
  120. base += ', qop="auth", nc=%s, cnonce="%s"' % (ncvalue, cnonce)
  121. return 'Digest %s' % (base)
  122. def handle_redirect(self, r, **kwargs):
  123. """Reset num_401_calls counter on redirects."""
  124. if r.is_redirect:
  125. self.num_401_calls = 1
  126. def handle_401(self, r, **kwargs):
  127. """Takes the given response and tries digest-auth, if needed."""
  128. if self.pos is not None:
  129. # Rewind the file position indicator of the body to where
  130. # it was to resend the request.
  131. r.request.body.seek(self.pos)
  132. num_401_calls = getattr(self, 'num_401_calls', 1)
  133. s_auth = r.headers.get('www-authenticate', '')
  134. if 'digest' in s_auth.lower() and num_401_calls < 2:
  135. self.num_401_calls += 1
  136. pat = re.compile(r'digest ', flags=re.IGNORECASE)
  137. self.chal = parse_dict_header(pat.sub('', s_auth, count=1))
  138. # Consume content and release the original connection
  139. # to allow our new request to reuse the same one.
  140. r.content
  141. r.raw.release_conn()
  142. prep = r.request.copy()
  143. extract_cookies_to_jar(prep._cookies, r.request, r.raw)
  144. prep.prepare_cookies(prep._cookies)
  145. prep.headers['Authorization'] = self.build_digest_header(
  146. prep.method, prep.url)
  147. _r = r.connection.send(prep, **kwargs)
  148. _r.history.append(r)
  149. _r.request = prep
  150. return _r
  151. self.num_401_calls = 1
  152. return r
  153. def __call__(self, r):
  154. # If we have a saved nonce, skip the 401
  155. if self.last_nonce:
  156. r.headers['Authorization'] = self.build_digest_header(r.method, r.url)
  157. try:
  158. self.pos = r.body.tell()
  159. except AttributeError:
  160. # In the case of HTTPDigestAuth being reused and the body of
  161. # the previous request was a file-like object, pos has the
  162. # file position of the previous body. Ensure it's set to
  163. # None.
  164. self.pos = None
  165. r.register_hook('response', self.handle_401)
  166. r.register_hook('response', self.handle_redirect)
  167. return r