Skip to content

Instantly share code, notes, and snippets.

@PJaros
Created January 5, 2018 09:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PJaros/b624e1b600d197c227b132f3c34ba3db to your computer and use it in GitHub Desktop.
Save PJaros/b624e1b600d197c227b132f3c34ba3db to your computer and use it in GitHub Desktop.
https://github.com/cherrypy/cherrypy/pull/1683 with some hexcode(...) sprinkled to debug the intermediate results. I've added the relevant output testing with the different browsers available
# This file is part of CherryPy <http://www.cherrypy.org/>
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:expandtab:fileencoding=utf-8
import binascii
import unicodedata
import cherrypy
from cherrypy._cpcompat import base64_decode, ntob, ntou, tonative
__doc__ = """This module provides a CherryPy 3.x tool which implements
the server-side of HTTP Basic Access Authentication, as described in
:rfc:`2617`.
Example usage, using the built-in checkpassword_dict function which uses a dict
as the credentials store::
userpassdict = {'bird' : 'bebop', 'ornette' : 'wayout'}
checkpassword = cherrypy.lib.auth_basic.checkpassword_dict(userpassdict)
basic_auth = {'tools.auth_basic.on': True,
'tools.auth_basic.realm': 'earth',
'tools.auth_basic.checkpassword': checkpassword,
}
app_config = { '/' : basic_auth }
"""
__author__ = 'visteya'
__date__ = 'April 2009'
def checkpassword_dict(user_password_dict):
"""Returns a checkpassword function which checks credentials
against a dictionary of the form: {username : password}.
If you want a simple dictionary-based authentication scheme, use
checkpassword_dict(my_credentials_dict) as the value for the
checkpassword argument to basic_auth().
"""
def checkpassword(realm, user, password):
p = user_password_dict.get(user)
return p and p == password or False
return checkpassword
def to_ord(n):
if type(n) is not type(0):
return ord(n)
else:
return n
def hexcode(s):
return ' '.join(hex(to_ord(x))[2:] for x in s)
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`
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
the request has no 'authorization' header, or if it does but the scheme is
not 'Basic', or if authentication fails, the tool sends a 401 response with
a 'WWW-Authenticate' Basic header.
realm
A string containing the authentication realm.
checkpassword
A callable which checks the authentication credentials.
Its signature is checkpassword(realm, username, password). where
username and password are the values obtained from the request's
'authorization' header. If authentication succeeds, checkpassword
returns True, else it returns False.
"""
fallback_charset = 'ISO-8859-1'
if '"' in realm:
raise ValueError('Realm cannot contain the " (quote) character.')
request = cherrypy.serving.request
auth_header = request.headers.get('authorization')
if auth_header is not None:
# split() error, base64.decodestring() error
msg = 'Bad Request'
with cherrypy.HTTPError.handle((ValueError, binascii.Error), 400, msg):
scheme, params = auth_header.split(' ', 1)
if scheme.lower() == 'basic':
decoded_params = base64_decode(params)
hex_decoded_params = hexcode(decoded_params)
print("1, decoded_params: {decoded_params!r}, hex_decoded_params: {hex_decoded_params}".format(**locals()))
decoded_params = ntob(decoded_params)
hex_decoded_params = hexcode(decoded_params)
print("2, decoded_params: {decoded_params!r}, hex_decoded_params: {hex_decoded_params}".format(**locals()))
last_err = None
for charset in (accept_charset, fallback_charset):
try:
decoded_params = tonative(decoded_params, charset)
hex_decoded_params = hexcode(decoded_params)
print("3, decoded_params: {decoded_params!r}, hex_decoded_params: {hex_decoded_params}".format(**locals()))
break
except ValueError as ve:
last_err = ve
else:
raise last_err
decoded_params = ntou(decoded_params)
hex_decoded_params = hexcode(decoded_params)
print("4, decoded_params: {decoded_params!r}, hex_decoded_params: {hex_decoded_params}".format(**locals()))
decoded_params = unicodedata.normalize('NFC', decoded_params)
hex_decoded_params = hexcode(decoded_params)
print("5, decoded_params: {decoded_params!r}, hex_decoded_params: {hex_decoded_params}".format(**locals()))
decoded_params = tonative(decoded_params)
hex_decoded_params = hexcode(decoded_params)
print("6, decoded_params: {decoded_params!r}, hex_decoded_params: {hex_decoded_params}".format(**locals()))
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"%s' % (realm, charset_declaration)
)
raise cherrypy.HTTPError(
401, 'You are not authorized to access that resource')
# C:\Users\jarop\PycharmProjects\cherrypy\venv\Scripts\python.exe C:/Users/jarop/PycharmProjects/cherrypy/Test_code.py
# [05/Jan/2018:09:31:49] ENGINE Bus STARTING
# [05/Jan/2018:09:31:49] ENGINE Serving on http://0.0.0.0:8080
# [05/Jan/2018:09:31:49] ENGINE Bus STARTED
#
# --- curl 7.56.1 (i686-pc-cygwin) libcurl/7.56.1 OpenSSL/1.0.2m zlib/1.2.11 libidn2/2.0.4 libpsl/0.18.0 (+libidn2/2.0.2) libssh2/1.7.0 nghttp2/1.23.1
# --- Release-Date: 2017-10-23 on Windows 10
# --- from cygwin-shell $ curl -u 'curl:€öäü' -i -X GET http://127.0.0.1:8080/
#
# 1, decoded_params: 'curl:â\x82¬Ã¶Ã¤Ã¼', hex_decoded_params: 63 75 72 6c 3a e2 82 ac c3 b6 c3 a4 c3 bc
# 2, decoded_params: b'curl:\xe2\x82\xac\xc3\xb6\xc3\xa4\xc3\xbc', hex_decoded_params: 63 75 72 6c 3a e2 82 ac c3 b6 c3 a4 c3 bc
# 3, decoded_params: 'curl:€öäü', hex_decoded_params: 63 75 72 6c 3a 20ac f6 e4 fc
# 4, decoded_params: 'curl:€öäü', hex_decoded_params: 63 75 72 6c 3a 20ac f6 e4 fc
# 5, decoded_params: 'curl:€öäü', hex_decoded_params: 63 75 72 6c 3a 20ac f6 e4 fc
# 6, decoded_params: 'curl:€öäü', hex_decoded_params: 63 75 72 6c 3a 20ac f6 e4 fc
# realm: 'MY_REALM', username: 'curl'-'63 75 72 6c', password: '€öäü'-'20ac f6 e4 fc'
# ...
# --- Conlusion: curl is sending a UTF-8 encoded String. Those are secessfully decoded with step 3
#
# --- Firefox 57.0.3 (32-Bit) on Windows 10
# 1, decoded_params: 'firefox:¬öäü', hex_decoded_params: 66 69 72 65 66 6f 78 3a ac f6 e4 fc
# 2, decoded_params: b'firefox:\xac\xf6\xe4\xfc', hex_decoded_params: 66 69 72 65 66 6f 78 3a ac f6 e4 fc
# 3, decoded_params: 'firefox:¬öäü', hex_decoded_params: 66 69 72 65 66 6f 78 3a ac f6 e4 fc
# 4, decoded_params: 'firefox:¬öäü', hex_decoded_params: 66 69 72 65 66 6f 78 3a ac f6 e4 fc
# 5, decoded_params: 'firefox:¬öäü', hex_decoded_params: 66 69 72 65 66 6f 78 3a ac f6 e4 fc
# 6, decoded_params: 'firefox:¬öäü', hex_decoded_params: 66 69 72 65 66 6f 78 3a ac f6 e4 fc
# realm: 'MY_REALM', username: 'firefox'-'66 69 72 65 66 6f 78', password: '¬öäü'-'ac f6 e4 fc'
# ...
# --- Conlusion: Firefox is probably sending a "ISO 8859-1" encoded String. The € (Euro) sign
# isn't part of that charset and Firefox decided to encode it as AC which is a ¬ (Not) sign in
# 8859-1, windows-1252, latin-1, cp850 and probably some more.
#
# Appart from the €-Sign, the rest is succesfully decoded with step 3
#
# --- Google Chrome 63.0.3239.108 (64-Bit) on Windows 10
# 1, decoded_params: 'chrome:â\x82¬Ã¶Ã¤Ã¼', hex_decoded_params: 63 68 72 6f 6d 65 3a e2 82 ac c3
# b6 c3 a4 c3 bc
# 2, decoded_params: b'chrome:\xe2\x82\xac\xc3\xb6\xc3\xa4\xc3\xbc', hex_decoded_params: 63 68 72 6f 6d 65 3a e2 82 ac c3 b6 c3 a4 c3 bc
# 3, decoded_params: 'chrome:€öäü', hex_decoded_params: 63 68 72 6f 6d 65 3a 20ac f6 e4 fc
# 4, decoded_params: 'chrome:€öäü', hex_decoded_params: 63 68 72 6f 6d 65 3a 20ac f6 e4 fc
# 5, decoded_params: 'chrome:€öäü', hex_decoded_params: 63 68 72 6f 6d 65 3a 20ac f6 e4 fc
# 6, decoded_params: 'chrome:€öäü', hex_decoded_params: 63 68 72 6f 6d 65 3a 20ac f6 e4 fc
# realm: 'MY_REALM', username: 'chrome'-'63 68 72 6f 6d 65', password: '€öäü'-'20ac f6 e4 fc'
# ...
# --- Conclusion: Same as with curl -> utf-8 decoding sucessfull after step 3
#
# --- Microsoft Edge 40.15063.674.0 on Windows 10
# 1, decoded_params: 'edge:\x80öäü', hex_decoded_params: 65 64 67 65 3a 80 f6 e4 fc
# 2, decoded_params: b'edge:\x80\xf6\xe4\xfc', hex_decoded_params: 65 64 67 65 3a 80 f6 e4 fc
# 3, decoded_params: 'edge:\x80öäü', hex_decoded_params: 65 64 67 65 3a 80 f6 e4 fc
# 4, decoded_params: 'edge:\x80öäü', hex_decoded_params: 65 64 67 65 3a 80 f6 e4 fc
# 5, decoded_params: 'edge:\x80öäü', hex_decoded_params: 65 64 67 65 3a 80 f6 e4 fc
# 6, decoded_params: 'edge:\x80öäü', hex_decoded_params: 65 64 67 65 3a 80 f6 e4 fc
# realm: 'MY_REALM', username: 'edge'-'65 64 67 65', password: '\x80öäü'-'80 f6 e4 fc'
# ...
# --- Conclusion: Same as with Firefox-> Some sort of of ISO 8859-1 send have problems to
# encode € sign. Appart of that successfull decoed auth string after step 3
#
# --- Microsoft Internet Explorer 11.786.15063.0 on Windows 10
# 1, decoded_params: 'IE-11:\x80öäü', hex_decoded_params: 49 45 2d 31 31 3a 80 f6 e4 fc
# 2, decoded_params: b'IE-11:\x80\xf6\xe4\xfc', hex_decoded_params: 49 45 2d 31 31 3a 80 f6 e4 fc
# 3, decoded_params: 'IE-11:\x80öäü', hex_decoded_params: 49 45 2d 31 31 3a 80 f6 e4 fc
# 4, decoded_params: 'IE-11:\x80öäü', hex_decoded_params: 49 45 2d 31 31 3a 80 f6 e4 fc
# 5, decoded_params: 'IE-11:\x80öäü', hex_decoded_params: 49 45 2d 31 31 3a 80 f6 e4 fc
# 6, decoded_params: 'IE-11:\x80öäü', hex_decoded_params: 49 45 2d 31 31 3a 80 f6 e4 fc
# realm: 'MY_REALM', username: 'IE-11'-'49 45 2d 31 31', password: '\x80öäü'-'80 f6 e4 fc'
# ...
# --- Conclusion: Same as with Firefox-> Some sort of of ISO 8859-1 send have problems to
# encode € sign. Appart of that successfull decoed auth string after step 3
#
# Judgeing from these results everthing works as expected. Steps 4, 5 and 6 can safely be removed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment