auth.py 7.9 KB

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