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