auth.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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 is request-uri defined in RFC 2616 which should not be empty
  81. path = p_parsed.path or "/"
  82. if p_parsed.query:
  83. path += '?' + p_parsed.query
  84. A1 = '%s:%s:%s' % (self.username, realm, self.password)
  85. A2 = '%s:%s' % (method, path)
  86. HA1 = hash_utf8(A1)
  87. HA2 = hash_utf8(A2)
  88. if nonce == self.last_nonce:
  89. self.nonce_count += 1
  90. else:
  91. self.nonce_count = 1
  92. ncvalue = '%08x' % self.nonce_count
  93. s = str(self.nonce_count).encode('utf-8')
  94. s += nonce.encode('utf-8')
  95. s += time.ctime().encode('utf-8')
  96. s += os.urandom(8)
  97. cnonce = (hashlib.sha1(s).hexdigest()[:16])
  98. if _algorithm == 'MD5-SESS':
  99. HA1 = hash_utf8('%s:%s:%s' % (HA1, nonce, cnonce))
  100. if qop is None:
  101. respdig = KD(HA1, "%s:%s" % (nonce, HA2))
  102. elif qop == 'auth' or 'auth' in qop.split(','):
  103. noncebit = "%s:%s:%s:%s:%s" % (
  104. nonce, ncvalue, cnonce, 'auth', HA2
  105. )
  106. respdig = KD(HA1, noncebit)
  107. else:
  108. # XXX handle auth-int.
  109. return None
  110. self.last_nonce = nonce
  111. # XXX should the partial digests be encoded too?
  112. base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
  113. 'response="%s"' % (self.username, realm, nonce, path, respdig)
  114. if opaque:
  115. base += ', opaque="%s"' % opaque
  116. if algorithm:
  117. base += ', algorithm="%s"' % algorithm
  118. if entdig:
  119. base += ', digest="%s"' % entdig
  120. if qop:
  121. base += ', qop="auth", nc=%s, cnonce="%s"' % (ncvalue, cnonce)
  122. return 'Digest %s' % (base)
  123. def handle_redirect(self, r, **kwargs):
  124. """Reset num_401_calls counter on redirects."""
  125. if r.is_redirect:
  126. self.num_401_calls = 1
  127. def handle_401(self, r, **kwargs):
  128. """Takes the given response and tries digest-auth, if needed."""
  129. if self.pos is not None:
  130. # Rewind the file position indicator of the body to where
  131. # it was to resend the request.
  132. r.request.body.seek(self.pos)
  133. num_401_calls = getattr(self, 'num_401_calls', 1)
  134. s_auth = r.headers.get('www-authenticate', '')
  135. if 'digest' in s_auth.lower() and num_401_calls < 2:
  136. self.num_401_calls += 1
  137. pat = re.compile(r'digest ', flags=re.IGNORECASE)
  138. self.chal = parse_dict_header(pat.sub('', s_auth, count=1))
  139. # Consume content and release the original connection
  140. # to allow our new request to reuse the same one.
  141. r.content
  142. r.raw.release_conn()
  143. prep = r.request.copy()
  144. extract_cookies_to_jar(prep._cookies, r.request, r.raw)
  145. prep.prepare_cookies(prep._cookies)
  146. prep.headers['Authorization'] = self.build_digest_header(
  147. prep.method, prep.url)
  148. _r = r.connection.send(prep, **kwargs)
  149. _r.history.append(r)
  150. _r.request = prep
  151. return _r
  152. self.num_401_calls = 1
  153. return r
  154. def __call__(self, r):
  155. # If we have a saved nonce, skip the 401
  156. if self.last_nonce:
  157. r.headers['Authorization'] = self.build_digest_header(r.method, r.url)
  158. try:
  159. self.pos = r.body.tell()
  160. except AttributeError:
  161. # In the case of HTTPDigestAuth being reused and the body of
  162. # the previous request was a file-like object, pos has the
  163. # file position of the previous body. Ensure it's set to
  164. # None.
  165. self.pos = None
  166. r.register_hook('response', self.handle_401)
  167. r.register_hook('response', self.handle_redirect)
  168. return r