auth.py 9.9 KB

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