Skip to content
Myr

Merge pull request #647 from mkomitee/kerberos

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Implement GSSAPI/Kerberos authentication for requests

authored by Kenneth Reitz · committed by Kenneth Reitz · parents 31e768f, c803e3a · 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
5 unmodified lines
24except (ImportError, SyntaxError):25 SIGNATURE_HMAC = None26 SIGNATURE_TYPE_AUTH_HEADER = None2728try:29 import kerberos as k30except ImportError as exc:31 k = None3233log = logging.getLogger(__name__)3435CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'3637def _basic_auth_str(username, password):38 """Returns a Basic Auth string."""
194 unmodified lines
233234 def __call__(self, r):235 r.register_hook('response', self.handle_401)236 return r237238def _negotiate_value(r):239 """Extracts the gssapi authentication token from the appropriate header"""240241 authreq = r.headers.get('www-authenticate', None)242243 if authreq:244 rx = re.compile('(?:.*,)*\s*Negotiate\s*([^,]*),?', re.I)245 mo = rx.search(authreq)246 if mo:247 return mo.group(1)248249 return None250251class 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_auth258259 def generate_request_header(self, r):260 """Generates the gssapi authentication token with kerberos"""261262 host = urlparse(r.url).netloc263 tail, _, head = host.rpartition(':')264 domain = tail if tail else head265266 result, self.context = k.authGSSClientInit("HTTP@%s" % domain)267268 if result < 1:269 raise Exception("authGSSClientInit failed")270271 result = k.authGSSClientStep(self.context, _negotiate_value(r))272273 if result < 0:274 raise Exception("authGSSClientStep failed")275276 response = k.authGSSClientResponse(self.context)277278 return "Negotiate %s" % response279280 def authenticate_user(self, r):281 """Handles user authentication with gssapi/kerberos"""282283 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 _r291292 def handle_401(self, r):293 """Handles 401's, attempts to use gssapi/kerberos authentication"""294295 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 r304305 def handle_other(self, r):306 """Handles all responses with the exception of 401s.307308 This is necessary so that we can authenticate responses if requested"""309310 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 r324325 def authenticate_server(self, r):326 """Uses GSSAPI to authenticate the server"""327328 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 _r335336 def handle_response(self, r):337 """Takes the given response and tries kerberos-auth, as needed."""338339 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 _r347348 log.debug("handle_response returning %s" % r)349 return r350351 def deregister(self, r):352 """Deregisters the response handler"""353 r.request.deregister_hook('response', self.handle_response)354355 def __call__(self, r):356 r.register_hook('response', self.handle_response)357 return r