summaryrefslogtreecommitdiff
path: root/cherrypy/lib/auth_digest.py
diff options
context:
space:
mode:
authorSviatoslav Sydorenko <wk@sydorenko.org.ua>2018-04-22 13:14:02 +0200
committerSviatoslav Sydorenko <wk@sydorenko.org.ua>2018-04-22 13:14:02 +0200
commit13e9f4019707722318e27e3574f67c837ecf60c1 (patch)
treeb25c5f954e88f891fa9f12fa79e4a0bdf503aac0 /cherrypy/lib/auth_digest.py
parent1af9a1d6342a50c5dc8ce61dd7b6abf70f94d301 (diff)
parent7247bf76d619197161c0440e15abe384833ffdc5 (diff)
downloadcherrypy-git-14.2.0.tar.gz
Support unicode in login/password during HTTP Authv14.2.0
Ref: :rfc:`7617`
Diffstat (limited to 'cherrypy/lib/auth_digest.py')
-rw-r--r--cherrypy/lib/auth_digest.py98
1 files changed, 76 insertions, 22 deletions
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