auth.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. import warnings
  13. from base64 import b64encode
  14. from .compat import urlparse, str, basestring
  15. from .cookies import extract_cookies_to_jar
  16. from ._internal_utils import to_native_string
  17. from .utils import parse_dict_header
  18. CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'
  19. CONTENT_TYPE_MULTI_PART = 'multipart/form-data'
  20. def _basic_auth_str(username, password):
  21. """Returns a Basic Auth string."""
  22. # "I want us to put a big-ol' comment on top of it that
  23. # says that this behaviour is dumb but we need to preserve
  24. # it because people are relying on it."
  25. # - Lukasa
  26. #
  27. # These are here solely to maintain backwards compatibility
  28. # for things like ints. This will be removed in 3.0.0.
  29. if not isinstance(username, basestring):
  30. warnings.warn(
  31. "Non-string usernames will no longer be supported in Requests "
  32. "3.0.0. Please convert the object you've passed in ({0!r}) to "
  33. "a string or bytes object in the near future to avoid "
  34. "problems.".format(username),
  35. category=DeprecationWarning,
  36. )
  37. username = str(username)
  38. if not isinstance(password, basestring):
  39. warnings.warn(
  40. "Non-string passwords will no longer be supported in Requests "
  41. "3.0.0. Please convert the object you've passed in ({0!r}) to "
  42. "a string or bytes object in the near future to avoid "
  43. "problems.".format(password),
  44. category=DeprecationWarning,
  45. )
  46. password = str(password)
  47. # -- End Removal --
  48. if isinstance(username, str):
  49. username = username.encode('latin1')
  50. if isinstance(password, str):
  51. password = password.encode('latin1')
  52. authstr = 'Basic ' + to_native_string(
  53. b64encode(b':'.join((username, password))).strip()
  54. )
  55. return authstr
  56. class AuthBase(object):
  57. """Base class that all auth implementations derive from"""
  58. def __call__(self, r):
  59. raise NotImplementedError('Auth hooks must be callable.')
  60. class HTTPBasicAuth(AuthBase):
  61. """Attaches HTTP Basic Authentication to the given Request object."""
  62. def __init__(self, username, password):
  63. self.username = username
  64. self.password = password
  65. def __eq__(self, other):
  66. return all([
  67. self.username == getattr(other, 'username', None),
  68. self.password == getattr(other, 'password', None)
  69. ])
  70. def __ne__(self, other):
  71. return not self == other
  72. def __call__(self, r):
  73. r.headers['Authorization'] = _basic_auth_str(self.username, self.password)
  74. return r
  75. class HTTPProxyAuth(HTTPBasicAuth):
  76. """Attaches HTTP Proxy Authentication to a given Request object."""
  77. def __call__(self, r):
  78. r.headers['Proxy-Authorization'] = _basic_auth_str(self.username, self.password)
  79. return r
  80. class HTTPDigestAuth(AuthBase):
  81. """Attaches HTTP Digest Authentication to the given Request object."""
  82. def __init__(self, username, password):
  83. self.username = username
  84. self.password = password
  85. # Keep state in per-thread local storage
  86. self._thread_local = threading.local()
  87. def init_per_thread_state(self):
  88. # Ensure state is initialized just once per-thread
  89. if not hasattr(self._thread_local, 'init'):
  90. self._thread_local.init = True
  91. self._thread_local.last_nonce = ''
  92. self._thread_local.nonce_count = 0
  93. self._thread_local.chal = {}
  94. self._thread_local.pos = None
  95. self._thread_local.num_401_calls = None
  96. def build_digest_header(self, method, url):
  97. """
  98. :rtype: str
  99. """
  100. realm = self._thread_local.chal['realm']
  101. nonce = self._thread_local.chal['nonce']
  102. qop = self._thread_local.chal.get('qop')
  103. algorithm = self._thread_local.chal.get('algorithm')
  104. opaque = self._thread_local.chal.get('opaque')
  105. hash_utf8 = None
  106. if algorithm is None:
  107. _algorithm = 'MD5'
  108. else:
  109. _algorithm = algorithm.upper()
  110. # lambdas assume digest modules are imported at the top level
  111. if _algorithm == 'MD5' or _algorithm == 'MD5-SESS':
  112. def md5_utf8(x):
  113. if isinstance(x, str):
  114. x = x.encode('utf-8')
  115. return hashlib.md5(x).hexdigest()
  116. hash_utf8 = md5_utf8
  117. elif _algorithm == 'SHA':
  118. def sha_utf8(x):
  119. if isinstance(x, str):
  120. x = x.encode('utf-8')
  121. return hashlib.sha1(x).hexdigest()
  122. hash_utf8 = sha_utf8
  123. KD = lambda s, d: hash_utf8("%s:%s" % (s, d))
  124. if hash_utf8 is None:
  125. return None
  126. # XXX not implemented yet
  127. entdig = None
  128. p_parsed = urlparse(url)
  129. #: path is request-uri defined in RFC 2616 which should not be empty
  130. path = p_parsed.path or "/"
  131. if p_parsed.query:
  132. path += '?' + p_parsed.query
  133. A1 = '%s:%s:%s' % (self.username, realm, self.password)
  134. A2 = '%s:%s' % (method, path)
  135. HA1 = hash_utf8(A1)
  136. HA2 = hash_utf8(A2)
  137. if nonce == self._thread_local.last_nonce:
  138. self._thread_local.nonce_count += 1
  139. else:
  140. self._thread_local.nonce_count = 1
  141. ncvalue = '%08x' % self._thread_local.nonce_count
  142. s = str(self._thread_local.nonce_count).encode('utf-8')
  143. s += nonce.encode('utf-8')
  144. s += time.ctime().encode('utf-8')
  145. s += os.urandom(8)
  146. cnonce = (hashlib.sha1(s).hexdigest()[:16])
  147. if _algorithm == 'MD5-SESS':
  148. HA1 = hash_utf8('%s:%s:%s' % (HA1, nonce, cnonce))
  149. if not qop:
  150. respdig = KD(HA1, "%s:%s" % (nonce, HA2))
  151. elif qop == 'auth' or 'auth' in qop.split(','):
  152. noncebit = "%s:%s:%s:%s:%s" % (
  153. nonce, ncvalue, cnonce, 'auth', HA2
  154. )
  155. respdig = KD(HA1, noncebit)
  156. else:
  157. # XXX handle auth-int.
  158. return None
  159. self._thread_local.last_nonce = nonce
  160. # XXX should the partial digests be encoded too?
  161. base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
  162. 'response="%s"' % (self.username, realm, nonce, path, respdig)
  163. if opaque:
  164. base += ', opaque="%s"' % opaque
  165. if algorithm:
  166. base += ', algorithm="%s"' % algorithm
  167. if entdig:
  168. base += ', digest="%s"' % entdig
  169. if qop:
  170. base += ', qop="auth", nc=%s, cnonce="%s"' % (ncvalue, cnonce)
  171. return 'Digest %s' % (base)
  172. def handle_redirect(self, r, **kwargs):
  173. """Reset num_401_calls counter on redirects."""
  174. if r.is_redirect:
  175. self._thread_local.num_401_calls = 1
  176. def handle_401(self, r, **kwargs):
  177. """
  178. Takes the given response and tries digest-auth, if needed.
  179. :rtype: requests.Response
  180. """
  181. # If response is not 4xx, do not auth
  182. # See https://github.com/requests/requests/issues/3772
  183. if not 400 <= r.status_code < 500:
  184. self._thread_local.num_401_calls = 1
  185. return r
  186. if self._thread_local.pos is not None:
  187. # Rewind the file position indicator of the body to where
  188. # it was to resend the request.
  189. r.request.body.seek(self._thread_local.pos)
  190. s_auth = r.headers.get('www-authenticate', '')
  191. if 'digest' in s_auth.lower() and self._thread_local.num_401_calls < 2:
  192. self._thread_local.num_401_calls += 1
  193. pat = re.compile(r'digest ', flags=re.IGNORECASE)
  194. self._thread_local.chal = parse_dict_header(pat.sub('', s_auth, count=1))
  195. # Consume content and release the original connection
  196. # to allow our new request to reuse the same one.
  197. r.content
  198. r.close()
  199. prep = r.request.copy()
  200. extract_cookies_to_jar(prep._cookies, r.request, r.raw)
  201. prep.prepare_cookies(prep._cookies)
  202. prep.headers['Authorization'] = self.build_digest_header(
  203. prep.method, prep.url)
  204. _r = r.connection.send(prep, **kwargs)
  205. _r.history.append(r)
  206. _r.request = prep
  207. return _r
  208. self._thread_local.num_401_calls = 1
  209. return r
  210. def __call__(self, r):
  211. # Initialize per-thread state, if needed
  212. self.init_per_thread_state()
  213. # If we have a saved nonce, skip the 401
  214. if self._thread_local.last_nonce:
  215. r.headers['Authorization'] = self.build_digest_header(r.method, r.url)
  216. try:
  217. self._thread_local.pos = r.body.tell()
  218. except AttributeError:
  219. # In the case of HTTPDigestAuth being reused and the body of
  220. # the previous request was a file-like object, pos has the
  221. # file position of the previous body. Ensure it's set to
  222. # None.
  223. self._thread_local.pos = None
  224. r.register_hook('response', self.handle_401)
  225. r.register_hook('response', self.handle_redirect)
  226. self._thread_local.num_401_calls = 1
  227. return r
  228. def __eq__(self, other):
  229. return all([
  230. self.username == getattr(other, 'username', None),
  231. self.password == getattr(other, 'password', None)
  232. ])
  233. def __ne__(self, other):
  234. return not self == other