Skip to content
Myr

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

1 file+130 added−0 removed

modified:requests/auth.py+130 added
6 unmodified lines
7This module contains the authentication handlers for Requests.8"""910import os11import re12import time13import hashlib14import logging1516from base64 import b64encode1718from .compat import urlparse, str
7 unmodified lines
26except (ImportError, SyntaxError):27 SIGNATURE_HMAC = None28 SIGNATURE_TYPE_AUTH_HEADER = None2930try:31 import kerberos as k32except ImportError as exc:33 k = None3435log = logging.getLogger(__name__)3637CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'3839def _basic_auth_str(username, password):40 """Returns a Basic Auth string."""
194 unmodified lines
235236 def __call__(self, r):237 r.register_hook('response', self.handle_401)238 return r239240def _negotiate_value(r):241 """Extracts the gssapi authentication token from the appropriate header"""242243 authreq = r.headers.get('www-authenticate', None)244245 if authreq:246 rx = re.compile('(?:.*,)*\s*Negotiate\s*([^,]*),?', re.I)247 mo = rx.search(authreq)248 if mo:249 return mo.group(1)250251 return None252253class 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_auth260261 def generate_request_header(self, r):262 """Generates the gssapi authentication token with kerberos"""263264 host = urlparse(r.url).netloc265 tail, _, head = host.rpartition(':')266 domain = tail if tail else head267268 result, self.context = k.authGSSClientInit("HTTP@%s" % domain)269270 if result < 1:271 raise Exception("authGSSClientInit failed")272273 result = k.authGSSClientStep(self.context, _negotiate_value(r))274275 if result < 0:276 raise Exception("authGSSClientStep failed")277278 response = k.authGSSClientResponse(self.context)279280 return "Negotiate %s" % response281282 def authenticate_user(self, r):283 """Handles user authentication with gssapi/kerberos"""284285 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 _r293294 def handle_401(self, r):295 """Handles 401's, attempts to use gssapi/kerberos authentication"""296297 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 r306307 def handle_other(self, r):308 """Handles all responses with the exception of 401s.309310 This is necessary so that we can authenticate responses if requested"""311312 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 r326327 def authenticate_server(self, r):328 """Uses GSSAPI to authenticate the server"""329330 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 _r337338 def handle_response(self, r):339 """Takes the given response and tries kerberos-auth, as needed."""340341 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 _r349350 log.debug("handle_response returning %s" % r)351 return r352353 def deregister(self, r):354 """Deregisters the response handler"""355 r.request.deregister_hook('response', self.handle_response)356357 def __call__(self, r):358 r.register_hook('response', self.handle_response)359 return r