| 1 |
import re |
| 2 |
from typing import Union, Tuple, Any |
| 3 |
|
| 4 |
from .errors import InvalidDN |
| 5 |
|
| 6 |
|
| 7 |
class LDAPDN: |
| 8 |
""" |
| 9 |
A class for handling valid LDAP distinguished name. |
| 10 |
|
| 11 |
:param str strdn: a string representation of LDAP distinguished name. |
| 12 |
""" |
| 13 |
|
| 14 |
__slots__ = ("__strdn",) |
| 15 |
|
| 16 |
_attrtype = r"[A-Za-z ][\w-]*|\d+(?:\.\d+)*" |
| 17 |
_attrvalue = ( |
| 18 |
r'#(?:[\dA-Fa-f]{2})+|(?:[^,=\+<>#;\\"]|\\[,=\+<>#;\\" ]' |
| 19 |
r'|\\[\dA-Fa-f]{2})*|"(?:[^\\"]|\\[,=\+<>#;\\"]|\\[\dA-Fa-f]{2})*"' |
| 20 |
) |
| 21 |
_namecomp = r"({typ})=({val})(?:\+({typ})=({val}))*".format( |
| 22 |
typ=_attrtype, val=_attrvalue |
| 23 |
) |
| 24 |
_dnregex = re.compile( |
| 25 |
r"({comp})(?:,({comp}))*\Z".format(comp=_namecomp), re.IGNORECASE |
| 26 |
) |
| 27 |
|
| 28 |
def __init__(self, strdn: str) -> None: |
| 29 |
if strdn != "" and not self._dnregex.match(strdn): |
| 30 |
raise InvalidDN(strdn) |
| 31 |
self.__strdn = self.__sanitize(strdn, True) |
| 32 |
|
| 33 |
def __str_rdn_to_tuple(self, str_rdn: str) -> Tuple[Tuple[str, str], ...]: |
| 34 |
""" |
| 35 |
Generate attribute type and value tuple from relative |
| 36 |
distinguished name. |
| 37 |
""" |
| 38 |
rdn = [] |
| 39 |
|
| 40 |
type_value_list = re.split(r"(?<!\\)[+]", str_rdn) |
| 41 |
for attr in type_value_list: |
| 42 |
|
| 43 |
atype, avalue = re.split(r"(?<!\\)=", attr) |
| 44 |
rdn.append((atype.strip(), self.__sanitize(avalue, True))) |
| 45 |
return tuple(rdn) |
| 46 |
|
| 47 |
@staticmethod |
| 48 |
def __sanitize(strdn: str, reverse: bool = False) -> str: |
| 49 |
"""Sanitizing special characters.""" |
| 50 |
char_list = [ |
| 51 |
(r"\\", "\\5C"), |
| 52 |
(r"\,", "\\2C"), |
| 53 |
(r"\+", "\\2B"), |
| 54 |
(r"\"", "\\22"), |
| 55 |
(r"\<", "\\3C"), |
| 56 |
(r"\>", "\\3E"), |
| 57 |
(r"\;", "\\3B"), |
| 58 |
(r"\=", "\\3D"), |
| 59 |
(r"\ ", "\\20"), |
| 60 |
] |
| 61 |
if strdn: |
| 62 |
for pair in char_list: |
| 63 |
if reverse: |
| 64 |
strdn = strdn.replace(pair[1], pair[0]) |
| 65 |
else: |
| 66 |
strdn = strdn.replace(pair[0], pair[1]) |
| 67 |
return strdn |
| 68 |
|
| 69 |
def __getitem__(self, idx: Union[int, slice]) -> str: |
| 70 |
""" |
| 71 |
Return the string format of the relative distinguished names |
| 72 |
in the LDAPDN. |
| 73 |
|
| 74 |
:param int idx: the indices of the RDNs. |
| 75 |
:return: the string format of the RDNs. |
| 76 |
:rtype: str |
| 77 |
""" |
| 78 |
rdns = re.split(r"(?<!\\),", self.__strdn) |
| 79 |
if isinstance(idx, int): |
| 80 |
if idx >= len(rdns): |
| 81 |
raise IndexError("Index is out of range.") |
| 82 |
|
| 83 |
idx = slice(idx, idx + 1) |
| 84 |
elif not isinstance(idx, slice): |
| 85 |
raise TypeError("Indices must be integers or slices.") |
| 86 |
return ",".join(rdns[idx]) |
| 87 |
|
| 88 |
def __setitem__(self, idx: Union[int, slice], value: str) -> None: |
| 89 |
""" |
| 90 |
Set the string format of the relative distinguished names |
| 91 |
in the LDAPDN. |
| 92 |
|
| 93 |
:param int idx: the indices of the RDNs. |
| 94 |
:param str value: the new RDNs. |
| 95 |
""" |
| 96 |
if not isinstance(value, str): |
| 97 |
raise ValueError("New value must be string.") |
| 98 |
if isinstance(idx, int): |
| 99 |
idx = slice(idx, idx + 1) |
| 100 |
elif not isinstance(idx, slice): |
| 101 |
raise TypeError("Indices must be integers or slices.") |
| 102 |
if not self._dnregex.match(value): |
| 103 |
raise InvalidDN(value) |
| 104 |
rdns = re.split(r"(?<!\\),", self.__strdn) |
| 105 |
rdns[idx] = re.split(r"(?<!\\),", value) |
| 106 |
self.__strdn = ",".join(rdns) |
| 107 |
|
| 108 |
def __eq__(self, other: object) -> bool: |
| 109 |
""" |
| 110 |
Check equality of two LDAPDNs by their string formats or |
| 111 |
their sanitized string formats. |
| 112 |
""" |
| 113 |
return ( |
| 114 |
str(self).lower() == str(other).lower() |
| 115 |
or self.__sanitize(str(self)).lower() == self.__sanitize(str(other)).lower() |
| 116 |
) |
| 117 |
|
| 118 |
def __str__(self) -> str: |
| 119 |
"""Return the full string format of the distinguished name.""" |
| 120 |
return self.__strdn |
| 121 |
|
| 122 |
def __len__(self) -> int: |
| 123 |
"""Return the number of RDNs of the distinguished name.""" |
| 124 |
return len(re.split(r"(?<!\\),", self.__strdn)) |
| 125 |
|
| 126 |
def __repr__(self) -> str: |
| 127 |
"""The representation of LDAPDN class.""" |
| 128 |
return "<LDAPDN %s>" % str(self) |
| 129 |
|
| 130 |
@property |
| 131 |
def rdns(self) -> Tuple[Tuple[Tuple[str, str], ...], ...]: |
| 132 |
"""The tuple of relative distinguished name.""" |
| 133 |
return tuple( |
| 134 |
self.__str_rdn_to_tuple(rdn) |
| 135 |
for rdn in re.split(r"(?<!\\),", self.__sanitize(self.__strdn)) |
| 136 |
) |
| 137 |
|
| 138 |
@rdns.setter |
| 139 |
def rdns(self, value: Any = None) -> None: |
| 140 |
"""The tuple of relative distinguished names.""" |
| 141 |
raise ValueError("RDNs attribute cannot be set.") |