From 067db4510bd022434089c89181fa5ec71fb716b5 Mon Sep 17 00:00:00 2001 From: Pierre Tardy Date: Tue, 5 Jan 2021 16:52:25 +0100 Subject: [PATCH] bpo-42833: make digest algorithms case insensitive as per https://tools.ietf.org/html/rfc3230#section-4.1.1 digest names shall be case insensitive --- Lib/test/test_urllib2.py | 9 +++++++++ Lib/urllib/request.py | 7 +++++-- .../Library/2021-01-05-16-58-10.bpo-42833.EIcmpu.rst | 1 + 3 files changed, 15 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2021-01-05-16-58-10.bpo-42833.EIcmpu.rst diff --git a/Lib/test/test_urllib2.py b/Lib/test/test_urllib2.py index 9db23e6ce04bd5..a702c1ac6581f8 100644 --- a/Lib/test/test_urllib2.py +++ b/Lib/test/test_urllib2.py @@ -1,5 +1,6 @@ import unittest from test import support +from test.support import hashlib_helper from test.support import os_helper from test.support import socket_helper from test.support import warnings_helper @@ -1876,6 +1877,14 @@ def test_unsupported_algorithm(self): "Unsupported digest authentication algorithm 'invalid'" ) + @hashlib_helper.requires_hashdigest('sha1') + def test_lowercase_algorithm(self): + handler = AbstractDigestAuthHandler() + # make sure both algorithms are equivalent + self.assertEqual( + handler.get_algorithm_impls('sha')[0]("TEST"), + handler.get_algorithm_impls('SHA')[0]("TEST")) + class RequestTests(unittest.TestCase): class PutRequest(Request): diff --git a/Lib/urllib/request.py b/Lib/urllib/request.py index e5febe61f556d3..105a86f0f27590 100644 --- a/Lib/urllib/request.py +++ b/Lib/urllib/request.py @@ -1206,10 +1206,13 @@ def get_authorization(self, req, chal): return base def get_algorithm_impls(self, algorithm): + # as per https://tools.ietf.org/html/rfc3230#section-4.1.1 + # algorithm is case insensitive + upper_algorithm = algorithm.upper() # lambdas assume digest modules are imported at the top level - if algorithm == 'MD5': + if upper_algorithm == 'MD5': H = lambda x: hashlib.md5(x.encode("ascii")).hexdigest() - elif algorithm == 'SHA': + elif upper_algorithm == 'SHA': H = lambda x: hashlib.sha1(x.encode("ascii")).hexdigest() # XXX MD5-sess else: diff --git a/Misc/NEWS.d/next/Library/2021-01-05-16-58-10.bpo-42833.EIcmpu.rst b/Misc/NEWS.d/next/Library/2021-01-05-16-58-10.bpo-42833.EIcmpu.rst new file mode 100644 index 00000000000000..b364172dd822e5 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2021-01-05-16-58-10.bpo-42833.EIcmpu.rst @@ -0,0 +1 @@ +urllib2 digest algorithm selection is now case insensitive