| 1 |
# Authors: |
| 2 |
# John Dennis <[email protected]> |
| 3 |
# |
| 4 |
# Copyright (C) 2011 Red Hat |
| 5 |
# see file 'COPYING' for use and warranty information |
| 6 |
# |
| 7 |
# This program is free software; you can redistribute it and/or modify |
| 8 |
# it under the terms of the GNU General Public License as published by |
| 9 |
# the Free Software Foundation, either version 3 of the License, or |
| 10 |
# (at your option) any later version. |
| 11 |
# |
| 12 |
# This program is distributed in the hope that it will be useful, |
| 13 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 15 |
# GNU General Public License for more details. |
| 16 |
# |
| 17 |
# You should have received a copy of the GNU General Public License |
| 18 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 19 |
|
| 20 |
r''' |
| 21 |
|
| 22 |
Goal |
| 23 |
---- |
| 24 |
|
| 25 |
To allow a Python programmer the ability to operate on DN's |
| 26 |
(Distinguished Names) in a simple intuitive manner supporting all the |
| 27 |
Pythonic mechanisms for manipulating objects such that the simple |
| 28 |
majority case remains simple with simple code, yet the corner cases |
| 29 |
are fully supported. With the result both simple and complex cases are |
| 30 |
100% correct. |
| 31 |
|
| 32 |
This is achieved with a fair of amount of syntax sugar which is best |
| 33 |
described as "Do What I Mean" (i.e. DWIM). The class implementations |
| 34 |
take simple expressions and internally convert them to their more |
| 35 |
complex full definitions hiding much of the complexity from the |
| 36 |
programmer. |
| 37 |
|
| 38 |
Anatomy of a DN |
| 39 |
--------------- |
| 40 |
|
| 41 |
Some definitions: |
| 42 |
|
| 43 |
AVA |
| 44 |
An AVA is an Attribute Value Assertion. In more simple terms it's |
| 45 |
an attribute value pair typically expressed as attr=value |
| 46 |
(e.g. cn=Bob). Both the attr and value in an AVA when expressed in |
| 47 |
a string representation are subject to encoding rules. |
| 48 |
|
| 49 |
RDN |
| 50 |
A RDN is a Relative Distinguished Name. A RDN is a non-empty set of |
| 51 |
AVA's. In the common case a RDN is single valued consisting of 1 |
| 52 |
AVA (e.g. cn=Bob). But a RDN may be multi-valued consisting of |
| 53 |
more than one AVA. Because the RDN is a set of AVA's the AVA's are |
| 54 |
unordered when they appear in a multi-valued RDN. In the string |
| 55 |
representation of a RDN AVA's are separated by the plus sign (+). |
| 56 |
|
| 57 |
DN |
| 58 |
A DN is a ordered sequence of 1 or more RDN's. In the string |
| 59 |
representation of a DN each RDN is separated by a comma (,) |
| 60 |
|
| 61 |
Thus a DN is: |
| 62 |
|
| 63 |
Sequence of set of <encoded attr, encoded value> pairs |
| 64 |
|
| 65 |
The following are valid DN's |
| 66 |
|
| 67 |
# 1 RDN with 1 AVA (e.g. cn=Bob) |
| 68 |
RDN(AVA) |
| 69 |
|
| 70 |
# 2 RDN's each with 1 AVA (e.g. cn=Bob,dc=redhat.com) |
| 71 |
RDN(AVA),RDN(AVA) |
| 72 |
|
| 73 |
# 2 RDN's the first RDN is multi-valued with 2 AVA's |
| 74 |
# the second RDN is singled valued with 1 AVA |
| 75 |
# (e.g. cn=Bob+ou=people,dc=redhat.com |
| 76 |
RDN({AVA,AVA}),RDN(AVA) |
| 77 |
|
| 78 |
Common programming mistakes |
| 79 |
--------------------------- |
| 80 |
|
| 81 |
DN's present a pernicious problem for programmers. They appear to have |
| 82 |
a very simple string format in the majority case, a sequence of |
| 83 |
attr=value pairs separated by commas. For example: |
| 84 |
|
| 85 |
dn='cn=Bob,ou=people,dc=redhat,dc=com' |
| 86 |
|
| 87 |
As such there is a tendency to believe you can form DN's by simple |
| 88 |
string manipulations such as: |
| 89 |
|
| 90 |
dn='%s=%s' % ('cn','Bob') + ',ou=people,dc=redhat,dc=com' |
| 91 |
|
| 92 |
Or to extract a attr & value by searching the string, for example: |
| 93 |
|
| 94 |
attr=dn[0 : dn.find('=')] |
| 95 |
value=dn[dn.find('=')+1 : dn.find(',')] |
| 96 |
|
| 97 |
Or compare a value returned by an LDAP query to a known value: |
| 98 |
|
| 99 |
if value == 'Bob' |
| 100 |
|
| 101 |
All of these simple coding assumptions are WRONG and will FAIL when a |
| 102 |
DN is not one of the simple DN's (simple DN's are probably the 95% of |
| 103 |
all DN's). This is what makes DN handling pernicious. What works in |
| 104 |
95% of the cases and is simple, fails for the 5% of DN's which are not |
| 105 |
simple. |
| 106 |
|
| 107 |
Examples of where the simple assumptions fail are: |
| 108 |
|
| 109 |
* A RDN may be multi-valued |
| 110 |
|
| 111 |
* A multi-valued RDN has no ordering on it's components |
| 112 |
|
| 113 |
* Attr's and values must be UTF-8 encoded |
| 114 |
|
| 115 |
* String representations of AVA's, RDN's and DN's must be completely UTF-8 |
| 116 |
|
| 117 |
* An attr or value may have reserved characters which must be escaped. |
| 118 |
|
| 119 |
* Whitespace needs special handling |
| 120 |
|
| 121 |
To complicate matters a bit more the RFC for the string representation |
| 122 |
of DN's (RFC 4514) permits a variety of different syntax's each of |
| 123 |
which can evaluate to exactly the same DN but have different string |
| 124 |
representations. For example, the attr "r,w" which contains a reserved |
| 125 |
character (the comma) can be encoded as a string in these different |
| 126 |
ways: |
| 127 |
|
| 128 |
'r\,w' # backslash escape |
| 129 |
'r\2cw' # hexadecimal ascii escape |
| 130 |
'#722C77' # binary encoded |
| 131 |
|
| 132 |
It should be clear a DN string may NOT be a simple string, rather a DN |
| 133 |
string is ENCODED. For simple strings the encoding of the DN is |
| 134 |
identical to the simple string value (this common case leads to |
| 135 |
erroneous assumptions and bugs because it does not account for |
| 136 |
encodings). |
| 137 |
|
| 138 |
The openldap library we use at the client level uses the backslash |
| 139 |
escape form. The LDAP server we use uses the hexadecimal ascii escape |
| 140 |
form. Thus 'r,w' appears as 'r\,w' when sent from the client to the |
| 141 |
LDAP server as part of a DN. But when it's returned as a DN from the |
| 142 |
server in an LDAP search it's returned as 'r\2cw'. Any attempt to |
| 143 |
compare 'r\,w' to 'r\2cw' for equality will fail despite the fact they |
| 144 |
are indeed equal once decoded. Such a test fails because you're |
| 145 |
comparing two different encodings of the same value. In MIME you |
| 146 |
wouldn't expect the base64 encoding of a string to be equal to the |
| 147 |
same string encoded as quoted-printable would you? |
| 148 |
|
| 149 |
When you are comparing attrs or values which are part of a DN and |
| 150 |
other string you MUST: |
| 151 |
|
| 152 |
* Know if either of the strings have been encoded and make sure you're |
| 153 |
comparing only decoded components component-wise. |
| 154 |
|
| 155 |
* Extract the component from the DN and decode it. You CANNOT decode |
| 156 |
the entire DN as a string and operate on it. Why? Consider a value |
| 157 |
with a comma embedded in it. For example: |
| 158 |
|
| 159 |
cn=r\2cw,cn=privilege |
| 160 |
|
| 161 |
Is a DN with 2 RDN components: cn=r,w followed by "cn=privilege" |
| 162 |
|
| 163 |
But if you decode the entire DN string as a whole you would get: |
| 164 |
|
| 165 |
cn=r,w,cn=privilege |
| 166 |
|
| 167 |
Which is a malformed DN with 3 RDN's, the 2nd RDN is invalid. |
| 168 |
|
| 169 |
* Determine if a RDN is multi-valued, if so you must account |
| 170 |
for the fact each AVA component in the multi-valued RDN can appear |
| 171 |
in any order and still be equivalent. For example the following two |
| 172 |
RDN's are equal: |
| 173 |
|
| 174 |
cn=Bob+ou=people |
| 175 |
ou=people+cn=Bob |
| 176 |
|
| 177 |
In addition each AVA (cn=Bob & ou=people) needs to be |
| 178 |
INDEPENDENTLY decoded prior to comparing the unordered set of AVA's |
| 179 |
in the multi-valued RDN. |
| 180 |
|
| 181 |
If you are trying to form a new DN or RDN from a raw string you cannot |
| 182 |
simply do string concatenation or string formatting unless you ESCAPE |
| 183 |
the components independently prior to concatenation, for example: |
| 184 |
|
| 185 |
base = 'dc=redhat,dc=com' |
| 186 |
value = 'r,w' |
| 187 |
dn = 'cn=%s,%s' % (value, base) |
| 188 |
|
| 189 |
Will result in the malformed DN 'cn=r,w,dc=redhat,dc=com' |
| 190 |
|
| 191 |
Syntax Sugar |
| 192 |
------------ |
| 193 |
|
| 194 |
The majority of DN's have a simple string form: |
| 195 |
|
| 196 |
attr=value,attr=value |
| 197 |
|
| 198 |
We want the programmer to be able to create DN's, compare them, and |
| 199 |
operate on their components as simply and concisely as possible so |
| 200 |
the classes are implemented to provide a lot of syntax sugar. |
| 201 |
|
| 202 |
The classes automatically handle UTF-8 <-> Unicode conversions. Every |
| 203 |
attr and value which is returned from a class will be Unicode. Every |
| 204 |
attr and value assigned into an object will be promoted to |
| 205 |
Unicode. All string representations in RFC 4514 format will be UTF-8 |
| 206 |
and properly escaped. Thus at the "user" or "API" level every string |
| 207 |
is Unicode with the single exception that the str() method returns RFC |
| 208 |
compliant escaped UTF-8. |
| 209 |
|
| 210 |
RDN's are assumed to be single-valued. If you need a multi-valued RDN |
| 211 |
(an exception) you must explicitly create a multi-valued RDN. |
| 212 |
|
| 213 |
Thus DN's are assumed to be a sequence of attr, value pairs, which is |
| 214 |
equivalent to a sequence of RDN's. The attr and value in the pair MUST |
| 215 |
be strings. |
| 216 |
|
| 217 |
The DN and RDN constructors take a sequence, the constructor parses |
| 218 |
the sequence to find items it knows about. |
| 219 |
|
| 220 |
The DN constructor will accept in it's sequence: |
| 221 |
* tuple of 2 strings, converting it to an RDN |
| 222 |
* list of 2 strings, converting it to an RDN |
| 223 |
* a RDN object |
| 224 |
* a DN syntax string (e.g. 'cn=Bob,dc=redhat.com') |
| 225 |
|
| 226 |
Note DN syntax strings should be avoided if possible when passing to a |
| 227 |
constructor because they run afoul of the problems outlined above |
| 228 |
which the DN, RDN & AVA classes are meant to overcome. But sometimes a |
| 229 |
DN syntax string is all you have to work with. DN strings which come |
| 230 |
from a LDAP library or server will be properly formed and it's safe to |
| 231 |
use those. However DN strings provided via user input should be |
| 232 |
treated suspiciously as they may be improperly formed. You can test |
| 233 |
for this by passing the string to the DN constructor and see if it |
| 234 |
throws an exception. |
| 235 |
|
| 236 |
The sequence passed to the DN constructor takes each item in order, |
| 237 |
produces one or more RDN's from it and appends those RDN in order to |
| 238 |
its internal RDN sequence. |
| 239 |
|
| 240 |
For example: |
| 241 |
|
| 242 |
DN(('cn', 'Bob'), ('dc', 'redhat.com')) |
| 243 |
|
| 244 |
This is equivalent to the DN string: |
| 245 |
|
| 246 |
cn=Bob,dc=redhat.com |
| 247 |
|
| 248 |
And is exactly equal to: |
| 249 |
|
| 250 |
DN(RDN(AVA('cn','Bob')),RDN(AVA('dc','redhat.com'))) |
| 251 |
|
| 252 |
The following are alternative syntax's which are all exactly |
| 253 |
equivalent to the above example. |
| 254 |
|
| 255 |
DN(['cn', 'Bob'], ['dc', 'redhat.com']) |
| 256 |
DN(RDN('cn', 'Bob'), RDN('dc', 'redhat.com')) |
| 257 |
|
| 258 |
You can provide a properly escaped string representation. |
| 259 |
|
| 260 |
DN('cn=Bob,dc=redhat.com') |
| 261 |
|
| 262 |
You can mix and match any of the forms in the constructor parameter |
| 263 |
list. |
| 264 |
|
| 265 |
DN(('cn', 'Bob'), 'dc=redhat.com') |
| 266 |
DN(('cn', 'Bob'), RDN('dc', 'redhat.com')) |
| 267 |
|
| 268 |
AVA's have an attr and value property, thus if you have an AVA |
| 269 |
|
| 270 |
# Get the attr and value |
| 271 |
ava.attr -> u'cn' |
| 272 |
ava.value -> u'Bob' |
| 273 |
|
| 274 |
# Set the attr and value |
| 275 |
ava.attr = 'cn' |
| 276 |
ava.value = 'Bob' |
| 277 |
|
| 278 |
Since RDN's are assumed to be single valued, exactly the same |
| 279 |
behavior applies to an RDN. If the RDN is multi-valued then the attr |
| 280 |
property returns the attr of the first AVA, likewise for the value. |
| 281 |
|
| 282 |
# Get the attr and value |
| 283 |
rdn.attr -> u'cn' |
| 284 |
rdn.value -> u'Bob' |
| 285 |
|
| 286 |
# Set the attr and value |
| 287 |
rdn.attr = 'cn' |
| 288 |
rdn.value = 'Bob' |
| 289 |
|
| 290 |
Also RDN's can be indexed by name or position (see the RDN class doc |
| 291 |
for details). |
| 292 |
|
| 293 |
rdn['cn'] -> u'Bob' |
| 294 |
rdn[0] -> AVA('cn', 'Bob') |
| 295 |
|
| 296 |
A DN is a sequence of RDN's, as such any of Python's container |
| 297 |
operators can be applied to a DN in a intuitive way. |
| 298 |
|
| 299 |
# How many RDN's in a DN? |
| 300 |
len(dn) |
| 301 |
|
| 302 |
# WARNING, this a count of RDN's not how characters there are in the |
| 303 |
# string representation the dn, instead that would be: |
| 304 |
len(str(dn)) |
| 305 |
|
| 306 |
# Iterate over each RDN in a DN |
| 307 |
for rdn in dn: |
| 308 |
|
| 309 |
# Get the first RDN in a DN |
| 310 |
dn[0] -> RDN('cn', 'Bob') |
| 311 |
|
| 312 |
# Get the value of the first RDN in a DN |
| 313 |
dn[0].value -> u'Bob' |
| 314 |
|
| 315 |
# Get the value of the first RDN by indexing by attr name |
| 316 |
dn['cn'] -> u'Bob' |
| 317 |
|
| 318 |
# WARNING, when a string is used as an index key the FIRST RDN's value |
| 319 |
# in the sequence whose attr matches the key is returned. Thus if you |
| 320 |
# have a DN like this "cn=foo,cn=bar" then dn['cn'] will always return |
| 321 |
# 'foo' even though there is another attr with the name 'cn'. This is |
| 322 |
# almost always what the programmer wants. See the class doc for how |
| 323 |
# you can override this default behavior and get a list of every value |
| 324 |
# whose attr matches the key. |
| 325 |
|
| 326 |
# Set the first RDN in the DN (all are equivalent) |
| 327 |
dn[0] = ('cn', 'Bob') |
| 328 |
dn[0] = ['cn', 'Bob'] |
| 329 |
dn[0] = RDN('cn', 'Bob') |
| 330 |
|
| 331 |
dn[0].attr = 'cn' |
| 332 |
dn[0].value = 'Bob' |
| 333 |
|
| 334 |
# Get the first two RDN's using slices |
| 335 |
dn[0:2] |
| 336 |
|
| 337 |
# Get the last two RDN's using slices |
| 338 |
dn[-2:] |
| 339 |
|
| 340 |
# Get a list of all RDN's using slices |
| 341 |
dn[:] |
| 342 |
|
| 343 |
# Set the 2nd and 3rd RDN using slices (all are equivalent) |
| 344 |
dn[1:3] = ('cn', 'Bob), ('dc', 'redhat.com') |
| 345 |
dn[1:3] = RDN('cn', 'Bob), RDN('dc', 'redhat.com') |
| 346 |
|
| 347 |
String representations and escapes: |
| 348 |
|
| 349 |
# To get an RFC compliant string representation of a DN, RDN or AVA |
| 350 |
# simply call str() on it or evaluate it in a string context. |
| 351 |
str(dn) -> 'cn=Bob,dc=redhat.com' |
| 352 |
|
| 353 |
# When working with attr's and values you do not have to worry about |
| 354 |
# escapes, simply use the raw unescaped string in a natural fashion. |
| 355 |
|
| 356 |
rdn = RDN('cn', 'r,w') |
| 357 |
|
| 358 |
# Thus: |
| 359 |
rdn.value == 'r,w' -> True |
| 360 |
|
| 361 |
# But: |
| 362 |
str(rdn) == 'cn=r,w' -> False |
| 363 |
# Because: |
| 364 |
str(rdn) -> 'cn=r\2cw' or 'cn='r\,w' # depending on the underlying LDAP library |
| 365 |
|
| 366 |
Equality and Comparing: |
| 367 |
|
| 368 |
# All DN's, RDN's and AVA's support equality testing in an intuitive |
| 369 |
# manner. |
| 370 |
dn1 = DN(('cn', 'Bob')) |
| 371 |
dn2 = DN(RDN('cn', 'Bob')) |
| 372 |
dn1 == dn2 -> True |
| 373 |
dn1[0] == dn2[0] -> True |
| 374 |
dn1[0].value = 'Bobby' |
| 375 |
dn1 == dn2 -> False |
| 376 |
|
| 377 |
DN objects implement startswith(), endswith() and the "in" membership |
| 378 |
operator. You may pass a DN or RDN object to these. Examples: |
| 379 |
|
| 380 |
if dn.endswith(base_dn): |
| 381 |
if dn.startswith(rdn1): |
| 382 |
if container_dn in dn: |
| 383 |
|
| 384 |
# See the class doc for how DN's, RDN's and AVA's compare |
| 385 |
# (e.g. cmp()). The general rule is for objects supporting multiple |
| 386 |
# values first their lengths are compared, then if the lengths match |
| 387 |
# the respective components of each are pair-wise compared until one |
| 388 |
# is discovered to be non-equal. The comparison is case insensitive. |
| 389 |
|
| 390 |
Concatenation, In-Place Addition, Insertion: |
| 391 |
|
| 392 |
# DN's and RDN's can be concatenated. |
| 393 |
# Return a new DN by appending the RDN's of dn2 to dn1 |
| 394 |
dn3 = dn1 + dn2 |
| 395 |
|
| 396 |
# Append a RDN to DN's RDN sequence (all are equivalent) |
| 397 |
dn += ('cn', 'Bob') |
| 398 |
dn += RDN('cn', 'Bob') |
| 399 |
|
| 400 |
# Append a DN to an existing DN |
| 401 |
dn1 += dn2 |
| 402 |
|
| 403 |
# Prepend a RDN to an existing DN |
| 404 |
dn1.insert(0, RDN('cn', 'Bob')) |
| 405 |
|
| 406 |
Finally see the unittest for a more complete set of ways you can |
| 407 |
manipulate these objects. |
| 408 |
|
| 409 |
Immutability |
| 410 |
------------ |
| 411 |
|
| 412 |
All the class types are immutable. |
| 413 |
As with other immutable types (such as str and int), you must not rely on |
| 414 |
the object identity operator ("is") for comparisons. |
| 415 |
|
| 416 |
It is possible to "copy" an object by passing an object of the same type |
| 417 |
to the constructor. The result may share underlying structure. |
| 418 |
|
| 419 |
''' |
| 420 |
from __future__ import print_function |
| 421 |
|
| 422 |
import sys |
| 423 |
import functools |
| 424 |
|
| 425 |
import cryptography.x509 |
| 426 |
import six |
| 427 |
|
| 428 |
try: |
| 429 |
from ldap import DECODING_ERROR |
| 430 |
except ImportError: |
| 431 |
from ipapython.dn_ctypes import str2dn, dn2str, DECODING_ERROR |
| 432 |
else: |
| 433 |
from ldap.dn import str2dn, dn2str |
| 434 |
|
| 435 |
|
| 436 |
if six.PY3: |
| 437 |
unicode = str |
| 438 |
|
| 439 |
__all__ = 'AVA', 'RDN', 'DN' |
| 440 |
|
| 441 |
def _adjust_indices(start, end, length): |
| 442 |
'helper to fixup start/end slice values' |
| 443 |
|
| 444 |
if end > length: |
| 445 |
end = length |
| 446 |
elif end < 0: |
| 447 |
end += length |
| 448 |
if end < 0: |
| 449 |
end = 0 |
| 450 |
|
| 451 |
if start < 0: |
| 452 |
start += length |
| 453 |
if start < 0: |
| 454 |
start = 0 |
| 455 |
|
| 456 |
return start, end |
| 457 |
|
| 458 |
|
| 459 |
def _normalize_ava_input(val): |
| 460 |
if six.PY3 and isinstance(val, bytes): |
| 461 |
raise TypeError('expected str, got bytes: %r' % val) |
| 462 |
elif not isinstance(val, str): |
| 463 |
val = val_encode(str(val)) |
| 464 |
elif six.PY2 and isinstance(val, unicode): |
| 465 |
val = val.encode('utf-8') |
| 466 |
return val |
| 467 |
|
| 468 |
|
| 469 |
def str2rdn(value): |
| 470 |
try: |
| 471 |
rdns = str2dn(value.encode('utf-8')) |
| 472 |
except DECODING_ERROR: |
| 473 |
raise ValueError("malformed AVA string = \"%s\"" % value) |
| 474 |
if len(rdns) != 1: |
| 475 |
raise ValueError("multiple RDN's specified by \"%s\"" % (value)) |
| 476 |
return rdns[0] |
| 477 |
|
| 478 |
|
| 479 |
def get_ava(*args): |
| 480 |
""" |
| 481 |
Get AVA from args in open ldap format(raw). Optimized for construction |
| 482 |
from openldap format. |
| 483 |
|
| 484 |
Allowed formats of argument list: |
| 485 |
1) three args - open ldap format (attr and value have to be utf-8 encoded): |
| 486 |
a) ['attr', 'value', 0] |
| 487 |
2) two args: |
| 488 |
a) ['attr', 'value'] |
| 489 |
3) one arg: |
| 490 |
a) [('attr', 'value')] |
| 491 |
b) [['attr', 'value']] |
| 492 |
c) [AVA(..)] |
| 493 |
d) ['attr=value'] |
| 494 |
""" |
| 495 |
ava = None |
| 496 |
l = len(args) |
| 497 |
if l == 3: # raw values - constructed FROM RDN |
| 498 |
ava = args |
| 499 |
elif l == 2: # user defined values |
| 500 |
ava = [_normalize_ava_input(args[0]), _normalize_ava_input(args[1]), 0] |
| 501 |
elif l == 1: # slow mode, tuple, string, |
| 502 |
arg = args[0] |
| 503 |
if isinstance(arg, AVA): |
| 504 |
ava = arg.to_openldap() |
| 505 |
elif isinstance(arg, (tuple, list)): |
| 506 |
if len(arg) != 2: |
| 507 |
raise ValueError("tuple or list must be 2-valued, not \"%s\"" % (arg)) |
| 508 |
ava = [_normalize_ava_input(arg[0]), _normalize_ava_input(arg[1]), 0] |
| 509 |
elif isinstance(arg, str): |
| 510 |
rdn = str2rdn(arg) |
| 511 |
if len(rdn) > 1: |
| 512 |
raise TypeError("multiple AVA's specified by \"%s\"" % (arg)) |
| 513 |
ava = list(rdn[0]) |
| 514 |
else: |
| 515 |
raise TypeError("with 1 argument, argument must be str, unicode, tuple or list, got %s instead" % |
| 516 |
arg.__class__.__name__) |
| 517 |
else: |
| 518 |
raise TypeError("invalid number of arguments. 1-3 allowed") |
| 519 |
return ava |
| 520 |
|
| 521 |
|
| 522 |
def sort_avas(rdn): |
| 523 |
if len(rdn) <= 1: |
| 524 |
return |
| 525 |
rdn.sort(key=ava_key) |
| 526 |
|
| 527 |
|
| 528 |
def ava_key(ava): |
| 529 |
return ava[0].lower(), ava[1].lower() |
| 530 |
|
| 531 |
|
| 532 |
def cmp_rdns(a, b): |
| 533 |
key_a = rdn_key(a) |
| 534 |
key_b = rdn_key(b) |
| 535 |
if key_a == key_b: |
| 536 |
return 0 |
| 537 |
elif key_a < key_b: |
| 538 |
return -1 |
| 539 |
else: |
| 540 |
return 1 |
| 541 |
|
| 542 |
|
| 543 |
def rdn_key(rdn): |
| 544 |
return (len(rdn),) + tuple(ava_key(k) for k in rdn) |
| 545 |
|
| 546 |
|
| 547 |
if six.PY2: |
| 548 |
# Python 2: Input/output is unicode; we store UTF-8 bytes |
| 549 |
def val_encode(s): |
| 550 |
return s.encode('utf-8') |
| 551 |
|
| 552 |
def val_decode(s): |
| 553 |
return s.decode('utf-8') |
| 554 |
else: |
| 555 |
# Python 3: Everything is unicode (str) |
| 556 |
def val_encode(s): |
| 557 |
if isinstance(s, bytes): |
| 558 |
raise TypeError('expected str, got bytes: %s' % s) |
| 559 |
return s |
| 560 |
|
| 561 |
def val_decode(s): |
| 562 |
return s |
| 563 |
|
| 564 |
|
| 565 |
@functools.total_ordering |
| 566 |
class AVA: |
| 567 |
''' |
| 568 |
AVA(arg0, ...) |
| 569 |
|
| 570 |
An AVA is an LDAP Attribute Value Assertion. It is convenient to think of |
| 571 |
AVA's as a <attr,value> pair. AVA's are members of RDN's (Relative |
| 572 |
Distinguished Name). |
| 573 |
|
| 574 |
The AVA constructor is passed a sequence of args and a set of |
| 575 |
keyword parameters used for configuration. |
| 576 |
|
| 577 |
The arg sequence may be: |
| 578 |
|
| 579 |
1) With 2 arguments, the first argument will be the attr, the 2nd |
| 580 |
the value. Each argument must be scalar convertable to unicode. |
| 581 |
|
| 582 |
2) With a sigle list or tuple argument containing exactly 2 items. |
| 583 |
Each item must be scalar convertable to unicode. |
| 584 |
|
| 585 |
3) With a single string (or unicode) argument, in this case the string will |
| 586 |
be interpretted using the DN syntax described in RFC 4514 to yield a AVA |
| 587 |
<attr,value> pair. The parsing recognizes the DN syntax escaping rules. |
| 588 |
|
| 589 |
For example: |
| 590 |
|
| 591 |
ava = AVA('cn', 'Bob') # case 1: two strings |
| 592 |
ava = AVA(('cn', 'Bob')) # case 2: 2-valued tuple |
| 593 |
ava = AVA(['cn', 'Bob']) # case 2: 2-valued list |
| 594 |
ava = AVA('cn=Bob') # case 3: DN syntax |
| 595 |
|
| 596 |
AVA object have two properties for accessing their data: |
| 597 |
|
| 598 |
attr: the attribute name, cn in our exmaple |
| 599 |
value: the attribute's value, Bob in our example |
| 600 |
|
| 601 |
When attr and value are returned they will always be unicode. When |
| 602 |
attr or value are set they will be promoted to unicode. |
| 603 |
|
| 604 |
AVA objects support indexing by name, e.g. |
| 605 |
|
| 606 |
ava['cn'] |
| 607 |
|
| 608 |
returns the value (Bob in our example). If the index does key does not match |
| 609 |
the attr then a KeyError will be raised. |
| 610 |
|
| 611 |
AVA objects support equality testing and comparsion (e.g. cmp()). When they |
| 612 |
are compared the attr is compared first, if the 2 attr's are equal then the |
| 613 |
values are compared. The comparison is case insensitive (because attr's map |
| 614 |
to numeric OID's and their values derive from from the 'name' atribute type |
| 615 |
(OID 2.5.4.41) whose EQUALITY MATCH RULE is caseIgnoreMatch. |
| 616 |
|
| 617 |
The str method of an AVA returns the string representation in RFC 4514 DN |
| 618 |
syntax with proper escaping. |
| 619 |
''' |
| 620 |
def __init__(self, *args): |
| 621 |
self._ava = get_ava(*args) |
| 622 |
|
| 623 |
def _get_attr(self): |
| 624 |
return val_decode(self._ava[0]) |
| 625 |
|
| 626 |
def _set_attr(self, new_attr): |
| 627 |
try: |
| 628 |
self._ava[0] = _normalize_ava_input(new_attr) |
| 629 |
except Exception as e: |
| 630 |
raise ValueError('unable to convert attr "%s": %s' % (new_attr, e)) |
| 631 |
|
| 632 |
attr = property(_get_attr) |
| 633 |
|
| 634 |
def _get_value(self): |
| 635 |
return val_decode(self._ava[1]) |
| 636 |
|
| 637 |
def _set_value(self, new_value): |
| 638 |
try: |
| 639 |
self._ava[1] = _normalize_ava_input(new_value) |
| 640 |
except Exception as e: |
| 641 |
raise ValueError('unable to convert value "%s": %s' % (new_value, e)) |
| 642 |
|
| 643 |
value = property(_get_value) |
| 644 |
|
| 645 |
def to_openldap(self): |
| 646 |
return list(self._ava) |
| 647 |
|
| 648 |
def __str__(self): |
| 649 |
return dn2str([[self.to_openldap()]]) |
| 650 |
|
| 651 |
def __repr__(self): |
| 652 |
return "%s.%s('%s')" % (self.__module__, self.__class__.__name__, self.__str__()) |
| 653 |
|
| 654 |
def __getitem__(self, key): |
| 655 |
|
| 656 |
if key == 0: |
| 657 |
return self.attr |
| 658 |
elif key == 1: |
| 659 |
return self.value |
| 660 |
elif key == self.attr: |
| 661 |
return self.value |
| 662 |
else: |
| 663 |
raise KeyError("\"%s\" not found in %s" % (key, self.__str__())) |
| 664 |
|
| 665 |
def __hash__(self): |
| 666 |
# Hash is computed from AVA's string representation. |
| 667 |
# |
| 668 |
# Because attrs & values are comparison case-insensitive the |
| 669 |
# hash value between two objects which compare as equal but |
| 670 |
# differ in case must yield the same hash value. |
| 671 |
|
| 672 |
return hash(str(self).lower()) |
| 673 |
|
| 674 |
def __eq__(self, other): |
| 675 |
''' |
| 676 |
The attr comparison is case insensitive because attr is |
| 677 |
really an LDAP attribute type which means it's specified with |
| 678 |
an OID (dotted number) and not a string. Since OID's are |
| 679 |
numeric the human readable name which maps to the OID is not |
| 680 |
significant in case. |
| 681 |
|
| 682 |
The value comparison is also case insensitive because the all |
| 683 |
attribute types used in a DN are derived from the 'name' |
| 684 |
atribute type (OID 2.5.4.41) whose EQUALITY MATCH RULE is |
| 685 |
caseIgnoreMatch. |
| 686 |
''' |
| 687 |
# Try coercing string to AVA, if successful compare to coerced object |
| 688 |
if isinstance(other, str): |
| 689 |
try: |
| 690 |
other_ava = AVA(other) |
| 691 |
return self.__eq__(other_ava) |
| 692 |
except Exception: |
| 693 |
return False |
| 694 |
|
| 695 |
# If it's not an AVA it can't be equal |
| 696 |
if not isinstance(other, AVA): |
| 697 |
return False |
| 698 |
|
| 699 |
# Perform comparison between objects of same type |
| 700 |
return ava_key(self._ava) == ava_key(other._ava) |
| 701 |
|
| 702 |
def __ne__(self, other): |
| 703 |
return not self.__eq__(other) |
| 704 |
|
| 705 |
def __lt__(self, other): |
| 706 |
'comparison is case insensitive, see __eq__ doc for explanation' |
| 707 |
|
| 708 |
if not isinstance(other, AVA): |
| 709 |
raise TypeError("expected AVA but got %s" % (other.__class__.__name__)) |
| 710 |
|
| 711 |
return ava_key(self._ava) < ava_key(other._ava) |
| 712 |
|
| 713 |
|
| 714 |
@functools.total_ordering |
| 715 |
class RDN: |
| 716 |
''' |
| 717 |
RDN(arg0, ...) |
| 718 |
|
| 719 |
An RDN is a LDAP Relative Distinguished Name. RDN's are members of DN's |
| 720 |
(Distinguished Name). An RDN contains 1 or more AVA's. If the RDN contains |
| 721 |
more than one AVA it is said to be a multi-valued RDN. When an RDN is |
| 722 |
multi-valued the AVA's are unorderd comprising a set. However this |
| 723 |
implementation orders the AVA's according to the AVA comparison function to |
| 724 |
make equality and comparison testing easier. Think of this a canonical |
| 725 |
normalization (however LDAP does not impose any ordering on multiple AVA's |
| 726 |
within an RDN). Single valued RDN's are the norm and thus the RDN |
| 727 |
constructor has simple syntax for them. |
| 728 |
|
| 729 |
The RDN constructor is passed a sequence of args and a set of |
| 730 |
keyword parameters used for configuration. |
| 731 |
|
| 732 |
The constructor iterates though the sequence and adds AVA's to the RDN. |
| 733 |
|
| 734 |
The arg sequence may be: |
| 735 |
|
| 736 |
* A 2-valued tuple or list denotes the <attr,value> pair of an AVA. The |
| 737 |
first member is the attr and the second member is the value, both members |
| 738 |
must be strings (or unicode). The tuple or list is passed to the AVA |
| 739 |
constructor and the resulting AVA is added to the RDN. Multiple tuples or |
| 740 |
lists may appear in the argument list, each adds one additional AVA to the |
| 741 |
RDN. |
| 742 |
|
| 743 |
* A single string (or unicode) argument, in this case the string will |
| 744 |
be interpretted using the DN syntax described in RFC 4514 to yield one or |
| 745 |
more AVA <attr,value> pairs. The parsing recognizes the DN syntax escaping |
| 746 |
rules. |
| 747 |
|
| 748 |
* A AVA object, the AVA will be copied into the new RDN respecting |
| 749 |
the constructors keyword configuration parameters. |
| 750 |
|
| 751 |
* A RDN object, the AVA's in the RDN are copied into the new RDN |
| 752 |
respecting the constructors keyword configuration parameters. |
| 753 |
|
| 754 |
Single AVA Examples: |
| 755 |
|
| 756 |
RDN(('cn', 'Bob')) # tuple yields 1 AVA |
| 757 |
RDN('cn=Bob') # DN syntax with 1 AVA |
| 758 |
RDN(AVA('cn', 'Bob')) # AVA object adds 1 AVA |
| 759 |
|
| 760 |
Multiple AVA Examples: |
| 761 |
|
| 762 |
RDN(('cn', 'Bob'),('ou', 'people')) # 2 tuples yields 2 AVA's |
| 763 |
RDN('cn=Bob+ou=people') # DN syntax with 2 AVA's |
| 764 |
RDN(AVA('cn', 'Bob'),AVA('ou', 'people')) # 2 AVA objects adds 2 AVA's |
| 765 |
RDN(('cn', 'Bob'), 'ou=people') # 2 args, 1st tuple forms 1 AVA, |
| 766 |
# 2nd DN syntax string adds 1 AVA, |
| 767 |
# 2 AVA's in total |
| 768 |
|
| 769 |
Note: The RHS of a slice assignment is interpreted exactly in the |
| 770 |
same manner as the constructor argument list (see above examples). |
| 771 |
|
| 772 |
RDN objects support iteration over their AVA members. You can iterate all |
| 773 |
AVA members via any Python iteration syntax. RDN objects support full Python |
| 774 |
indexing using bracket [] notation. Examples: |
| 775 |
|
| 776 |
len(rdn) # return the number of AVA's |
| 777 |
rdn[0] # indexing the first AVA |
| 778 |
rdn['cn'] # index by AVA attr, returns AVA value |
| 779 |
for ava in rdn: # iterate over each AVA |
| 780 |
rdn[:] # a slice, in this case a copy of each AVA |
| 781 |
|
| 782 |
WARNING: When indexing by attr (e.g. rdn['cn']) there is a possibility more |
| 783 |
than one AVA has the same attr name as the index key. The default behavior |
| 784 |
is to return the value of the first AVA whose attr matches the index |
| 785 |
key. |
| 786 |
|
| 787 |
RDN objects support the AVA attr and value properties as another programmer |
| 788 |
convenience because the vast majority of RDN's are single valued. The attr |
| 789 |
and value properties return the attr and value properties of the first AVA |
| 790 |
in the RDN, for example: |
| 791 |
|
| 792 |
rdn = RDN(('cn', 'Bob')) # rdn has 1 AVA whose attr == 'cn' and value == 'Bob' |
| 793 |
len(rdn) -> 1 |
| 794 |
rdn.attr -> u'cn' # exactly equivalent to rdn[0].attr |
| 795 |
rdn.value -> u'Bob' # exactly equivalent to rdn[0].value |
| 796 |
|
| 797 |
When attr and value are returned they will always be unicode. When |
| 798 |
attr or value are set they will be promoted to unicode. |
| 799 |
|
| 800 |
If an RDN is multi-valued the attr and value properties still return only |
| 801 |
the first AVA's properties, programmer beware! Recall the AVA's in the RDN |
| 802 |
are sorted according the to AVA collating semantics. |
| 803 |
|
| 804 |
RDN objects support equality testing and comparison. See AVA for the |
| 805 |
definition of the comparison method. |
| 806 |
|
| 807 |
RDN objects support concatenation and addition with other RDN's or AVA's |
| 808 |
|
| 809 |
rdn1 + rdn2 # yields a new RDN object with the contents of each RDN. |
| 810 |
rdn1 + ava1 # yields a new RDN object with the contents of rdn1 and ava1 |
| 811 |
|
| 812 |
RDN objects can add AVA's objects via in-place addition. |
| 813 |
|
| 814 |
rdn1 += rdn2 # rdn1 now contains the sum of rdn1 and rdn2 |
| 815 |
rdn1 += ava1 # rdn1 has ava1 added to it. |
| 816 |
|
| 817 |
The str method of an RDN returns the string representation in RFC 4514 DN |
| 818 |
syntax with proper escaping. |
| 819 |
''' |
| 820 |
|
| 821 |
AVA_type = AVA |
| 822 |
|
| 823 |
def __init__(self, *args, **kwds): |
| 824 |
self._avas = self._avas_from_sequence(args, kwds.get('raw', False)) |
| 825 |
|
| 826 |
def _avas_from_sequence(self, args, raw=False): |
| 827 |
avas = [] |
| 828 |
sort = 0 |
| 829 |
ava_count = len(args) |
| 830 |
|
| 831 |
if raw: # fast raw mode |
| 832 |
avas = args |
| 833 |
elif ava_count == 1 and isinstance(args[0], str): |
| 834 |
avas = str2rdn(args[0]) |
| 835 |
sort = 1 |
| 836 |
elif ava_count == 1 and isinstance(args[0], RDN): |
| 837 |
avas = args[0].to_openldap() |
| 838 |
elif ava_count > 0: |
| 839 |
sort = 1 |
| 840 |
for arg in args: |
| 841 |
avas.append(get_ava(arg)) |
| 842 |
if sort: |
| 843 |
sort_avas(avas) |
| 844 |
return avas |
| 845 |
|
| 846 |
def to_openldap(self): |
| 847 |
return [list(a) for a in self._avas] |
| 848 |
|
| 849 |
def __str__(self): |
| 850 |
return dn2str([self.to_openldap()]) |
| 851 |
|
| 852 |
def __repr__(self): |
| 853 |
return "%s.%s('%s')" % (self.__module__, self.__class__.__name__, self.__str__()) |
| 854 |
|
| 855 |
def _get_ava(self, ava): |
| 856 |
return self.AVA_type(*ava) |
| 857 |
|
| 858 |
def _next(self): |
| 859 |
for ava in self._avas: |
| 860 |
yield self._get_ava(ava) |
| 861 |
|
| 862 |
def __iter__(self): |
| 863 |
return self._next() |
| 864 |
|
| 865 |
def __len__(self): |
| 866 |
return len(self._avas) |
| 867 |
|
| 868 |
def __getitem__(self, key): |
| 869 |
if isinstance(key, int): |
| 870 |
return self._get_ava(self._avas[key]) |
| 871 |
if isinstance(key, slice): |
| 872 |
return [self._get_ava(ava) for ava in self._avas[key]] |
| 873 |
elif isinstance(key, str): |
| 874 |
for ava in self._avas: |
| 875 |
if key == val_decode(ava[0]): |
| 876 |
return val_decode(ava[1]) |
| 877 |
raise KeyError("\"%s\" not found in %s" % (key, self.__str__())) |
| 878 |
else: |
| 879 |
raise TypeError("unsupported type for RDN indexing, must be int, basestring or slice; not %s" % \ |
| 880 |
(key.__class__.__name__)) |
| 881 |
|
| 882 |
def _get_attr(self): |
| 883 |
if len(self._avas) == 0: |
| 884 |
raise IndexError("No AVA's in this RDN") |
| 885 |
return val_decode(self._avas[0][0]) |
| 886 |
|
| 887 |
def _set_attr(self, new_attr): |
| 888 |
if len(self._avas) == 0: |
| 889 |
raise IndexError("No AVA's in this RDN") |
| 890 |
|
| 891 |
self._avas[0][0] = val_encode(str(new_attr)) |
| 892 |
|
| 893 |
attr = property(_get_attr) |
| 894 |
|
| 895 |
def _get_value(self): |
| 896 |
if len(self._avas) == 0: |
| 897 |
raise IndexError("No AVA's in this RDN") |
| 898 |
return val_decode(self._avas[0][1]) |
| 899 |
|
| 900 |
def _set_value(self, new_value): |
| 901 |
if len(self._avas) == 0: |
| 902 |
raise IndexError("No AVA's in this RDN") |
| 903 |
self._avas[0][1] = val_encode(str(new_value)) |
| 904 |
|
| 905 |
value = property(_get_value) |
| 906 |
|
| 907 |
def __hash__(self): |
| 908 |
# Hash is computed from RDN's string representation. |
| 909 |
# |
| 910 |
# Because attrs & values are comparison case-insensitive the |
| 911 |
# hash value between two objects which compare as equal but |
| 912 |
# differ in case must yield the same hash value. |
| 913 |
|
| 914 |
return hash(str(self).lower()) |
| 915 |
|
| 916 |
def __eq__(self, other): |
| 917 |
# Try coercing string to RDN, if successful compare to coerced object |
| 918 |
if isinstance(other, str): |
| 919 |
try: |
| 920 |
other_rdn = RDN(other) |
| 921 |
return self.__eq__(other_rdn) |
| 922 |
except Exception: |
| 923 |
return False |
| 924 |
|
| 925 |
# If it's not an RDN it can't be equal |
| 926 |
if not isinstance(other, RDN): |
| 927 |
return False |
| 928 |
|
| 929 |
# Perform comparison between objects of same type |
| 930 |
return rdn_key(self._avas) == rdn_key(other._avas) |
| 931 |
|
| 932 |
def __ne__(self, other): |
| 933 |
return not self.__eq__(other) |
| 934 |
|
| 935 |
def __lt__(self, other): |
| 936 |
if not isinstance(other, RDN): |
| 937 |
raise TypeError("expected RDN but got %s" % (other.__class__.__name__)) |
| 938 |
|
| 939 |
return rdn_key(self._avas) < rdn_key(other._avas) |
| 940 |
|
| 941 |
def __add__(self, other): |
| 942 |
result = self.__class__(self) |
| 943 |
if isinstance(other, RDN): |
| 944 |
for ava in other._avas: |
| 945 |
result._avas.append((ava[0], ava[1], ava[2])) |
| 946 |
elif isinstance(other, AVA): |
| 947 |
result._avas.append(other.to_openldap()) |
| 948 |
elif isinstance(other, str): |
| 949 |
rdn = self.__class__(other) |
| 950 |
for ava in rdn._avas: |
| 951 |
result._avas.append((ava[0], ava[1], ava[2])) |
| 952 |
else: |
| 953 |
raise TypeError("expected RDN, AVA or basestring but got %s" % (other.__class__.__name__)) |
| 954 |
|
| 955 |
sort_avas(result._avas) |
| 956 |
return result |
| 957 |
|
| 958 |
|
| 959 |
@functools.total_ordering |
| 960 |
class DN: |
| 961 |
''' |
| 962 |
DN(arg0, ...) |
| 963 |
|
| 964 |
A DN is a LDAP Distinguished Name. A DN is an ordered sequence of RDN's. |
| 965 |
|
| 966 |
The DN constructor is passed a sequence of args and a set of |
| 967 |
keyword parameters used for configuration. normalize means the |
| 968 |
attr and value will be converted to lower case. |
| 969 |
|
| 970 |
The constructor iterates through the sequence and adds the RDN's |
| 971 |
it finds in order to the DN object. Each item in the sequence may |
| 972 |
be: |
| 973 |
|
| 974 |
* A 2-valued tuple or list. The first member is the attr and the |
| 975 |
second member is the value of an RDN, both members must be |
| 976 |
strings (or unicode). The tuple or list is passed to the RDN |
| 977 |
constructor and the resulting RDN is appended to the |
| 978 |
DN. Multiple tuples or lists may appear in the argument list, |
| 979 |
each adds one additional RDN to the DN. |
| 980 |
|
| 981 |
* A single string (or unicode) argument, in this case the string |
| 982 |
will be interpretted using the DN syntax described in RFC 4514 |
| 983 |
to yield one or more RDN's which will be appended in order to |
| 984 |
the DN. The parsing recognizes the DN syntax escaping rules. |
| 985 |
|
| 986 |
* A single ``cryptography.x509.name.Name`` object. |
| 987 |
|
| 988 |
* A RDN object, the RDN will copied respecting the constructors |
| 989 |
keyword configuration parameters and appended in order. |
| 990 |
|
| 991 |
* A DN object, the RDN's in the DN are copied respecting the |
| 992 |
constructors keyword configuration parameters and appended in |
| 993 |
order. |
| 994 |
|
| 995 |
Single DN Examples: |
| 996 |
|
| 997 |
DN(('cn', 'Bob')) # tuple yields 1 RDN |
| 998 |
DN(['cn', 'Bob']) # list yields 1 RDN |
| 999 |
DN('cn=Bob') # DN syntax with 1 RDN |
| 1000 |
DN(RDN('cn', 'Bob')) # RDN object adds 1 RDN |
| 1001 |
|
| 1002 |
Multiple RDN Examples: |
| 1003 |
|
| 1004 |
DN(('cn', 'Bob'),('ou', 'people')) # 2 tuples yields 2 RDN's |
| 1005 |
# 2 RDN's total |
| 1006 |
DN('cn=Bob,ou=people') # DN syntax with 2 RDN's |
| 1007 |
# 2 RDN's total |
| 1008 |
DN(RDN('cn', 'Bob'),RDN('ou', 'people')) # 2 RDN objects |
| 1009 |
# 2 RDN's total |
| 1010 |
DN(('cn', 'Bob'), "ou=people') # 1st tuple adds 1 RDN |
| 1011 |
# 2nd DN syntax string adds 1 RDN |
| 1012 |
# 2 RDN's total |
| 1013 |
base_dn = DN('dc=redhat,dc=com') |
| 1014 |
container_dn = DN('cn=sudorules,cn=sudo') |
| 1015 |
DN(('cn', 'Bob'), container_dn, base_dn) |
| 1016 |
# 1st arg adds 1 RDN, cn=Bob |
| 1017 |
# 2nd arg adds 2 RDN's, cn=sudorules,cn=sudo |
| 1018 |
# 3rd arg adds 2 RDN's, dc=redhat,dc=com |
| 1019 |
# 5 RDN's total |
| 1020 |
|
| 1021 |
|
| 1022 |
Note: The RHS of a slice assignment is interpreted exactly in the |
| 1023 |
same manner as the constructor argument list (see above examples). |
| 1024 |
|
| 1025 |
DN objects support iteration over their RDN members. You can iterate all |
| 1026 |
RDN members via any Python iteration syntax. DN objects support full Python |
| 1027 |
indexing using bracket [] notation. Examples: |
| 1028 |
|
| 1029 |
len(rdn) # return the number of RDN's |
| 1030 |
rdn[0] # indexing the first RDN |
| 1031 |
rdn['cn'] # index by RDN attr, returns RDN value |
| 1032 |
for ava in rdn: # iterate over each RDN |
| 1033 |
rdn[:] # a slice, in this case a copy of each RDN |
| 1034 |
|
| 1035 |
WARNING: When indexing by attr (e.g. dn['cn']) there is a |
| 1036 |
possibility more than one RDN has the same attr name as the index |
| 1037 |
key. The default behavior is to return the value of the first RDN |
| 1038 |
whose attr matches the index key. If it's important the attr |
| 1039 |
belong to a specific RDN (e.g. the first) then this is the |
| 1040 |
suggested construct: |
| 1041 |
|
| 1042 |
try: |
| 1043 |
cn = dn[0]['cn'] |
| 1044 |
except (IndexError, KeyError): |
| 1045 |
raise ValueError("dn '%s' missing expected cn as first attribute" % dn) |
| 1046 |
|
| 1047 |
The IndexError catches a DN which does not have the expected |
| 1048 |
number of RDN's and the KeyError catches the case where the |
| 1049 |
indexed RDN does not have the expected attr. |
| 1050 |
|
| 1051 |
DN object support slices. |
| 1052 |
|
| 1053 |
# Get the first two RDN's using slices |
| 1054 |
dn[0:2] |
| 1055 |
|
| 1056 |
# Get the last two RDN's using slices |
| 1057 |
dn[-2:] |
| 1058 |
|
| 1059 |
# Get a list of all RDN's using slices |
| 1060 |
dn[:] |
| 1061 |
|
| 1062 |
# Set the 2nd and 3rd RDN using slices (all are equivalent) |
| 1063 |
dn[1:3] = ('cn', 'Bob'), ('dc', 'redhat.com') |
| 1064 |
dn[1:3] = [['cn', 'Bob'], ['dc', 'redhat.com']] |
| 1065 |
dn[1:3] = RDN('cn', 'Bob'), RDN('dc', 'redhat.com') |
| 1066 |
|
| 1067 |
DN objects support the insert operation. |
| 1068 |
|
| 1069 |
dn.insert(i,x) is exactly equivalent to dn[i:i] = [x], thus the following |
| 1070 |
are all equivalent: |
| 1071 |
|
| 1072 |
dn.insert(i, ('cn','Bob')) |
| 1073 |
dn.insert(i, ['cn','Bob']) |
| 1074 |
dn.insert(i, RDN(('cn','Bob'))) |
| 1075 |
dn[i:i] = [('cn','Bob')] |
| 1076 |
|
| 1077 |
DN objects support equality testing and comparison. See RDN for the |
| 1078 |
definition of the comparison method. |
| 1079 |
|
| 1080 |
DN objects implement startswith(), endswith() and the "in" membership |
| 1081 |
operator. You may pass a DN or RDN object to these. Examples: |
| 1082 |
|
| 1083 |
# Test if dn ends with the contents of base_dn |
| 1084 |
if dn.endswith(base_dn): |
| 1085 |
# Test if dn starts with a rdn |
| 1086 |
if dn.startswith(rdn1): |
| 1087 |
# Test if a container is present in a dn |
| 1088 |
if container_dn in dn: |
| 1089 |
|
| 1090 |
DN objects support concatenation and addition with other DN's or RDN's |
| 1091 |
or strings (interpreted as RFC 4514 DN syntax). |
| 1092 |
|
| 1093 |
# yields a new DN object with the RDN's of dn2 appended to the RDN's of dn1 |
| 1094 |
dn1 + dn2 |
| 1095 |
|
| 1096 |
# yields a new DN object with the rdn1 appended to the RDN's of dn1 |
| 1097 |
dn1 + rdn1 |
| 1098 |
|
| 1099 |
DN objects can add RDN's objects via in-place addition. |
| 1100 |
|
| 1101 |
dn1 += dn2 # dn2 RDN's are appended to the dn1's RDN's |
| 1102 |
dn1 += rdn1 # dn1 has rdn appended to its RDN's |
| 1103 |
dn1 += "dc=redhat.com" # string is converted to DN, then appended |
| 1104 |
|
| 1105 |
The str method of an DN returns the string representation in RFC 4514 DN |
| 1106 |
syntax with proper escaping. |
| 1107 |
''' |
| 1108 |
|
| 1109 |
AVA_type = AVA |
| 1110 |
RDN_type = RDN |
| 1111 |
|
| 1112 |
def __init__(self, *args, **kwds): |
| 1113 |
self.rdns = self._rdns_from_sequence(args) |
| 1114 |
|
| 1115 |
def _copy_rdns(self, rdns=None): |
| 1116 |
if not rdns: |
| 1117 |
rdns = self.rdns |
| 1118 |
return [[list(a) for a in rdn] for rdn in rdns] |
| 1119 |
|
| 1120 |
def _rdns_from_value(self, value): |
| 1121 |
if isinstance(value, str): |
| 1122 |
try: |
| 1123 |
if isinstance(value, str): |
| 1124 |
value = val_encode(value) |
| 1125 |
rdns = str2dn(value) |
| 1126 |
except DECODING_ERROR: |
| 1127 |
raise ValueError("malformed RDN string = \"%s\"" % value) |
| 1128 |
for rdn in rdns: |
| 1129 |
sort_avas(rdn) |
| 1130 |
elif isinstance(value, DN): |
| 1131 |
rdns = value._copy_rdns() |
| 1132 |
elif isinstance(value, (tuple, list, AVA)): |
| 1133 |
ava = get_ava(value) |
| 1134 |
rdns = [[ava]] |
| 1135 |
elif isinstance(value, RDN): |
| 1136 |
rdns = [value.to_openldap()] |
| 1137 |
elif isinstance(value, cryptography.x509.name.Name): |
| 1138 |
rdns = list(reversed([ |
| 1139 |
[get_ava( |
| 1140 |
ATTR_NAME_BY_OID.get(ava.oid, ava.oid.dotted_string), |
| 1141 |
ava.value) for ava in rdn] |
| 1142 |
for rdn in value.rdns |
| 1143 |
])) |
| 1144 |
for rdn in rdns: |
| 1145 |
sort_avas(rdn) |
| 1146 |
else: |
| 1147 |
raise TypeError( |
| 1148 |
"must be str, unicode, tuple, Name, RDN or DN, got %s instead" |
| 1149 |
% type(value)) |
| 1150 |
return rdns |
| 1151 |
|
| 1152 |
def _rdns_from_sequence(self, seq): |
| 1153 |
rdns = [] |
| 1154 |
|
| 1155 |
for item in seq: |
| 1156 |
rdn = self._rdns_from_value(item) |
| 1157 |
rdns.extend(rdn) |
| 1158 |
return rdns |
| 1159 |
|
| 1160 |
def __deepcopy__(self, memo): |
| 1161 |
return self |
| 1162 |
|
| 1163 |
def _get_rdn(self, rdn): |
| 1164 |
return self.RDN_type(*rdn, **{'raw': True}) |
| 1165 |
|
| 1166 |
def ldap_text(self): |
| 1167 |
return dn2str(self.rdns) |
| 1168 |
|
| 1169 |
def x500_text(self): |
| 1170 |
return dn2str(reversed(self.rdns)) |
| 1171 |
|
| 1172 |
def __str__(self): |
| 1173 |
return self.ldap_text() |
| 1174 |
|
| 1175 |
def __repr__(self): |
| 1176 |
return "%s.%s('%s')" % (self.__module__, self.__class__.__name__, self.__str__()) |
| 1177 |
|
| 1178 |
def _next(self): |
| 1179 |
for rdn in self.rdns: |
| 1180 |
yield self._get_rdn(rdn) |
| 1181 |
|
| 1182 |
def __iter__(self): |
| 1183 |
return self._next() |
| 1184 |
|
| 1185 |
def __len__(self): |
| 1186 |
return len(self.rdns) |
| 1187 |
|
| 1188 |
def __getitem__(self, key): |
| 1189 |
if isinstance(key, int): |
| 1190 |
return self._get_rdn(self.rdns[key]) |
| 1191 |
if isinstance(key, slice): |
| 1192 |
cls = self.__class__ |
| 1193 |
new_dn = cls.__new__(cls) |
| 1194 |
new_dn.rdns = self.rdns[key] |
| 1195 |
return new_dn |
| 1196 |
elif isinstance(key, str): |
| 1197 |
for rdn in self.rdns: |
| 1198 |
for ava in rdn: |
| 1199 |
if key == val_decode(ava[0]): |
| 1200 |
return val_decode(ava[1]) |
| 1201 |
raise KeyError("\"%s\" not found in %s" % (key, self.__str__())) |
| 1202 |
else: |
| 1203 |
raise TypeError("unsupported type for DN indexing, must be int, basestring or slice; not %s" % \ |
| 1204 |
(key.__class__.__name__)) |
| 1205 |
|
| 1206 |
def __hash__(self): |
| 1207 |
# Hash is computed from DN's string representation. |
| 1208 |
# |
| 1209 |
# Because attrs & values are comparison case-insensitive the |
| 1210 |
# hash value between two objects which compare as equal but |
| 1211 |
# differ in case must yield the same hash value. |
| 1212 |
|
| 1213 |
str_dn = ';,'.join([ |
| 1214 |
'++'.join([ |
| 1215 |
'=='.join((atype, avalue or '')) |
| 1216 |
for atype, avalue, _dummy in rdn |
| 1217 |
]) for rdn in self.rdns |
| 1218 |
]) |
| 1219 |
return hash(str_dn.lower()) |
| 1220 |
|
| 1221 |
def __eq__(self, other): |
| 1222 |
# Try coercing to DN, if successful compare to coerced object |
| 1223 |
if isinstance(other, (str, RDN, AVA)): |
| 1224 |
try: |
| 1225 |
other_dn = DN(other) |
| 1226 |
return self.__eq__(other_dn) |
| 1227 |
except Exception: |
| 1228 |
return False |
| 1229 |
|
| 1230 |
# If it's not an DN it can't be equal |
| 1231 |
if not isinstance(other, DN): |
| 1232 |
return False |
| 1233 |
|
| 1234 |
if len(self) != len(other): |
| 1235 |
return False |
| 1236 |
|
| 1237 |
# Perform comparison between objects of same type |
| 1238 |
return self._cmp_sequence(other, 0, len(self)) == 0 |
| 1239 |
|
| 1240 |
def __ne__(self, other): |
| 1241 |
return not self.__eq__(other) |
| 1242 |
|
| 1243 |
def __lt__(self, other): |
| 1244 |
if not isinstance(other, DN): |
| 1245 |
raise TypeError("expected DN but got %s" % (other.__class__.__name__)) |
| 1246 |
|
| 1247 |
if len(self) != len(other): |
| 1248 |
return len(self) < len(other) |
| 1249 |
|
| 1250 |
return self._cmp_sequence(other, 0, len(self)) < 0 |
| 1251 |
|
| 1252 |
def _cmp_sequence(self, pattern, self_start, pat_len): |
| 1253 |
self_idx = self_start |
| 1254 |
pat_idx = 0 |
| 1255 |
while pat_idx < pat_len: |
| 1256 |
r = cmp_rdns(self.rdns[self_idx], pattern.rdns[pat_idx]) |
| 1257 |
if r != 0: |
| 1258 |
return r |
| 1259 |
self_idx += 1 |
| 1260 |
pat_idx += 1 |
| 1261 |
return 0 |
| 1262 |
|
| 1263 |
def __add__(self, other): |
| 1264 |
return self.__class__(self, other) |
| 1265 |
|
| 1266 |
# The implementation of startswith, endswith, tailmatch, adjust_indices |
| 1267 |
# was based on the Python's stringobject.c implementation |
| 1268 |
|
| 1269 |
def startswith(self, prefix, start=0, end=sys.maxsize): |
| 1270 |
''' |
| 1271 |
Return True if the dn starts with the specified prefix (either a DN or |
| 1272 |
RDN object), False otherwise. With optional start, test dn beginning at |
| 1273 |
that position. With optional end, stop comparing dn at that position. |
| 1274 |
prefix can also be a tuple of dn's or rdn's to try. |
| 1275 |
''' |
| 1276 |
if isinstance(prefix, tuple): |
| 1277 |
for pat in prefix: |
| 1278 |
if self._tailmatch(pat, start, end, -1): |
| 1279 |
return True |
| 1280 |
return False |
| 1281 |
|
| 1282 |
return self._tailmatch(prefix, start, end, -1) |
| 1283 |
|
| 1284 |
def endswith(self, suffix, start=0, end=sys.maxsize): |
| 1285 |
''' |
| 1286 |
Return True if dn ends with the specified suffix (either a DN or RDN |
| 1287 |
object), False otherwise. With optional start, test dn beginning at |
| 1288 |
that position. With optional end, stop comparing dn at that position. |
| 1289 |
suffix can also be a tuple of dn's or rdn's to try. |
| 1290 |
''' |
| 1291 |
if isinstance(suffix, tuple): |
| 1292 |
for pat in suffix: |
| 1293 |
if self._tailmatch(pat, start, end, +1): |
| 1294 |
return True |
| 1295 |
return False |
| 1296 |
|
| 1297 |
return self._tailmatch(suffix, start, end, +1) |
| 1298 |
|
| 1299 |
def _tailmatch(self, pattern, start, end, direction): |
| 1300 |
''' |
| 1301 |
Matches the end (direction >= 0) or start (direction < 0) of self |
| 1302 |
against pattern (either a DN or RDN), using the start and end |
| 1303 |
arguments. Returns 0 if not found and 1 if found. |
| 1304 |
''' |
| 1305 |
|
| 1306 |
if isinstance(pattern, RDN): |
| 1307 |
pattern = DN(pattern) |
| 1308 |
if isinstance(pattern, DN): |
| 1309 |
pat_len = len(pattern) |
| 1310 |
else: |
| 1311 |
raise TypeError("expected DN or RDN but got %s" % (pattern.__class__.__name__)) |
| 1312 |
|
| 1313 |
self_len = len(self) |
| 1314 |
|
| 1315 |
start, end = _adjust_indices(start, end, self_len) |
| 1316 |
|
| 1317 |
if direction < 0: # starswith |
| 1318 |
if start+pat_len > self_len: |
| 1319 |
return 0 |
| 1320 |
else: # endswith |
| 1321 |
if end-start < pat_len or start > self_len: |
| 1322 |
return 0 |
| 1323 |
|
| 1324 |
if end-pat_len >= start: |
| 1325 |
start = end - pat_len |
| 1326 |
|
| 1327 |
if end-start >= pat_len: |
| 1328 |
return not self._cmp_sequence(pattern, start, pat_len) |
| 1329 |
return 0 |
| 1330 |
|
| 1331 |
def __contains__(self, other): |
| 1332 |
"""Return the outcome of the test other in self. |
| 1333 |
|
| 1334 |
Note the reversed operands. |
| 1335 |
""" |
| 1336 |
|
| 1337 |
if isinstance(other, RDN): |
| 1338 |
other = DN(other) |
| 1339 |
if isinstance(other, DN): |
| 1340 |
other_len = len(other) |
| 1341 |
end = len(self) - other_len |
| 1342 |
i = 0 |
| 1343 |
while i <= end: |
| 1344 |
result = self._cmp_sequence(other, i, other_len) |
| 1345 |
if result == 0: |
| 1346 |
return True |
| 1347 |
i += 1 |
| 1348 |
return False |
| 1349 |
raise TypeError( |
| 1350 |
"expected DN or RDN but got %s" % other.__class__.__name__ |
| 1351 |
) |
| 1352 |
|
| 1353 |
def find(self, pattern, start=None, end=None): |
| 1354 |
''' |
| 1355 |
Return the lowest index in the DN where pattern DN is found, |
| 1356 |
such that pattern is contained in the range [start, end]. Optional |
| 1357 |
arguments start and end are interpreted as in slice notation. Return |
| 1358 |
-1 if pattern is not found. |
| 1359 |
''' |
| 1360 |
|
| 1361 |
if isinstance(pattern, DN): |
| 1362 |
pat_len = len(pattern) |
| 1363 |
else: |
| 1364 |
raise TypeError("expected DN but got %s" % (pattern.__class__.__name__)) |
| 1365 |
|
| 1366 |
self_len = len(self) |
| 1367 |
|
| 1368 |
if start is None: |
| 1369 |
start = 0 |
| 1370 |
if end is None: |
| 1371 |
end = self_len |
| 1372 |
|
| 1373 |
start, end = _adjust_indices(start, end, self_len) |
| 1374 |
|
| 1375 |
i = start |
| 1376 |
stop = max(start, end - pat_len) |
| 1377 |
|
| 1378 |
while i <= stop: |
| 1379 |
result = self._cmp_sequence(pattern, i, pat_len) |
| 1380 |
if result == 0: |
| 1381 |
return i |
| 1382 |
i += 1 |
| 1383 |
return -1 |
| 1384 |
|
| 1385 |
|
| 1386 |
def index(self, pattern, start=None, end=None): |
| 1387 |
''' |
| 1388 |
Like find() but raise ValueError when the pattern is not found. |
| 1389 |
''' |
| 1390 |
|
| 1391 |
i = self.find(pattern, start, end) |
| 1392 |
if i == -1: |
| 1393 |
raise ValueError("pattern not found") |
| 1394 |
return i |
| 1395 |
|
| 1396 |
def rfind(self, pattern, start=None, end=None): |
| 1397 |
''' |
| 1398 |
Return the highest index in the DN where pattern DN is found, |
| 1399 |
such that pattern is contained in the range [start, end]. Optional |
| 1400 |
arguments start and end are interpreted as in slice notation. Return |
| 1401 |
-1 if pattern is not found. |
| 1402 |
''' |
| 1403 |
|
| 1404 |
if isinstance(pattern, DN): |
| 1405 |
pat_len = len(pattern) |
| 1406 |
else: |
| 1407 |
raise TypeError("expected DN but got %s" % (pattern.__class__.__name__)) |
| 1408 |
|
| 1409 |
self_len = len(self) |
| 1410 |
|
| 1411 |
if start is None: |
| 1412 |
start = 0 |
| 1413 |
if end is None: |
| 1414 |
end = self_len |
| 1415 |
|
| 1416 |
start, end = _adjust_indices(start, end, self_len) |
| 1417 |
|
| 1418 |
i = max(start, min(end, self_len - pat_len)) |
| 1419 |
stop = start |
| 1420 |
|
| 1421 |
while i >= stop: |
| 1422 |
result = self._cmp_sequence(pattern, i, pat_len) |
| 1423 |
if result == 0: |
| 1424 |
return i |
| 1425 |
i -= 1 |
| 1426 |
return -1 |
| 1427 |
|
| 1428 |
def rindex(self, pattern, start=None, end=None): |
| 1429 |
''' |
| 1430 |
Like rfind() but raise ValueError when the pattern is not found. |
| 1431 |
''' |
| 1432 |
|
| 1433 |
i = self.rfind(pattern, start, end) |
| 1434 |
if i == -1: |
| 1435 |
raise ValueError("pattern not found") |
| 1436 |
return i |
| 1437 |
|
| 1438 |
|
| 1439 |
ATTR_NAME_BY_OID = { |
| 1440 |
cryptography.x509.oid.NameOID.COMMON_NAME: 'CN', |
| 1441 |
cryptography.x509.oid.NameOID.COUNTRY_NAME: 'C', |
| 1442 |
cryptography.x509.oid.NameOID.LOCALITY_NAME: 'L', |
| 1443 |
cryptography.x509.oid.NameOID.STATE_OR_PROVINCE_NAME: 'ST', |
| 1444 |
cryptography.x509.oid.NameOID.ORGANIZATION_NAME: 'O', |
| 1445 |
cryptography.x509.oid.NameOID.ORGANIZATIONAL_UNIT_NAME: 'OU', |
| 1446 |
cryptography.x509.oid.NameOID.SERIAL_NUMBER: 'serialNumber', |
| 1447 |
cryptography.x509.oid.NameOID.SURNAME: 'SN', |
| 1448 |
cryptography.x509.oid.NameOID.GIVEN_NAME: 'givenName', |
| 1449 |
cryptography.x509.oid.NameOID.TITLE: 'title', |
| 1450 |
cryptography.x509.oid.NameOID.GENERATION_QUALIFIER: 'generationQualifier', |
| 1451 |
cryptography.x509.oid.NameOID.DN_QUALIFIER: 'dnQualifier', |
| 1452 |
cryptography.x509.oid.NameOID.PSEUDONYM: 'pseudonym', |
| 1453 |
cryptography.x509.oid.NameOID.DOMAIN_COMPONENT: 'DC', |
| 1454 |
cryptography.x509.oid.NameOID.EMAIL_ADDRESS: 'E', |
| 1455 |
cryptography.x509.oid.NameOID.JURISDICTION_COUNTRY_NAME: |
| 1456 |
'incorporationCountry', |
| 1457 |
cryptography.x509.oid.NameOID.JURISDICTION_LOCALITY_NAME: |
| 1458 |
'incorporationLocality', |
| 1459 |
cryptography.x509.oid.NameOID.JURISDICTION_STATE_OR_PROVINCE_NAME: |
| 1460 |
'incorporationState', |
| 1461 |
cryptography.x509.oid.NameOID.BUSINESS_CATEGORY: 'businessCategory', |
| 1462 |
cryptography.x509.ObjectIdentifier('2.5.4.9'): 'STREET', |
| 1463 |
cryptography.x509.ObjectIdentifier('2.5.4.17'): 'postalCode', |
| 1464 |
cryptography.x509.ObjectIdentifier('0.9.2342.19200300.100.1.1'): 'UID', |
| 1465 |
cryptography.x509.ObjectIdentifier('2.5.4.97'): 'organizationIdentifier', |
| 1466 |
} |