diff options
| author | Sviatoslav Sydorenko <wk@sydorenko.org.ua> | 2018-04-22 13:14:02 +0200 |
|---|---|---|
| committer | Sviatoslav Sydorenko <wk@sydorenko.org.ua> | 2018-04-22 13:14:02 +0200 |
| commit | 13e9f4019707722318e27e3574f67c837ecf60c1 (patch) | |
| tree | b25c5f954e88f891fa9f12fa79e4a0bdf503aac0 /cherrypy/lib | |
| parent | 1af9a1d6342a50c5dc8ce61dd7b6abf70f94d301 (diff) | |
| parent | 7247bf76d619197161c0440e15abe384833ffdc5 (diff) | |
| download | cherrypy-git-14.2.0.tar.gz | |
Support unicode in login/password during HTTP Authv14.2.0
Ref: :rfc:`7617`
Diffstat (limited to 'cherrypy/lib')
| -rw-r--r-- | cherrypy/lib/auth_basic.py | 53 | ||||
| -rw-r--r-- | cherrypy/lib/auth_digest.py | 98 |
2 files changed, 117 insertions, 34 deletions
diff --git a/cherrypy/lib/auth_basic.py b/cherrypy/lib/auth_basic.py index 44eb9b14..59e95f3c 100644 --- a/cherrypy/lib/auth_basic.py +++ b/cherrypy/lib/auth_basic.py @@ -1,14 +1,9 @@ # This file is part of CherryPy <http://www.cherrypy.org/> # -*- coding: utf-8 -*- # vim:ts=4:sw=4:expandtab:fileencoding=utf-8 +"""HTTP Basic Authentication tool. -import binascii - -import cherrypy -from cherrypy._cpcompat import base64_decode - - -__doc__ = """This module provides a CherryPy 3.x tool which implements +This module provides a CherryPy 3.x tool which implements the server-side of HTTP Basic Access Authentication, as described in :rfc:`2617`. @@ -20,11 +15,19 @@ as the credentials store:: basic_auth = {'tools.auth_basic.on': True, 'tools.auth_basic.realm': 'earth', 'tools.auth_basic.checkpassword': checkpassword, + 'tools.auth_basic.accept_charset': 'UTF-8', } app_config = { '/' : basic_auth } """ +import binascii +import unicodedata + +import cherrypy +from cherrypy._cpcompat import base64_decode, ntob, ntou, tonative + + __author__ = 'visteya' __date__ = 'April 2009' @@ -44,9 +47,10 @@ def checkpassword_dict(user_password_dict): return checkpassword -def basic_auth(realm, checkpassword, debug=False): +def basic_auth(realm, checkpassword, debug=False, accept_charset='utf-8'): """A CherryPy tool which hooks at before_handler to perform - HTTP Basic Access Authentication, as specified in :rfc:`2617`. + HTTP Basic Access Authentication, as specified in :rfc:`2617` + and :rfc:`7617`. If the request has an 'authorization' header with a 'Basic' scheme, this tool attempts to authenticate the credentials supplied in that header. If @@ -66,6 +70,8 @@ def basic_auth(realm, checkpassword, debug=False): """ + fallback_charset = 'ISO-8859-1' + if '"' in realm: raise ValueError('Realm cannot contain the " (quote) character.') request = cherrypy.serving.request @@ -77,15 +83,38 @@ def basic_auth(realm, checkpassword, debug=False): with cherrypy.HTTPError.handle((ValueError, binascii.Error), 400, msg): scheme, params = auth_header.split(' ', 1) if scheme.lower() == 'basic': - username, password = base64_decode(params).split(':', 1) + decoded_params = base64_decode(params) + decoded_params = ntob(decoded_params) + + last_err = None + for charset in (accept_charset, fallback_charset): + try: + decoded_params = tonative(decoded_params, charset) + break + except ValueError as ve: + last_err = ve + else: + raise last_err + + decoded_params = ntou(decoded_params) + decoded_params = unicodedata.normalize('NFC', decoded_params) + decoded_params = tonative(decoded_params) + username, password = decoded_params.split(':', 1) if checkpassword(realm, username, password): if debug: cherrypy.log('Auth succeeded', 'TOOLS.AUTH_BASIC') request.login = username return # successful authentication + charset = accept_charset.upper() + charset_declaration = ( + (', charset="%s"' % charset) + if charset != fallback_charset + else '' + ) # Respond with 401 status and a WWW-Authenticate header - cherrypy.serving.response.headers[ - 'www-authenticate'] = 'Basic realm="%s"' % realm + cherrypy.serving.response.headers['www-authenticate'] = ( + 'Basic realm="%s"%s' % (realm, charset_declaration) + ) raise cherrypy.HTTPError( 401, 'You are not authorized to access that resource') diff --git a/cherrypy/lib/auth_digest.py b/cherrypy/lib/auth_digest.py index b604bf6d..92265c5a 100644 --- a/cherrypy/lib/auth_digest.py +++ b/cherrypy/lib/auth_digest.py @@ -1,17 +1,9 @@ # This file is part of CherryPy <http://www.cherrypy.org/> # -*- coding: utf-8 -*- # vim:ts=4:sw=4:expandtab:fileencoding=utf-8 +"""HTTP Digest Authentication tool. -import time -from hashlib import md5 - -from six.moves.urllib.request import parse_http_list, parse_keqv_list - -import cherrypy -from cherrypy._cpcompat import ntob - - -__doc__ = """An implementation of the server-side of HTTP Digest Access +An implementation of the server-side of HTTP Digest Access Authentication, which is described in :rfc:`2617`. Example usage, using the built-in get_ha1_dict_plain function which uses a dict @@ -23,16 +15,27 @@ of plaintext passwords as the credentials store:: 'tools.auth_digest.realm': 'wonderland', 'tools.auth_digest.get_ha1': get_ha1, 'tools.auth_digest.key': 'a565c27146791cfb', + 'tools.auth_digest.accept_charset': 'UTF-8', } app_config = { '/' : digest_auth } """ +import time +from hashlib import md5 + +from six.moves.urllib.parse import unquote_to_bytes +from six.moves.urllib.request import parse_http_list, parse_keqv_list + +import cherrypy +from cherrypy._cpcompat import ntob, tonative + + __author__ = 'visteya' __date__ = 'April 2009' def md5_hex(s): - return md5(ntob(s)).hexdigest() + return md5(ntob(s, 'utf-8')).hexdigest() qop_auth = 'auth' @@ -41,6 +44,9 @@ valid_qops = (qop_auth, qop_auth_int) valid_algorithms = ('MD5', 'MD5-sess') +FALLBACK_CHARSET = 'ISO-8859-1' +DEFAULT_CHARSET = 'UTF-8' + def TRACE(msg): cherrypy.log(msg, context='TOOLS.AUTH_DIGEST') @@ -135,6 +141,21 @@ def H(s): return md5_hex(s) +def _try_decode_map_values(param_map, charset): + global FALLBACK_CHARSET + + for enc in (charset, FALLBACK_CHARSET): + try: + return { + k: tonative(v, enc) + for k, v in param_map.items() + } + except ValueError as ve: + last_err = ve + else: + raise last_err + + class HttpDigestAuthorization (object): """Class to parse a Digest Authorization header and perform re-calculation @@ -144,7 +165,10 @@ class HttpDigestAuthorization (object): def errmsg(self, s): return 'Digest Authorization header: %s' % s - def __init__(self, auth_header, http_method, debug=False): + def __init__( + self, auth_header, http_method, + debug=False, accept_charset=DEFAULT_CHARSET[:], + ): self.http_method = http_method self.debug = debug scheme, params = auth_header.split(' ', 1) @@ -157,6 +181,11 @@ class HttpDigestAuthorization (object): # make a dict of the params items = parse_http_list(params) paramsd = parse_keqv_list(items) + paramsd = { + k: unquote_to_bytes(v) + for k, v in paramsd.items() + } + paramsd = _try_decode_map_values(paramsd, accept_charset) self.realm = paramsd.get('realm') self.username = paramsd.get('username') @@ -307,24 +336,43 @@ class HttpDigestAuthorization (object): return digest -def www_authenticate(realm, key, algorithm='MD5', nonce=None, qop=qop_auth, - stale=False): +def _get_charset_declaration(charset): + global FALLBACK_CHARSET + charset = charset.upper() + return ( + (', charset="%s"' % charset) + if charset != FALLBACK_CHARSET + else '' + ) + + +def www_authenticate( + realm, key, algorithm='MD5', nonce=None, qop=qop_auth, + stale=False, accept_charset=DEFAULT_CHARSET[:], +): """Constructs a WWW-Authenticate header for Digest authentication.""" if qop not in valid_qops: raise ValueError("Unsupported value for qop: '%s'" % qop) if algorithm not in valid_algorithms: raise ValueError("Unsupported value for algorithm: '%s'" % algorithm) + HEADER_PATTERN = ( + 'Digest realm="%s", nonce="%s", algorithm="%s", qop="%s"%s%s' + ) + if nonce is None: nonce = synthesize_nonce(realm, key) - s = 'Digest realm="%s", nonce="%s", algorithm="%s", qop="%s"' % ( - realm, nonce, algorithm, qop) - if stale: - s += ', stale="true"' - return s + + stale_param = ', stale="true"' if stale else '' + + charset_declaration = _get_charset_declaration(accept_charset) + + return HEADER_PATTERN % ( + realm, nonce, algorithm, qop, stale_param, charset_declaration, + ) -def digest_auth(realm, get_ha1, key, debug=False): +def digest_auth(realm, get_ha1, key, debug=False, accept_charset='utf-8'): """A CherryPy tool which hooks at before_handler to perform HTTP Digest Access Authentication, as specified in :rfc:`2617`. @@ -359,7 +407,9 @@ def digest_auth(realm, get_ha1, key, debug=False): msg = 'The Authorization header could not be parsed.' with cherrypy.HTTPError.handle(ValueError, 400, msg): auth = HttpDigestAuthorization( - auth_header, request.method, debug=debug) + auth_header, request.method, + debug=debug, accept_charset=accept_charset, + ) if debug: TRACE(str(auth)) @@ -386,7 +436,11 @@ def digest_auth(realm, get_ha1, key, debug=False): return # Respond with 401 status and a WWW-Authenticate header - header = www_authenticate(realm, key, stale=nonce_is_stale) + header = www_authenticate( + realm, key, + stale=nonce_is_stale, + accept_charset=accept_charset, + ) if debug: TRACE(header) cherrypy.serving.response.headers['WWW-Authenticate'] = header |
