Implement GSSAPI/Kerberos authentication for requests
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Currently has two issues which may be related: - doesn't work with redirects, we try to authenticate the server a second time with a fully completed kerberos context. - 403 responses result in the wrong response object being returned, but this is also true for http digest authentication due to a bug in hook handling in general.
authored by Michael Komitee · committed by Michael Komitee · parent 77a57c0 · Browse files · 1 file·+130 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
1 file+130 added−0 removed
- other:+130 added−0 removed
Provenance
- Commit
c803e3a- Tree
6f693e2- Author
Michael Komitee <komitee@deshaw.com>- Committer
Michael Komitee <komitee@deshaw.com>- Parent
77a57c0
1 file changed+130 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, str7 unmodified lines26 except (ImportError, SyntaxError):27 SIGNATURE_HMAC = None28 SIGNATURE_TYPE_AUTH_HEADER = None29 30+try:31+ import kerberos as k32+except ImportError as exc:33+ k = None34+35+log = logging.getLogger(__name__)36+37 CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'38 39 def _basic_auth_str(username, password):40 """Returns a Basic Auth string."""194 unmodified lines235 236 def __call__(self, r):237 r.register_hook('response', self.handle_401)238 return r239+240+def _negotiate_value(r):241+ """Extracts the gssapi authentication token from the appropriate header"""242+243+ authreq = r.headers.get('www-authenticate', None)244+245+ if authreq:246+ rx = re.compile('(?:.*,)*\s*Negotiate\s*([^,]*),?', re.I)247+ mo = rx.search(authreq)248+ if mo:249+ return mo.group(1)250+251+ return None252+253+class HTTPKerberosAuth(AuthBase):254+ """Attaches HTTP GSSAPI/Kerberos Authentication to the given Request object."""255+ def __init__(self, require_mutual_auth=True):256+ if k is None:257+ raise Exception("Kerberos libraries unavailable")258+ self.context = None259+ self.require_mutual_auth = require_mutual_auth260+261+ def generate_request_header(self, r):262+ """Generates the gssapi authentication token with kerberos"""263+264+ host = urlparse(r.url).netloc265+ tail, _, head = host.rpartition(':')266+ domain = tail if tail else head267+268+ result, self.context = k.authGSSClientInit("HTTP@%s" % domain)269+270+ if result < 1:271+ raise Exception("authGSSClientInit failed")272+273+ result = k.authGSSClientStep(self.context, _negotiate_value(r))274+275+ if result < 0:276+ raise Exception("authGSSClientStep failed")277+278+ response = k.authGSSClientResponse(self.context)279+280+ return "Negotiate %s" % response281+282+ def authenticate_user(self, r):283+ """Handles user authentication with gssapi/kerberos"""284+285+ auth_header = self.generate_request_header(r)286+ log.debug("authenticate_user(): Authorization header: %s" % auth_header)287+ r.request.headers['Authorization'] = auth_header288+ r.request.send(anyway=True)289+ _r = r.request.response290+ _r.history.append(r)291+ log.debug("authenticate_user(): returning %s" % _r)292+ return _r293+294+ def handle_401(self, r):295+ """Handles 401's, attempts to use gssapi/kerberos authentication"""296+297+ log.debug("handle_401(): Handling: 401")298+ if _negotiate_value(r) is not None:299+ _r = self.authenticate_user(r)300+ log.debug("handle_401(): returning %s" % _r)301+ return _r302+ else:303+ log.debug("handle_401(): Kerberos is not supported")304+ log.debug("handle_401(): returning %s" % r)305+ return r306+307+ def handle_other(self, r):308+ """Handles all responses with the exception of 401s.309+310+ This is necessary so that we can authenticate responses if requested"""311+312+ log.debug("handle_other(): Handling: %d" % r.status_code)313+ self.deregister(r)314+ if self.require_mutual_auth:315+ if _negotiate_value(r) is not None:316+ log.debug("handle_other(): Authenticating the server")317+ _r = self.authenticate_server(r)318+ log.debug("handle_other(): returning %s" % _r)319+ return _r320+ else:321+ log.error("handle_other(): Mutual authentication failed")322+ raise Exception("Mutual authentication failed")323+ else:324+ log.debug("handle_other(): returning %s" % r)325+ return r326+327+ def authenticate_server(self, r):328+ """Uses GSSAPI to authenticate the server"""329+330+ log.debug("authenticate_server(): Authenticate header: %s" % _negotiate_value(r))331+ result = k.authGSSClientStep(self.context, _negotiate_value(r))332+ if result < 1:333+ raise Exception("authGSSClientStep failed")334+ _r = r.request.response335+ log.debug("authenticate_server(): returning %s" % _r)336+ return _r337+338+ def handle_response(self, r):339+ """Takes the given response and tries kerberos-auth, as needed."""340+341+ if r.status_code == 401:342+ _r = self.handle_401(r)343+ log.debug("handle_response returning %s" % _r)344+ return _r345+ else:346+ _r = self.handle_other(r)347+ log.debug("handle_response returning %s" % _r)348+ return _r349+350+ log.debug("handle_response returning %s" % r)351+ return r352+353+ def deregister(self, r):354+ """Deregisters the response handler"""355+ r.request.deregister_hook('response', self.handle_response)356+357+ def __call__(self, r):358+ r.register_hook('response', self.handle_response)359+ return r