From cad1bbe56e37d6b60f9e802bbb16f515a9d48e53 Mon Sep 17 00:00:00 2001 From: Anuj Borah Date: Dec 03 2019 09:37:03 +0000 Subject: Issue: 50443 - Create a module in lib389 to Convert a byte sequence to a properly escaped for LDAP Create a module in lib389 to Convert a byte sequence to a properly escaped for LDAP Fixes: https://pagure.io/389-ds-base/issue/50443 Author: aborah Reviewed by: Matus Honek, Simon Pichugin --- diff --git a/src/lib389/lib389/tests/utils_test.py b/src/lib389/lib389/tests/utils_test.py index a696eb5..8bfe4ab 100644 --- a/src/lib389/lib389/tests/utils_test.py +++ b/src/lib389/lib389/tests/utils_test.py @@ -174,6 +174,19 @@ def test_ds_is_newer_versions(ds_ver, cmp_ver): assert ds_is_related('newer', ds_ver, cmp_ver) +@pytest.mark.parametrize('input, result', [ + (b'', ''), + (b'\x00', '\\00'), + (b'\x01\x00', '\\01\\00'), + (b'01', '\\30\\31'), + (b'101', '\\31\\30\\31'), + (b'101x1', '\\31\\30\\31\\78\\31'), + (b'0\x82\x05s0\x82\x03[\xa0\x03\x02\x01\x02', '\\30\\82\\05\\73\\30\\82\\03\\5b\\a0\\03\\02\\01\\02'), +]) +def test_search_filter_escape_bytes(input, result): + assert search_filter_escape_bytes(input) == result + + if __name__ == "__main__": CURRENT_FILE = os.path.realpath(__file__) pytest.main("-s -v %s" % CURRENT_FILE) diff --git a/src/lib389/lib389/utils.py b/src/lib389/lib389/utils.py index b9eacfd..459a490 100644 --- a/src/lib389/lib389/utils.py +++ b/src/lib389/lib389/utils.py @@ -1315,3 +1315,15 @@ def convert_bytes(bytes): pow = math.pow(1024, i) siz = round(bytes / pow, 2) return "{} {}".format(siz, size_name[i]) + + +def search_filter_escape_bytes(bytes_value): + """ Convert a byte sequence to a properly escaped for LDAP (format BACKSLASH HEX HEX) string""" + # copied from https://github.com/cannatag/ldap3/blob/master/ldap3/utils/conv.py + if str is not bytes: + if isinstance(bytes_value, str): + bytes_value = bytearray(bytes_value, encoding='utf-8') + return ''.join([('\\%02x' % int(b)) for b in bytes_value]) + else: + raise RuntimeError('Running with Python 2 is unsupported') +