Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

auth.py 10.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. elif _algorithm == 'SHA-256':
  124. def sha256_utf8(x):
  125. if isinstance(x, str):
  126. x = x.encode('utf-8')
  127. return hashlib.sha256(x).hexdigest()
  128. hash_utf8 = sha256_utf8
  129. elif _algorithm == 'SHA-512':
  130. def sha512_utf8(x):
  131. if isinstance(x, str):
  132. x = x.encode('utf-8')
  133. return hashlib.sha512(x).hexdigest()
  134. hash_utf8 = sha512_utf8
  135. KD = lambda s, d: hash_utf8("%s:%s" % (s, d))
  136. if hash_utf8 is None:
  137. return None
  138. # XXX not implemented yet
  139. entdig = None
  140. p_parsed = urlparse(url)
  141. #: path is request-uri defined in RFC 2616 which should not be empty
  142. path = p_parsed.path or "/"
  143. if p_parsed.query:
  144. path += '?' + p_parsed.query
  145. A1 = '%s:%s:%s' % (self.username, realm, self.password)
  146. A2 = '%s:%s' % (method, path)
  147. HA1 = hash_utf8(A1)
  148. HA2 = hash_utf8(A2)
  149. if nonce == self._thread_local.last_nonce:
  150. self._thread_local.nonce_count += 1
  151. else:
  152. self._thread_local.nonce_count = 1
  153. ncvalue = '%08x' % self._thread_local.nonce_count
  154. s = str(self._thread_local.nonce_count).encode('utf-8')
  155. s += nonce.encode('utf-8')
  156. s += time.ctime().encode('utf-8')
  157. s += os.urandom(8)
  158. cnonce = (hashlib.sha1(s).hexdigest()[:16])
  159. if _algorithm == 'MD5-SESS':
  160. HA1 = hash_utf8('%s:%s:%s' % (HA1, nonce, cnonce))
  161. if not qop:
  162. respdig = KD(HA1, "%s:%s" % (nonce, HA2))
  163. elif qop == 'auth' or 'auth' in qop.split(','):
  164. noncebit = "%s:%s:%s:%s:%s" % (
  165. nonce, ncvalue, cnonce, 'auth', HA2
  166. )
  167. respdig = KD(HA1, noncebit)
  168. else:
  169. # XXX handle auth-int.
  170. return None
  171. self._thread_local.last_nonce = nonce
  172. # XXX should the partial digests be encoded too?
  173. base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
  174. 'response="%s"' % (self.username, realm, nonce, path, respdig)
  175. if opaque:
  176. base += ', opaque="%s"' % opaque
  177. if algorithm:
  178. base += ', algorithm="%s"' % algorithm
  179. if entdig:
  180. base += ', digest="%s"' % entdig
  181. if qop:
  182. base += ', qop="auth", nc=%s, cnonce="%s"' % (ncvalue, cnonce)
  183. return 'Digest %s' % (base)
  184. def handle_redirect(self, r, **kwargs):
  185. """Reset num_401_calls counter on redirects."""
  186. if r.is_redirect:
  187. self._thread_local.num_401_calls = 1
  188. def handle_401(self, r, **kwargs):
  189. """
  190. Takes the given response and tries digest-auth, if needed.
  191. :rtype: requests.Response
  192. """
  193. # If response is not 4xx, do not auth
  194. # See https://github.com/requests/requests/issues/3772
  195. if not 400 <= r.status_code < 500:
  196. self._thread_local.num_401_calls = 1
  197. return r
  198. if self._thread_local.pos is not None:
  199. # Rewind the file position indicator of the body to where
  200. # it was to resend the request.
  201. r.request.body.seek(self._thread_local.pos)
  202. s_auth = r.headers.get('www-authenticate', '')
  203. if 'digest' in s_auth.lower() and self._thread_local.num_401_calls < 2:
  204. self._thread_local.num_401_calls += 1
  205. pat = re.compile(r'digest ', flags=re.IGNORECASE)
  206. self._thread_local.chal = parse_dict_header(pat.sub('', s_auth, count=1))
  207. # Consume content and release the original connection
  208. # to allow our new request to reuse the same one.
  209. r.content
  210. r.close()
  211. prep = r.request.copy()
  212. extract_cookies_to_jar(prep._cookies, r.request, r.raw)
  213. prep.prepare_cookies(prep._cookies)
  214. prep.headers['Authorization'] = self.build_digest_header(
  215. prep.method, prep.url)
  216. _r = r.connection.send(prep, **kwargs)
  217. _r.history.append(r)
  218. _r.request = prep
  219. return _r
  220. self._thread_local.num_401_calls = 1
  221. return r
  222. def __call__(self, r):
  223. # Initialize per-thread state, if needed
  224. self.init_per_thread_state()
  225. # If we have a saved nonce, skip the 401
  226. if self._thread_local.last_nonce:
  227. r.headers['Authorization'] = self.build_digest_header(r.method, r.url)
  228. try:
  229. self._thread_local.pos = r.body.tell()
  230. except AttributeError:
  231. # In the case of HTTPDigestAuth being reused and the body of
  232. # the previous request was a file-like object, pos has the
  233. # file position of the previous body. Ensure it's set to
  234. # None.
  235. self._thread_local.pos = None
  236. r.register_hook('response', self.handle_401)
  237. r.register_hook('response', self.handle_redirect)
  238. self._thread_local.num_401_calls = 1
  239. return r
  240. def __eq__(self, other):
  241. return all([
  242. self.username == getattr(other, 'username', None),
  243. self.password == getattr(other, 'password', None)
  244. ])
  245. def __ne__(self, other):
  246. return not self == other