Merge remote-tracking branch 'origin/develop' into develop
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kenneth Reitz · committed by Kenneth Reitz · parents c650651, bc63617 · Browse files · 2 files·+137 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+137 added−0 removed
- other:+137 added−0 removed
Provenance
- Commit
8120778- Tree
de22ca1- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
c650651- Parent 2
bc63617
2 files changed+137 added−0 removed
modified:requests/auth.py+130 added
6 unmodified lines7 This module contains the authentication handlers for Requests.8 """9 10 import os11+import re12 import time13 import hashlib14+import logging15 16 from base64 import b64encode17 18 from .compat import urlparse, str5 unmodified lines24 except (ImportError, SyntaxError):25 SIGNATURE_HMAC = None26 SIGNATURE_TYPE_AUTH_HEADER = None27 28+try:29+ import kerberos as k30+except ImportError as exc:31+ k = None32+33+log = logging.getLogger(__name__)34+35 CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'36 37 def _basic_auth_str(username, password):38 """Returns a Basic Auth string."""194 unmodified lines233 234 def __call__(self, r):235 r.register_hook('response', self.handle_401)236 return r237+238+def _negotiate_value(r):239+ """Extracts the gssapi authentication token from the appropriate header"""240+241+ authreq = r.headers.get('www-authenticate', None)242+243+ if authreq:244+ rx = re.compile('(?:.*,)*\s*Negotiate\s*([^,]*),?', re.I)245+ mo = rx.search(authreq)246+ if mo:247+ return mo.group(1)248+249+ return None250+251+class HTTPKerberosAuth(AuthBase):252+ """Attaches HTTP GSSAPI/Kerberos Authentication to the given Request object."""253+ def __init__(self, require_mutual_auth=True):254+ if k is None:255+ raise Exception("Kerberos libraries unavailable")256+ self.context = None257+ self.require_mutual_auth = require_mutual_auth258+259+ def generate_request_header(self, r):260+ """Generates the gssapi authentication token with kerberos"""261+262+ host = urlparse(r.url).netloc263+ tail, _, head = host.rpartition(':')264+ domain = tail if tail else head265+266+ result, self.context = k.authGSSClientInit("HTTP@%s" % domain)267+268+ if result < 1:269+ raise Exception("authGSSClientInit failed")270+271+ result = k.authGSSClientStep(self.context, _negotiate_value(r))272+273+ if result < 0:274+ raise Exception("authGSSClientStep failed")275+276+ response = k.authGSSClientResponse(self.context)277+278+ return "Negotiate %s" % response279+280+ def authenticate_user(self, r):281+ """Handles user authentication with gssapi/kerberos"""282+283+ auth_header = self.generate_request_header(r)284+ log.debug("authenticate_user(): Authorization header: %s" % auth_header)285+ r.request.headers['Authorization'] = auth_header286+ r.request.send(anyway=True)287+ _r = r.request.response288+ _r.history.append(r)289+ log.debug("authenticate_user(): returning %s" % _r)290+ return _r291+292+ def handle_401(self, r):293+ """Handles 401's, attempts to use gssapi/kerberos authentication"""294+295+ log.debug("handle_401(): Handling: 401")296+ if _negotiate_value(r) is not None:297+ _r = self.authenticate_user(r)298+ log.debug("handle_401(): returning %s" % _r)299+ return _r300+ else:301+ log.debug("handle_401(): Kerberos is not supported")302+ log.debug("handle_401(): returning %s" % r)303+ return r304+305+ def handle_other(self, r):306+ """Handles all responses with the exception of 401s.307+308+ This is necessary so that we can authenticate responses if requested"""309+310+ log.debug("handle_other(): Handling: %d" % r.status_code)311+ self.deregister(r)312+ if self.require_mutual_auth:313+ if _negotiate_value(r) is not None:314+ log.debug("handle_other(): Authenticating the server")315+ _r = self.authenticate_server(r)316+ log.debug("handle_other(): returning %s" % _r)317+ return _r318+ else:319+ log.error("handle_other(): Mutual authentication failed")320+ raise Exception("Mutual authentication failed")321+ else:322+ log.debug("handle_other(): returning %s" % r)323+ return r324+325+ def authenticate_server(self, r):326+ """Uses GSSAPI to authenticate the server"""327+328+ log.debug("authenticate_server(): Authenticate header: %s" % _negotiate_value(r))329+ result = k.authGSSClientStep(self.context, _negotiate_value(r))330+ if result < 1:331+ raise Exception("authGSSClientStep failed")332+ _r = r.request.response333+ log.debug("authenticate_server(): returning %s" % _r)334+ return _r335+336+ def handle_response(self, r):337+ """Takes the given response and tries kerberos-auth, as needed."""338+339+ if r.status_code == 401:340+ _r = self.handle_401(r)341+ log.debug("handle_response returning %s" % _r)342+ return _r343+ else:344+ _r = self.handle_other(r)345+ log.debug("handle_response returning %s" % _r)346+ return _r347+348+ log.debug("handle_response returning %s" % r)349+ return r350+351+ def deregister(self, r):352+ """Deregisters the response handler"""353+ r.request.deregister_hook('response', self.handle_response)354+355+ def __call__(self, r):356+ r.register_hook('response', self.handle_response)357+ return rmodified:requests/models.py+7 added
353 unmodified lines354 if isinstance(fp, (bytes, str)):355 fp = StringIO(fp)356 fields.update({k: (fn, fp.read())})357 358+ for field in fields:359+ if isinstance(fields[field], float):360+ fields[field] = str(fields[field])361+ if isinstance(fields[field], list):362+ newvalue = ', '.join(fields[field])363+ fields[field] = newvalue364+ 365 (body, content_type) = encode_multipart_formdata(fields)366 367 return (body, content_type)368 475 unmodified lines