| 1 |
# Authors: Rich Megginson <[email protected]> |
| 2 |
# Rob Crittenden <[email protected]> |
| 3 |
# John Dennis <[email protected]> |
| 4 |
# |
| 5 |
# Copyright (C) 2007 Red Hat |
| 6 |
# see file 'COPYING' for use and warranty information |
| 7 |
# |
| 8 |
# This program is free software; you can redistribute it and/or modify |
| 9 |
# it under the terms of the GNU General Public License as published by |
| 10 |
# the Free Software Foundation, either version 3 of the License, or |
| 11 |
# (at your option) any later version. |
| 12 |
# |
| 13 |
# This program is distributed in the hope that it will be useful, |
| 14 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 16 |
# GNU General Public License for more details. |
| 17 |
# |
| 18 |
# You should have received a copy of the GNU General Public License |
| 19 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 20 |
# |
| 21 |
|
| 22 |
import binascii |
| 23 |
import errno |
| 24 |
import logging |
| 25 |
import time |
| 26 |
from datetime import datetime |
| 27 |
from decimal import Decimal |
| 28 |
from copy import deepcopy |
| 29 |
import contextlib |
| 30 |
import os |
| 31 |
import pwd |
| 32 |
import warnings |
| 33 |
|
| 34 |
from collections import OrderedDict |
| 35 |
|
| 36 |
from cryptography.hazmat.primitives import serialization |
| 37 |
|
| 38 |
import ldap |
| 39 |
import ldap.sasl |
| 40 |
import ldap.filter |
| 41 |
from ldap.controls import SimplePagedResultsControl, GetEffectiveRightsControl |
| 42 |
import ldapurl |
| 43 |
import six |
| 44 |
|
| 45 |
# pylint: disable=ipa-forbidden-import |
| 46 |
from ipalib import errors, x509, _ |
| 47 |
from ipalib.constants import LDAP_GENERALIZED_TIME_FORMAT |
| 48 |
# pylint: enable=ipa-forbidden-import |
| 49 |
from ipaplatform.paths import paths |
| 50 |
from ipapython.ipautil import format_netloc, CIDict |
| 51 |
from ipapython.dn import DN, RDN |
| 52 |
from ipapython.dnsutil import DNSName |
| 53 |
from ipapython.kerberos import Principal |
| 54 |
|
| 55 |
from collections.abc import MutableMapping |
| 56 |
|
| 57 |
if six.PY3: |
| 58 |
unicode = str |
| 59 |
|
| 60 |
logger = logging.getLogger(__name__) |
| 61 |
|
| 62 |
# Global variable to define SASL auth |
| 63 |
SASL_GSSAPI = ldap.sasl.sasl({}, 'GSSAPI') |
| 64 |
SASL_GSS_SPNEGO = ldap.sasl.sasl({}, 'GSS-SPNEGO') |
| 65 |
|
| 66 |
_debug_log_ldap = False |
| 67 |
|
| 68 |
_missing = object() |
| 69 |
|
| 70 |
# Autobind modes |
| 71 |
AUTOBIND_AUTO = 1 |
| 72 |
AUTOBIND_ENABLED = 2 |
| 73 |
AUTOBIND_DISABLED = 3 |
| 74 |
|
| 75 |
TRUNCATED_SIZE_LIMIT = object() |
| 76 |
TRUNCATED_TIME_LIMIT = object() |
| 77 |
TRUNCATED_ADMIN_LIMIT = object() |
| 78 |
|
| 79 |
DIRMAN_DN = DN(('cn', 'directory manager')) |
| 80 |
|
| 81 |
|
| 82 |
if six.PY2 and hasattr(ldap, 'LDAPBytesWarning'): |
| 83 |
# XXX silence python-ldap's BytesWarnings |
| 84 |
warnings.filterwarnings( |
| 85 |
action="ignore", |
| 86 |
category=ldap.LDAPBytesWarning, |
| 87 |
) |
| 88 |
|
| 89 |
|
| 90 |
def realm_to_serverid(realm_name): |
| 91 |
"""Convert Kerberos realm name to 389-DS server id""" |
| 92 |
return "-".join(realm_name.split(".")) |
| 93 |
|
| 94 |
|
| 95 |
def realm_to_ldapi_uri(realm_name): |
| 96 |
"""Get ldapi:// URI to 389-DS's Unix socket""" |
| 97 |
serverid = realm_to_serverid(realm_name) |
| 98 |
socketname = paths.SLAPD_INSTANCE_SOCKET_TEMPLATE % (serverid,) |
| 99 |
return 'ldapi://' + ldapurl.ldapUrlEscape(socketname) |
| 100 |
|
| 101 |
|
| 102 |
def ldap_initialize(uri, cacertfile=None): |
| 103 |
"""Wrapper around ldap.initialize() |
| 104 |
|
| 105 |
The function undoes global and local ldap.conf settings that may cause |
| 106 |
issues or reduce security: |
| 107 |
|
| 108 |
* Canonization of SASL host names is disabled. |
| 109 |
* With cacertfile=None, the connection uses OpenSSL's default verify |
| 110 |
locations, also known as system-wide trust store. |
| 111 |
* Cert validation is enforced. |
| 112 |
* SSLv2 and SSLv3 are disabled. |
| 113 |
""" |
| 114 |
conn = ldap.initialize(uri) |
| 115 |
|
| 116 |
# Do not perform reverse DNS lookups to canonicalize SASL host names |
| 117 |
conn.set_option(ldap.OPT_X_SASL_NOCANON, ldap.OPT_ON) |
| 118 |
|
| 119 |
if not uri.startswith('ldapi://'): |
| 120 |
if cacertfile: |
| 121 |
if not os.path.isfile(cacertfile): |
| 122 |
raise IOError(errno.ENOENT, cacertfile) |
| 123 |
conn.set_option(ldap.OPT_X_TLS_CACERTFILE, cacertfile) |
| 124 |
|
| 125 |
# SSLv3 and SSLv2 are insecure |
| 126 |
# OpenLDAP 2.4 sets minimum version with SSL_CTX_set_options(). The |
| 127 |
# system-wide crypto-policies for TLS minimum version are applied |
| 128 |
# with SSL_CTX_set_min_proto_version(). The set_option() call cannot |
| 129 |
# enable lower versions than allowed by crypto-policy, e.g. |
| 130 |
# openssl.cnf MinProtocol=TLS1.2 + OPT_X_TLS_PROTOCOL_MIN=TLS1.0 |
| 131 |
# result in TLS 1.2 as minimum protocol version. |
| 132 |
conn.set_option(ldap.OPT_X_TLS_PROTOCOL_MIN, 0x301) # TLS 1.0 |
| 133 |
# libldap defaults to cert validation, but the default can be |
| 134 |
# overridden in global or user local ldap.conf. |
| 135 |
conn.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_DEMAND) |
| 136 |
# reinitialize TLS context to materialize settings |
| 137 |
conn.set_option(ldap.OPT_X_TLS_NEWCTX, 0) |
| 138 |
|
| 139 |
return conn |
| 140 |
|
| 141 |
|
| 142 |
class _ServerSchema: |
| 143 |
''' |
| 144 |
Properties of a schema retrieved from an LDAP server. |
| 145 |
''' |
| 146 |
|
| 147 |
def __init__(self, server, schema): |
| 148 |
self.server = server |
| 149 |
self.schema = schema |
| 150 |
self.retrieve_timestamp = time.time() |
| 151 |
|
| 152 |
|
| 153 |
class SchemaCache: |
| 154 |
''' |
| 155 |
Cache the schema's from individual LDAP servers. |
| 156 |
''' |
| 157 |
|
| 158 |
def __init__(self): |
| 159 |
self.servers = {} |
| 160 |
|
| 161 |
def get_schema(self, url, conn, force_update=False): |
| 162 |
''' |
| 163 |
Return schema belonging to a specific LDAP server. |
| 164 |
|
| 165 |
For performance reasons the schema is retrieved once and |
| 166 |
cached unless force_update is True. force_update flushes the |
| 167 |
existing schema for the server from the cache and reacquires |
| 168 |
it. |
| 169 |
''' |
| 170 |
|
| 171 |
if force_update: |
| 172 |
self.flush(url) |
| 173 |
|
| 174 |
server_schema = self.servers.get(url) |
| 175 |
if server_schema is None: |
| 176 |
schema = self._retrieve_schema_from_server(url, conn) |
| 177 |
server_schema = _ServerSchema(url, schema) |
| 178 |
self.servers[url] = server_schema |
| 179 |
return server_schema.schema |
| 180 |
|
| 181 |
def flush(self, url): |
| 182 |
logger.debug('flushing %s from SchemaCache', url) |
| 183 |
try: |
| 184 |
del self.servers[url] |
| 185 |
except KeyError: |
| 186 |
pass |
| 187 |
|
| 188 |
def _retrieve_schema_from_server(self, url, conn): |
| 189 |
""" |
| 190 |
Retrieve the LDAP schema from the provided url and determine if |
| 191 |
User-Private Groups (upg) are configured. |
| 192 |
|
| 193 |
Bind using kerberos credentials. If in the context of the |
| 194 |
in-tree "lite" server then use the current ccache. If in the context of |
| 195 |
Apache then create a new ccache and bind using the Apache HTTP service |
| 196 |
principal. |
| 197 |
|
| 198 |
If a connection is provided then it the credentials bound to it are |
| 199 |
used. The connection is not closed when the request is done. |
| 200 |
""" |
| 201 |
assert conn is not None |
| 202 |
|
| 203 |
logger.debug( |
| 204 |
'retrieving schema for SchemaCache url=%s conn=%s', url, conn) |
| 205 |
|
| 206 |
try: |
| 207 |
try: |
| 208 |
schema_entry = conn.search_s('cn=schema', ldap.SCOPE_BASE, |
| 209 |
attrlist=['attributetypes', 'objectclasses'])[0] |
| 210 |
except ldap.NO_SUCH_OBJECT: |
| 211 |
# try different location for schema |
| 212 |
# openldap has schema located in cn=subschema |
| 213 |
logger.debug('cn=schema not found, fallback to cn=subschema') |
| 214 |
schema_entry = conn.search_s('cn=subschema', ldap.SCOPE_BASE, |
| 215 |
attrlist=['attributetypes', 'objectclasses'])[0] |
| 216 |
except ldap.SERVER_DOWN: |
| 217 |
raise errors.NetworkError(uri=url, |
| 218 |
error=u'LDAP Server Down, unable to retrieve LDAP schema') |
| 219 |
except ldap.LDAPError as e: |
| 220 |
desc = e.args[0]['desc'].strip() |
| 221 |
info = e.args[0].get('info', '').strip() |
| 222 |
raise errors.DatabaseError(desc = u'uri=%s' % url, |
| 223 |
info = u'Unable to retrieve LDAP schema: %s: %s' % (desc, info)) |
| 224 |
|
| 225 |
# no 'cn=schema' entry in LDAP? some servers use 'cn=subschema' |
| 226 |
# TODO: DS uses 'cn=schema', support for other server? |
| 227 |
# raise a more appropriate exception |
| 228 |
|
| 229 |
return ldap.schema.SubSchema(schema_entry[1]) |
| 230 |
|
| 231 |
schema_cache = SchemaCache() |
| 232 |
|
| 233 |
|
| 234 |
class LDAPEntry(MutableMapping): |
| 235 |
__slots__ = ('_conn', '_dn', '_names', '_nice', '_raw', '_sync', |
| 236 |
'_not_list', '_orig_raw', '_raw_view', |
| 237 |
'_single_value_view') |
| 238 |
|
| 239 |
__hash__ = None |
| 240 |
|
| 241 |
def __init__(self, _conn, _dn=None, _obj=None, **kwargs): |
| 242 |
""" |
| 243 |
LDAPEntry constructor. |
| 244 |
|
| 245 |
Takes 1 to 3 positional arguments and an arbitrary number of keyword |
| 246 |
arguments. The 3 forms of positional arguments are: |
| 247 |
|
| 248 |
* LDAPEntry(entry) - create a shallow copy of an existing LDAPEntry. |
| 249 |
* LDAPEntry(dn, entry) - create a shallow copy of an existing |
| 250 |
LDAPEntry with a different DN. |
| 251 |
* LDAPEntry(conn, dn, mapping) - create a new LDAPEntry using the |
| 252 |
specified LDAPClient and DN and optionally initialize |
| 253 |
attributes from the specified mapping object. |
| 254 |
|
| 255 |
Keyword arguments can be used to override values of specific attributes. |
| 256 |
""" |
| 257 |
super(LDAPEntry, self).__init__() |
| 258 |
|
| 259 |
if isinstance(_conn, LDAPEntry): |
| 260 |
assert _dn is None |
| 261 |
_dn = _conn |
| 262 |
_conn = _conn._conn |
| 263 |
assert isinstance(_conn, LDAPClient) |
| 264 |
|
| 265 |
if isinstance(_dn, LDAPEntry): |
| 266 |
assert _obj is None |
| 267 |
_obj = _dn |
| 268 |
_dn = _dn._dn |
| 269 |
assert isinstance(_dn, DN) |
| 270 |
|
| 271 |
if _obj is None: |
| 272 |
_obj = {} |
| 273 |
|
| 274 |
self._conn = _conn |
| 275 |
self._dn = _dn |
| 276 |
self._names = CIDict() |
| 277 |
self._nice = {} |
| 278 |
self._raw = {} |
| 279 |
self._sync = {} |
| 280 |
self._not_list = set() |
| 281 |
self._orig_raw = {} |
| 282 |
self._raw_view = None |
| 283 |
self._single_value_view = None |
| 284 |
|
| 285 |
if isinstance(_obj, LDAPEntry): |
| 286 |
self._not_list = set(_obj._not_list) |
| 287 |
self._orig_raw = dict(_obj._orig_raw) |
| 288 |
if _obj.conn is _conn: |
| 289 |
self._names = CIDict(_obj._names) |
| 290 |
self._nice = dict(_obj._nice) |
| 291 |
self._raw = dict(_obj._raw) |
| 292 |
self._sync = dict(_obj._sync) |
| 293 |
else: |
| 294 |
self.raw.update(_obj.raw) |
| 295 |
|
| 296 |
_obj = {} |
| 297 |
|
| 298 |
self.update(_obj, **kwargs) |
| 299 |
|
| 300 |
@property |
| 301 |
def conn(self): |
| 302 |
return self._conn |
| 303 |
|
| 304 |
@property |
| 305 |
def dn(self): |
| 306 |
return self._dn |
| 307 |
|
| 308 |
@dn.setter |
| 309 |
def dn(self, value): |
| 310 |
assert isinstance(value, DN) |
| 311 |
self._dn = value |
| 312 |
|
| 313 |
@property |
| 314 |
def raw(self): |
| 315 |
if self._raw_view is None: |
| 316 |
self._raw_view = RawLDAPEntryView(self) |
| 317 |
return self._raw_view |
| 318 |
|
| 319 |
@property |
| 320 |
def single_value(self): |
| 321 |
if self._single_value_view is None: |
| 322 |
self._single_value_view = SingleValueLDAPEntryView(self) |
| 323 |
return self._single_value_view |
| 324 |
|
| 325 |
def __repr__(self): |
| 326 |
data = dict(self._raw) |
| 327 |
data.update((k, v) for k, v in self._nice.items() if v is not None) |
| 328 |
return '%s(%r, %r)' % (type(self).__name__, self._dn, data) |
| 329 |
|
| 330 |
def copy(self): |
| 331 |
return LDAPEntry(self) |
| 332 |
|
| 333 |
def _sync_attr(self, name): |
| 334 |
nice = self._nice[name] |
| 335 |
assert isinstance(nice, list) |
| 336 |
|
| 337 |
raw = self._raw[name] |
| 338 |
assert isinstance(raw, list) |
| 339 |
|
| 340 |
nice_sync, raw_sync = self._sync.setdefault(name, ([], [])) |
| 341 |
if nice == nice_sync and raw == raw_sync: |
| 342 |
return |
| 343 |
|
| 344 |
nice_adds = set(nice) - set(nice_sync) |
| 345 |
nice_dels = set(nice_sync) - set(nice) |
| 346 |
raw_adds = set(raw) - set(raw_sync) |
| 347 |
raw_dels = set(raw_sync) - set(raw) |
| 348 |
|
| 349 |
for value in nice_dels: |
| 350 |
value = self._conn.encode(value) |
| 351 |
if value in raw_adds: |
| 352 |
continue |
| 353 |
raw.remove(value) |
| 354 |
|
| 355 |
for value in raw_dels: |
| 356 |
try: |
| 357 |
value = self._conn.decode(value, name) |
| 358 |
except ValueError as e: |
| 359 |
raise ValueError("{error} in LDAP entry '{dn}'".format( |
| 360 |
error=e, dn=self._dn)) |
| 361 |
if value in nice_adds: |
| 362 |
continue |
| 363 |
nice.remove(value) |
| 364 |
|
| 365 |
for value in sorted(nice_adds, key=nice.index): |
| 366 |
value = self._conn.encode(value) |
| 367 |
if value in raw_dels: |
| 368 |
continue |
| 369 |
raw.append(value) |
| 370 |
|
| 371 |
for value in sorted(raw_adds, key=raw.index): |
| 372 |
try: |
| 373 |
value = self._conn.decode(value, name) |
| 374 |
except ValueError as e: |
| 375 |
raise ValueError("{error} in LDAP entry '{dn}'".format( |
| 376 |
error=e, dn=self._dn)) |
| 377 |
if value in nice_dels: |
| 378 |
continue |
| 379 |
nice.append(value) |
| 380 |
|
| 381 |
self._sync[name] = (deepcopy(nice), deepcopy(raw)) |
| 382 |
|
| 383 |
if len(nice) > 1: |
| 384 |
self._not_list.discard(name) |
| 385 |
|
| 386 |
def _attr_name(self, name): |
| 387 |
if not isinstance(name, str): |
| 388 |
raise TypeError( |
| 389 |
"attribute name must be unicode or str, got %s object %r" % ( |
| 390 |
name.__class__.__name__, name)) |
| 391 |
|
| 392 |
if isinstance(name, bytes): |
| 393 |
name = name.decode('utf-8') |
| 394 |
|
| 395 |
return name |
| 396 |
|
| 397 |
def _add_attr_name(self, name): |
| 398 |
if name in self._names: |
| 399 |
return self._names[name] |
| 400 |
|
| 401 |
if self._conn.schema is not None: |
| 402 |
if six.PY2: |
| 403 |
encoded_name = name.encode('utf-8') |
| 404 |
else: |
| 405 |
encoded_name = name |
| 406 |
attrtype = self._conn.schema.get_obj( |
| 407 |
ldap.schema.AttributeType, encoded_name) |
| 408 |
if attrtype is not None: |
| 409 |
for altname in attrtype.names: |
| 410 |
if six.PY2: |
| 411 |
altname = altname.decode('utf-8') |
| 412 |
self._names[altname] = name |
| 413 |
|
| 414 |
self._names[name] = name |
| 415 |
|
| 416 |
for oldname in list(self._orig_raw): |
| 417 |
if self._names.get(oldname) == name: |
| 418 |
self._orig_raw[name] = self._orig_raw.pop(oldname) |
| 419 |
break |
| 420 |
|
| 421 |
return name |
| 422 |
|
| 423 |
def _set_nice(self, name, value): |
| 424 |
name = self._attr_name(name) |
| 425 |
name = self._add_attr_name(name) |
| 426 |
|
| 427 |
if not isinstance(value, list): |
| 428 |
if value is None: |
| 429 |
value = [] |
| 430 |
else: |
| 431 |
value = [value] |
| 432 |
self._not_list.add(name) |
| 433 |
else: |
| 434 |
self._not_list.discard(name) |
| 435 |
|
| 436 |
if self._nice.get(name) is not value: |
| 437 |
self._nice[name] = value |
| 438 |
self._raw[name] = None |
| 439 |
self._sync.pop(name, None) |
| 440 |
|
| 441 |
if self._raw[name] is not None: |
| 442 |
self._sync_attr(name) |
| 443 |
|
| 444 |
def _set_raw(self, name, value): |
| 445 |
name = self._attr_name(name) |
| 446 |
|
| 447 |
if not isinstance(value, list): |
| 448 |
raise TypeError("%s value must be list, got %s object %r" % ( |
| 449 |
name, value.__class__.__name__, value)) |
| 450 |
for (i, item) in enumerate(value): |
| 451 |
if not isinstance(item, bytes): |
| 452 |
raise TypeError( |
| 453 |
"%s[%d] value must be bytes, got %s object %r" % ( |
| 454 |
name, i, item.__class__.__name__, item) |
| 455 |
) |
| 456 |
|
| 457 |
name = self._add_attr_name(name) |
| 458 |
|
| 459 |
if self._raw.get(name) is not value: |
| 460 |
self._raw[name] = value |
| 461 |
self._nice[name] = None |
| 462 |
self._sync.pop(name, None) |
| 463 |
|
| 464 |
if self._nice[name] is not None: |
| 465 |
self._sync_attr(name) |
| 466 |
|
| 467 |
def __setitem__(self, name, value): |
| 468 |
self._set_nice(name, value) |
| 469 |
|
| 470 |
def _get_attr_name(self, name): |
| 471 |
name = self._attr_name(name) |
| 472 |
name = self._names[name] |
| 473 |
return name |
| 474 |
|
| 475 |
def _get_nice(self, name): |
| 476 |
name = self._get_attr_name(name) |
| 477 |
|
| 478 |
value = self._nice[name] |
| 479 |
if value is None: |
| 480 |
value = self._nice[name] = [] |
| 481 |
assert isinstance(value, list) |
| 482 |
|
| 483 |
if self._raw[name] is not None: |
| 484 |
self._sync_attr(name) |
| 485 |
|
| 486 |
if name in self._not_list: |
| 487 |
assert len(value) <= 1 |
| 488 |
if value: |
| 489 |
value = value[0] |
| 490 |
else: |
| 491 |
value = None |
| 492 |
|
| 493 |
return value |
| 494 |
|
| 495 |
def _get_raw(self, name): |
| 496 |
name = self._get_attr_name(name) |
| 497 |
|
| 498 |
value = self._raw[name] |
| 499 |
if value is None: |
| 500 |
value = self._raw[name] = [] |
| 501 |
assert isinstance(value, list) |
| 502 |
|
| 503 |
if self._nice[name] is not None: |
| 504 |
self._sync_attr(name) |
| 505 |
|
| 506 |
return value |
| 507 |
|
| 508 |
def __getitem__(self, name): |
| 509 |
return self._get_nice(name) |
| 510 |
|
| 511 |
def __delitem__(self, name): |
| 512 |
name = self._get_attr_name(name) |
| 513 |
|
| 514 |
for (altname, keyname) in list(self._names.items()): |
| 515 |
if keyname == name: |
| 516 |
del self._names[altname] |
| 517 |
|
| 518 |
del self._nice[name] |
| 519 |
del self._raw[name] |
| 520 |
self._sync.pop(name, None) |
| 521 |
self._not_list.discard(name) |
| 522 |
|
| 523 |
def clear(self): |
| 524 |
self._names.clear() |
| 525 |
self._nice.clear() |
| 526 |
self._raw.clear() |
| 527 |
self._sync.clear() |
| 528 |
self._not_list.clear() |
| 529 |
|
| 530 |
def __len__(self): |
| 531 |
return len(self._nice) |
| 532 |
|
| 533 |
def __contains__(self, name): |
| 534 |
return name in self._names |
| 535 |
|
| 536 |
def has_key(self, name): |
| 537 |
return name in self |
| 538 |
|
| 539 |
def __eq__(self, other): |
| 540 |
if not isinstance(other, LDAPEntry): |
| 541 |
return NotImplemented |
| 542 |
return other is self |
| 543 |
|
| 544 |
def __ne__(self, other): |
| 545 |
if not isinstance(other, LDAPEntry): |
| 546 |
return NotImplemented |
| 547 |
return other is not self |
| 548 |
|
| 549 |
def reset_modlist(self, other=None): |
| 550 |
if other is None: |
| 551 |
other = self |
| 552 |
assert isinstance(other, LDAPEntry) |
| 553 |
self._orig_raw = deepcopy(dict(other.raw)) |
| 554 |
|
| 555 |
def generate_modlist(self): |
| 556 |
modlist = [] |
| 557 |
|
| 558 |
names = set(self) |
| 559 |
names.update(self._orig_raw) |
| 560 |
for name in names: |
| 561 |
new = self.raw.get(name, []) |
| 562 |
old = self._orig_raw.get(name, []) |
| 563 |
if old and not new: |
| 564 |
modlist.append((ldap.MOD_DELETE, name, None)) |
| 565 |
continue |
| 566 |
if not old and new: |
| 567 |
modlist.append((ldap.MOD_REPLACE, name, new)) |
| 568 |
continue |
| 569 |
|
| 570 |
# We used to convert to sets and use difference to calculate |
| 571 |
# the changes but this did not preserve order which is important |
| 572 |
# particularly for schema |
| 573 |
adds = [value for value in new if value not in old] |
| 574 |
dels = [value for value in old if value not in new] |
| 575 |
if adds and self.conn.get_attribute_single_value(name): |
| 576 |
if len(adds) > 1: |
| 577 |
raise errors.OnlyOneValueAllowed(attr=name) |
| 578 |
modlist.append((ldap.MOD_REPLACE, name, adds)) |
| 579 |
else: |
| 580 |
# dels before adds, in case the same value occurs in |
| 581 |
# both due to encoding differences |
| 582 |
# (https://pagure.io/freeipa/issue/7750) |
| 583 |
if dels: |
| 584 |
modlist.append((ldap.MOD_DELETE, name, dels)) |
| 585 |
if adds: |
| 586 |
modlist.append((ldap.MOD_ADD, name, adds)) |
| 587 |
|
| 588 |
# Usually the modlist order does not matter. |
| 589 |
# However, for schema updates, we want 'attributetypes' before |
| 590 |
# 'objectclasses'. |
| 591 |
# A simple sort will ensure this. |
| 592 |
modlist.sort(key=lambda m: m[1].lower() != 'attributetypes') |
| 593 |
|
| 594 |
return modlist |
| 595 |
|
| 596 |
def __iter__(self): |
| 597 |
return iter(self._nice) |
| 598 |
|
| 599 |
|
| 600 |
class LDAPEntryView(MutableMapping): |
| 601 |
__slots__ = ('_entry',) |
| 602 |
|
| 603 |
def __init__(self, entry): |
| 604 |
assert isinstance(entry, LDAPEntry) |
| 605 |
self._entry = entry |
| 606 |
|
| 607 |
def __delitem__(self, name): |
| 608 |
del self._entry[name] |
| 609 |
|
| 610 |
def clear(self): |
| 611 |
self._entry.clear() |
| 612 |
|
| 613 |
def __iter__(self): |
| 614 |
return iter(self._entry) |
| 615 |
|
| 616 |
def __len__(self): |
| 617 |
return len(self._entry) |
| 618 |
|
| 619 |
def __contains__(self, name): |
| 620 |
return name in self._entry |
| 621 |
|
| 622 |
def has_key(self, name): |
| 623 |
return name in self |
| 624 |
|
| 625 |
class RawLDAPEntryView(LDAPEntryView): |
| 626 |
def __getitem__(self, name): |
| 627 |
return self._entry._get_raw(name) |
| 628 |
|
| 629 |
def __setitem__(self, name, value): |
| 630 |
self._entry._set_raw(name, value) |
| 631 |
|
| 632 |
class SingleValueLDAPEntryView(LDAPEntryView): |
| 633 |
def __getitem__(self, name): |
| 634 |
value = self._entry[name] |
| 635 |
if not isinstance(value, list): |
| 636 |
# FIXME: remove when we enforce lists |
| 637 |
return value |
| 638 |
elif not value: |
| 639 |
return None |
| 640 |
elif len(value) == 1: |
| 641 |
return value[0] |
| 642 |
else: |
| 643 |
raise ValueError( |
| 644 |
'%s has %s values, one expected' % (name, len(value))) |
| 645 |
|
| 646 |
def __setitem__(self, name, value): |
| 647 |
if value is None: |
| 648 |
self._entry[name] = None |
| 649 |
else: |
| 650 |
self._entry[name] = [value] |
| 651 |
|
| 652 |
|
| 653 |
class LDAPClient: |
| 654 |
"""LDAP backend class |
| 655 |
|
| 656 |
This class abstracts a LDAP connection, providing methods that work with |
| 657 |
LADPEntries. |
| 658 |
|
| 659 |
The purpose of this class is to provide a boundary between IPA and |
| 660 |
python-ldap. In IPA we use IPA defined types because they are |
| 661 |
richer and are designed to meet our needs. We also require that we |
| 662 |
consistently use those types without exception. On the other hand |
| 663 |
python-ldap uses different types. The goal is to be able to have |
| 664 |
IPA code call python-ldap methods using the types native to |
| 665 |
IPA. This class accomplishes that goal by exposing python-ldap |
| 666 |
methods which take IPA types, convert them to python-ldap types, |
| 667 |
call python-ldap, and then convert the results returned by |
| 668 |
python-ldap into IPA types. |
| 669 |
""" |
| 670 |
|
| 671 |
# rules for generating filters from entries |
| 672 |
MATCH_ANY = '|' # (|(filter1)(filter2)) |
| 673 |
MATCH_ALL = '&' # (&(filter1)(filter2)) |
| 674 |
MATCH_NONE = '!' # (!(filter1)(filter2)) |
| 675 |
|
| 676 |
# search scope for find_entries() |
| 677 |
SCOPE_BASE = ldap.SCOPE_BASE |
| 678 |
SCOPE_ONELEVEL = ldap.SCOPE_ONELEVEL |
| 679 |
SCOPE_SUBTREE = ldap.SCOPE_SUBTREE |
| 680 |
|
| 681 |
_SYNTAX_MAPPING = { |
| 682 |
'1.3.6.1.4.1.1466.115.121.1.1' : bytes, # ACI item |
| 683 |
'1.3.6.1.4.1.1466.115.121.1.4' : bytes, # Audio |
| 684 |
'1.3.6.1.4.1.1466.115.121.1.5' : bytes, # Binary |
| 685 |
'1.3.6.1.4.1.1466.115.121.1.7' : bool, # Boolean |
| 686 |
'1.3.6.1.4.1.1466.115.121.1.8' : bytes, # Certificate |
| 687 |
'1.3.6.1.4.1.1466.115.121.1.9' : bytes, # Certificate List |
| 688 |
'1.3.6.1.4.1.1466.115.121.1.10' : bytes, # Certificate Pair |
| 689 |
'1.3.6.1.4.1.1466.115.121.1.12' : DN, # Distinguished Name |
| 690 |
'1.3.6.1.4.1.1466.115.121.1.23' : bytes, # Fax |
| 691 |
'1.3.6.1.4.1.1466.115.121.1.24' : datetime, # GeneralizedTime |
| 692 |
'1.3.6.1.4.1.1466.115.121.1.28' : bytes, # JPEG |
| 693 |
'1.3.6.1.4.1.1466.115.121.1.40' : bytes, # OctetString (same as Binary) |
| 694 |
'1.3.6.1.4.1.1466.115.121.1.49' : bytes, # Supported Algorithm |
| 695 |
'1.3.6.1.4.1.1466.115.121.1.51' : bytes, # Teletext Terminal Identifier |
| 696 |
'1.3.6.1.4.1.5322.21.2.5' : datetime, # krbLastAdminUnlock |
| 697 |
|
| 698 |
'2.16.840.1.113730.3.8.3.3' : DN, # enrolledBy |
| 699 |
'2.16.840.1.113730.3.8.3.18' : DN, # managedBy |
| 700 |
'2.16.840.1.113730.3.8.3.5' : DN, # memberUser |
| 701 |
'2.16.840.1.113730.3.8.3.7' : DN, # memberHost |
| 702 |
'2.16.840.1.113730.3.8.3.20' : DN, # memberService |
| 703 |
'2.16.840.1.113730.3.8.11.4' : DN, # ipaNTFallbackPrimaryGroup |
| 704 |
'2.16.840.1.113730.3.8.11.21' : DN, # ipaAllowToImpersonate |
| 705 |
'2.16.840.1.113730.3.8.11.22' : DN, # ipaAllowedTarget |
| 706 |
'2.16.840.1.113730.3.8.7.1' : DN, # memberAllowCmd |
| 707 |
'2.16.840.1.113730.3.8.7.2' : DN, # memberDenyCmd |
| 708 |
|
| 709 |
'2.16.840.1.113719.1.301.4.6.1' : datetime, # krbPrincipalExpiration |
| 710 |
'2.16.840.1.113719.1.301.4.14.1' : DN, # krbRealmReferences |
| 711 |
'2.16.840.1.113719.1.301.4.17.1' : DN, # krbKdcServers |
| 712 |
'2.16.840.1.113719.1.301.4.18.1' : DN, # krbPwdServers |
| 713 |
'2.16.840.1.113719.1.301.4.26.1' : DN, # krbPrincipalReferences |
| 714 |
'2.16.840.1.113719.1.301.4.29.1' : DN, # krbAdmServers |
| 715 |
'2.16.840.1.113719.1.301.4.36.1' : DN, # krbPwdPolicyReference |
| 716 |
'2.16.840.1.113719.1.301.4.37.1' : datetime, # krbPasswordExpiration |
| 717 |
'2.16.840.1.113719.1.301.4.40.1' : DN, # krbTicketPolicyReference |
| 718 |
'2.16.840.1.113719.1.301.4.41.1' : DN, # krbSubTrees |
| 719 |
'2.16.840.1.113719.1.301.4.45.1' : datetime, # krbLastPwdChange |
| 720 |
'2.16.840.1.113719.1.301.4.48.1' : datetime, # krbLastSuccessfulAuth |
| 721 |
'2.16.840.1.113719.1.301.4.49.1' : datetime, # krbLastFailedAuth |
| 722 |
'2.16.840.1.113719.1.301.4.52.1' : DN, # krbObjectReferences |
| 723 |
'2.16.840.1.113719.1.301.4.53.1' : DN, # krbPrincContainerRef |
| 724 |
'2.16.840.1.113730.3.8.16.1.3' : datetime, # ipatokenNotBefore |
| 725 |
'2.16.840.1.113730.3.8.16.1.4' : datetime, # ipatokenNotAfter |
| 726 |
} |
| 727 |
|
| 728 |
# In most cases we lookup the syntax from the schema returned by |
| 729 |
# the server. However, sometimes attributes may not be defined in |
| 730 |
# the schema (e.g. extensibleObject which permits undefined |
| 731 |
# attributes), or the schema was incorrectly defined (i.e. giving |
| 732 |
# an attribute the syntax DirectoryString when in fact it's really |
| 733 |
# a DN). This (hopefully sparse) table allows us to trap these |
| 734 |
# anomalies and force them to be the syntax we know to be in use. |
| 735 |
# |
| 736 |
# FWIW, many entries under cn=config are undefined :-( |
| 737 |
|
| 738 |
_SYNTAX_OVERRIDE = CIDict({ |
| 739 |
'managedtemplate': DN, |
| 740 |
'managedbase': DN, |
| 741 |
'memberindirect': DN, |
| 742 |
'memberofindirect':DN, |
| 743 |
'originscope': DN, |
| 744 |
'idnsname': DNSName, |
| 745 |
'idnssoamname': DNSName, |
| 746 |
'idnssoarname': DNSName, |
| 747 |
'dnszoneidnsname': DNSName, |
| 748 |
'krbcanonicalname': Principal, |
| 749 |
'krbprincipalname': Principal, |
| 750 |
'usercertificate': x509.IPACertificate, |
| 751 |
'usercertificate;binary': x509.IPACertificate, |
| 752 |
'cACertificate': x509.IPACertificate, |
| 753 |
'cACertificate;binary': x509.IPACertificate, |
| 754 |
'nsds5replicalastupdatestart': unicode, |
| 755 |
'nsds5replicalastupdateend': unicode, |
| 756 |
'nsds5replicalastinitstart': unicode, |
| 757 |
'nsds5replicalastinitend': unicode, |
| 758 |
}) |
| 759 |
_SINGLE_VALUE_OVERRIDE = CIDict({ |
| 760 |
'nsslapd-ssl-check-hostname': True, |
| 761 |
'nsslapd-lookthroughlimit': True, |
| 762 |
'nsslapd-idlistscanlimit': True, |
| 763 |
'nsslapd-anonlimitsdn': True, |
| 764 |
'nsslapd-minssf-exclude-rootdse': True, |
| 765 |
'nsslapd-enable-upgrade-hash': True, |
| 766 |
'nsslapd-db-locks': True, |
| 767 |
'nsslapd-logging-hr-timestamps-enabled': True, |
| 768 |
'nsslapd-ldapientrysearchbase': True, |
| 769 |
'nsslapd-ldapidnmappingbase': True, |
| 770 |
'nsslapd-sizelimit': True, |
| 771 |
}) |
| 772 |
|
| 773 |
time_limit = -1.0 # unlimited |
| 774 |
size_limit = 0 # unlimited |
| 775 |
|
| 776 |
def __init__(self, ldap_uri, start_tls=False, force_schema_updates=False, |
| 777 |
no_schema=False, decode_attrs=True, cacert=None, |
| 778 |
sasl_nocanon=True): |
| 779 |
"""Create LDAPClient object. |
| 780 |
|
| 781 |
:param ldap_uri: The LDAP URI to connect to |
| 782 |
:param start_tls: Use STARTTLS |
| 783 |
:param force_schema_updates: |
| 784 |
If true, this object will always request a new schema from the |
| 785 |
server. If false, a cached schema will be reused if it exists. |
| 786 |
|
| 787 |
Generally, it should be true if the API context is 'installer' or |
| 788 |
'updates', but it must be given explicitly since the API object |
| 789 |
is not always available |
| 790 |
:param no_schema: If true, schema is never requested from the server. |
| 791 |
:param decode_attrs: |
| 792 |
If true, attributes are decoded to Python types according to their |
| 793 |
syntax. |
| 794 |
""" |
| 795 |
if ldap_uri is not None: |
| 796 |
# special case for ldap2 server plugin |
| 797 |
self.ldap_uri = ldap_uri |
| 798 |
assert self.protocol in {'ldaps', 'ldapi', 'ldap'} |
| 799 |
self._start_tls = start_tls |
| 800 |
self._force_schema_updates = force_schema_updates |
| 801 |
self._no_schema = no_schema |
| 802 |
self._decode_attrs = decode_attrs |
| 803 |
self._cacert = cacert |
| 804 |
self._sasl_nocanon = sasl_nocanon |
| 805 |
|
| 806 |
self._has_schema = False |
| 807 |
self._schema = None |
| 808 |
|
| 809 |
if ldap_uri is not None: |
| 810 |
self._conn = self._connect() |
| 811 |
|
| 812 |
@classmethod |
| 813 |
def from_realm(cls, realm_name, **kwargs): |
| 814 |
"""Create a LDAPI connection to local 389-DS instance |
| 815 |
""" |
| 816 |
uri = realm_to_ldapi_uri(realm_name) |
| 817 |
return cls(uri, start_tls=False, cacert=None, **kwargs) |
| 818 |
|
| 819 |
@classmethod |
| 820 |
def from_hostname_secure(cls, hostname, cacert=paths.IPA_CA_CRT, |
| 821 |
start_tls=True, **kwargs): |
| 822 |
"""Create LDAP or LDAPS connection to a remote 389-DS instance |
| 823 |
|
| 824 |
This constructor is opinionated and doesn't let you shoot yourself in |
| 825 |
the foot. It always creates a secure connection. By default it |
| 826 |
returns a LDAP connection to port 389 and performs STARTTLS using the |
| 827 |
default CA cert. With start_tls=False, it creates a LDAPS connection |
| 828 |
to port 636 instead. |
| 829 |
|
| 830 |
Note: Microsoft AD does not support SASL encryption and integrity |
| 831 |
verification with a TLS connection. For AD, use a plain connection |
| 832 |
with GSSAPI and a MIN_SSF >= 56. SASL GSSAPI and SASL GSS SPNEGO |
| 833 |
ensure data integrity and confidentiality with SSF > 1. Also see |
| 834 |
https://msdn.microsoft.com/en-us/library/cc223500.aspx |
| 835 |
""" |
| 836 |
if start_tls: |
| 837 |
uri = 'ldap://%s' % format_netloc(hostname, 389) |
| 838 |
else: |
| 839 |
uri = 'ldaps://%s' % format_netloc(hostname, 636) |
| 840 |
return cls(uri, start_tls=start_tls, cacert=cacert, **kwargs) |
| 841 |
|
| 842 |
@classmethod |
| 843 |
def from_hostname_plain(cls, hostname, **kwargs): |
| 844 |
"""Create a plain LDAP connection with TLS/SSL |
| 845 |
|
| 846 |
Note: A plain TLS connection should only be used in combination with |
| 847 |
GSSAPI bind. |
| 848 |
""" |
| 849 |
assert 'start_tls' not in kwargs |
| 850 |
assert 'cacert' not in kwargs |
| 851 |
uri = 'ldap://%s' % format_netloc(hostname, 389) |
| 852 |
return cls(uri, **kwargs) |
| 853 |
|
| 854 |
def __str__(self): |
| 855 |
return self.ldap_uri |
| 856 |
|
| 857 |
def modify_s(self, dn, modlist): |
| 858 |
# FIXME: for backwards compatibility only |
| 859 |
assert isinstance(dn, DN) |
| 860 |
dn = str(dn) |
| 861 |
modlist = [(a, b, self.encode(c)) for a, b, c in modlist] |
| 862 |
return self.conn.modify_s(dn, modlist) |
| 863 |
|
| 864 |
@property |
| 865 |
def conn(self): |
| 866 |
return self._conn |
| 867 |
|
| 868 |
@property |
| 869 |
def protocol(self): |
| 870 |
if self.ldap_uri: |
| 871 |
return self.ldap_uri.split('://', 1)[0] |
| 872 |
else: |
| 873 |
return None |
| 874 |
|
| 875 |
def _get_schema(self): |
| 876 |
if self._no_schema: |
| 877 |
return None |
| 878 |
|
| 879 |
if not self._has_schema: |
| 880 |
try: |
| 881 |
schema = schema_cache.get_schema( |
| 882 |
self.ldap_uri, self.conn, |
| 883 |
force_update=self._force_schema_updates) |
| 884 |
except (errors.ExecutionError, IndexError): |
| 885 |
schema = None |
| 886 |
|
| 887 |
# bypass ldap2's locking |
| 888 |
object.__setattr__(self, '_schema', schema) |
| 889 |
object.__setattr__(self, '_has_schema', True) |
| 890 |
|
| 891 |
return self._schema |
| 892 |
|
| 893 |
def _flush_schema(self): |
| 894 |
''' |
| 895 |
Force this instance to forget it's cached schema and reacquire |
| 896 |
it from the schema cache. |
| 897 |
''' |
| 898 |
|
| 899 |
# Currently this is called during bind operations to assure |
| 900 |
# we're working with valid schema for a specific |
| 901 |
# connection. This causes self._get_schema() to query the |
| 902 |
# schema cache for the server's schema passing along a flag |
| 903 |
# indicating if we're in a context that requires freshly |
| 904 |
# loading the schema vs. returning the last cached version of |
| 905 |
# the schema. If we're in a mode that permits use of |
| 906 |
# previously cached schema the flush and reacquire is a very |
| 907 |
# low cost operation. |
| 908 |
# |
| 909 |
# The schema is reacquired whenever this object is |
| 910 |
# instantiated or when binding occurs. The schema is not |
| 911 |
# reacquired for operations during a bound connection, it is |
| 912 |
# presumed schema cannot change during this interval. This |
| 913 |
# provides for maximum efficiency in contexts which do need |
| 914 |
# schema refreshing by only peforming the refresh inbetween |
| 915 |
# logical operations that have the potential to cause a schema |
| 916 |
# change. |
| 917 |
|
| 918 |
# bypass ldap2's locking |
| 919 |
object.__setattr__(self, '_has_schema', False) |
| 920 |
object.__setattr__(self, '_schema', None) |
| 921 |
|
| 922 |
def get_attribute_type(self, name_or_oid): |
| 923 |
if not self._decode_attrs: |
| 924 |
return bytes |
| 925 |
|
| 926 |
if six.PY2: |
| 927 |
if isinstance(name_or_oid, unicode): |
| 928 |
name_or_oid = name_or_oid.encode('utf-8') |
| 929 |
|
| 930 |
# Is this a special case attribute? |
| 931 |
if name_or_oid in self._SYNTAX_OVERRIDE: |
| 932 |
return self._SYNTAX_OVERRIDE[name_or_oid] |
| 933 |
|
| 934 |
schema = self._get_schema() |
| 935 |
if schema is not None: |
| 936 |
# Try to lookup the syntax in the schema returned by the server |
| 937 |
obj = schema.get_obj(ldap.schema.AttributeType, name_or_oid) |
| 938 |
if obj is not None and obj.syntax in self._SYNTAX_MAPPING: |
| 939 |
return self._SYNTAX_MAPPING[obj.syntax] |
| 940 |
|
| 941 |
return unicode |
| 942 |
|
| 943 |
def has_dn_syntax(self, name_or_oid): |
| 944 |
""" |
| 945 |
Check the schema to see if the attribute uses DN syntax. |
| 946 |
|
| 947 |
Returns True/False |
| 948 |
""" |
| 949 |
return self.get_attribute_type(name_or_oid) is DN |
| 950 |
|
| 951 |
def get_attribute_single_value(self, name_or_oid): |
| 952 |
""" |
| 953 |
Check the schema to see if the attribute is single-valued. |
| 954 |
|
| 955 |
If the attribute is in the schema then returns True/False |
| 956 |
|
| 957 |
If there is a problem loading the schema or the attribute is |
| 958 |
not in the schema return None |
| 959 |
""" |
| 960 |
if six.PY2 and isinstance(name_or_oid, unicode): |
| 961 |
name_or_oid = name_or_oid.encode('utf-8') |
| 962 |
|
| 963 |
if name_or_oid in self._SINGLE_VALUE_OVERRIDE: |
| 964 |
return self._SINGLE_VALUE_OVERRIDE[name_or_oid] |
| 965 |
|
| 966 |
schema = self._get_schema() |
| 967 |
if schema is not None: |
| 968 |
obj = schema.get_obj(ldap.schema.AttributeType, name_or_oid) |
| 969 |
if obj is not None: |
| 970 |
return obj.single_value |
| 971 |
|
| 972 |
return None |
| 973 |
|
| 974 |
def encode(self, val): |
| 975 |
""" |
| 976 |
Encode attribute value to LDAP representation (str/bytes). |
| 977 |
""" |
| 978 |
# Booleans are both an instance of bool and int, therefore |
| 979 |
# test for bool before int otherwise the int clause will be |
| 980 |
# entered for a boolean value instead of the boolean clause. |
| 981 |
if isinstance(val, bool): |
| 982 |
if val: |
| 983 |
return b'TRUE' |
| 984 |
else: |
| 985 |
return b'FALSE' |
| 986 |
elif isinstance(val, (unicode, int, Decimal, DN, Principal)): |
| 987 |
return str(val).encode('utf-8') |
| 988 |
elif isinstance(val, DNSName): |
| 989 |
return val.to_text().encode('ascii') |
| 990 |
elif isinstance(val, bytes): |
| 991 |
return val |
| 992 |
elif isinstance(val, list): |
| 993 |
return [self.encode(m) for m in val] |
| 994 |
elif isinstance(val, tuple): |
| 995 |
return tuple(self.encode(m) for m in val) |
| 996 |
elif isinstance(val, dict): |
| 997 |
# key in dict must be str not bytes |
| 998 |
dct = dict((k, self.encode(v)) for k, v in val.items()) |
| 999 |
return dct |
| 1000 |
elif isinstance(val, datetime): |
| 1001 |
return val.strftime(LDAP_GENERALIZED_TIME_FORMAT).encode('utf-8') |
| 1002 |
elif isinstance(val, x509.IPACertificate): |
| 1003 |
return val.public_bytes(x509.Encoding.DER) |
| 1004 |
elif val is None: |
| 1005 |
return None |
| 1006 |
else: |
| 1007 |
raise TypeError("attempt to pass unsupported type to ldap, value=%s type=%s" %(val, type(val))) |
| 1008 |
|
| 1009 |
def decode(self, val, attr): |
| 1010 |
""" |
| 1011 |
Decode attribute value from LDAP representation (str/bytes). |
| 1012 |
""" |
| 1013 |
if isinstance(val, bytes): |
| 1014 |
target_type = self.get_attribute_type(attr) |
| 1015 |
try: |
| 1016 |
if target_type is bytes: |
| 1017 |
return val |
| 1018 |
elif target_type is unicode: |
| 1019 |
return val.decode('utf-8') |
| 1020 |
elif target_type is bool: |
| 1021 |
return val.decode('utf-8') == 'TRUE' |
| 1022 |
elif target_type is datetime: |
| 1023 |
return datetime.strptime( |
| 1024 |
val.decode('utf-8'), LDAP_GENERALIZED_TIME_FORMAT) |
| 1025 |
elif target_type is DNSName: |
| 1026 |
return DNSName.from_text(val.decode('utf-8')) |
| 1027 |
elif target_type in (DN, Principal): |
| 1028 |
return target_type(val.decode('utf-8')) |
| 1029 |
elif target_type is x509.IPACertificate: |
| 1030 |
return x509.load_der_x509_certificate(val) |
| 1031 |
else: |
| 1032 |
return target_type(val) |
| 1033 |
except Exception: |
| 1034 |
msg = 'unable to convert the attribute %r value %r to type %s' % (attr, val, target_type) |
| 1035 |
logger.error('%s', msg) |
| 1036 |
raise ValueError(msg) |
| 1037 |
elif isinstance(val, list): |
| 1038 |
return [self.decode(m, attr) for m in val] |
| 1039 |
elif isinstance(val, tuple): |
| 1040 |
return tuple(self.decode(m, attr) for m in val) |
| 1041 |
elif isinstance(val, dict): |
| 1042 |
dct = { |
| 1043 |
k.decode('utf-8'): self.decode(v, k) for k, v in val.items() |
| 1044 |
} |
| 1045 |
return dct |
| 1046 |
elif val is None: |
| 1047 |
return None |
| 1048 |
else: |
| 1049 |
raise TypeError("attempt to pass unsupported type from ldap, value=%s type=%s" %(val, type(val))) |
| 1050 |
|
| 1051 |
def _convert_result(self, result): |
| 1052 |
''' |
| 1053 |
result is a python-ldap result tuple of the form (dn, attrs), |
| 1054 |
where dn is a string containing the dn (distinguished name) of |
| 1055 |
the entry, and attrs is a dictionary containing the attributes |
| 1056 |
associated with the entry. The keys of attrs are strings, and |
| 1057 |
the associated values are lists of strings. |
| 1058 |
|
| 1059 |
We convert the tuple to an LDAPEntry object. |
| 1060 |
''' |
| 1061 |
|
| 1062 |
ipa_result = [] |
| 1063 |
for dn_tuple in result: |
| 1064 |
original_dn = dn_tuple[0] |
| 1065 |
original_attrs = dn_tuple[1] |
| 1066 |
|
| 1067 |
# original_dn is None if referral instead of an entry was |
| 1068 |
# returned from the LDAP server, we need to skip this item |
| 1069 |
if original_dn is None: |
| 1070 |
log_msg = 'Referral entry ignored: {ref}'\ |
| 1071 |
.format(ref=str(original_attrs)) |
| 1072 |
logger.debug('%s', log_msg) |
| 1073 |
|
| 1074 |
continue |
| 1075 |
|
| 1076 |
ipa_entry = LDAPEntry(self, DN(original_dn)) |
| 1077 |
|
| 1078 |
for attr, original_values in original_attrs.items(): |
| 1079 |
ipa_entry.raw[attr] = original_values |
| 1080 |
ipa_entry.reset_modlist() |
| 1081 |
|
| 1082 |
ipa_result.append(ipa_entry) |
| 1083 |
|
| 1084 |
if _debug_log_ldap: |
| 1085 |
logger.debug('ldap.result: %s', ipa_result) |
| 1086 |
return ipa_result |
| 1087 |
|
| 1088 |
@contextlib.contextmanager |
| 1089 |
def error_handler(self, arg_desc=None): |
| 1090 |
"""Context manager that handles LDAPErrors |
| 1091 |
""" |
| 1092 |
desc = None |
| 1093 |
try: |
| 1094 |
try: |
| 1095 |
yield |
| 1096 |
except ldap.TIMEOUT: |
| 1097 |
raise errors.DatabaseTimeout() |
| 1098 |
except ldap.LDAPError as e: |
| 1099 |
desc = e.args[0]['desc'].strip() |
| 1100 |
info = e.args[0].get('info', '').strip() |
| 1101 |
if arg_desc is not None: |
| 1102 |
info = "%s arguments: %s" % (info, arg_desc) |
| 1103 |
raise |
| 1104 |
except ldap.NO_SUCH_OBJECT: |
| 1105 |
raise errors.NotFound(reason=arg_desc or 'no such entry') |
| 1106 |
except ldap.ALREADY_EXISTS: |
| 1107 |
# entry already exists |
| 1108 |
raise errors.DuplicateEntry() |
| 1109 |
except ldap.TYPE_OR_VALUE_EXISTS: |
| 1110 |
# attribute type or attribute value already exists, usually only |
| 1111 |
# occurs, when two machines try to write at the same time. |
| 1112 |
raise errors.DuplicateEntry(message=desc) |
| 1113 |
except ldap.CONSTRAINT_VIOLATION: |
| 1114 |
# This error gets thrown by the uniqueness plugin |
| 1115 |
_msg = 'Another entry with the same attribute value already exists' |
| 1116 |
if info.startswith(_msg): |
| 1117 |
raise errors.DuplicateEntry() |
| 1118 |
else: |
| 1119 |
raise errors.DatabaseError(desc=desc, info=info) |
| 1120 |
except ldap.INSUFFICIENT_ACCESS: |
| 1121 |
raise errors.ACIError(info=info) |
| 1122 |
except ldap.INVALID_CREDENTIALS: |
| 1123 |
raise errors.ACIError(info="%s %s" % (info, desc)) |
| 1124 |
except ldap.INAPPROPRIATE_AUTH: |
| 1125 |
raise errors.ACIError(info="%s: %s" % (desc, info)) |
| 1126 |
except ldap.NO_SUCH_ATTRIBUTE: |
| 1127 |
# this is raised when a 'delete' attribute isn't found. |
| 1128 |
# it indicates the previous attribute was removed by another |
| 1129 |
# update, making the oldentry stale. |
| 1130 |
raise errors.MidairCollision() |
| 1131 |
except ldap.INVALID_SYNTAX: |
| 1132 |
raise errors.InvalidSyntax(attr=info) |
| 1133 |
except ldap.OBJECT_CLASS_VIOLATION: |
| 1134 |
raise errors.ObjectclassViolation(info=info) |
| 1135 |
except ldap.ADMINLIMIT_EXCEEDED: |
| 1136 |
raise errors.AdminLimitExceeded() |
| 1137 |
except ldap.SIZELIMIT_EXCEEDED: |
| 1138 |
raise errors.SizeLimitExceeded() |
| 1139 |
except ldap.TIMELIMIT_EXCEEDED: |
| 1140 |
raise errors.TimeLimitExceeded() |
| 1141 |
except ldap.NOT_ALLOWED_ON_RDN: |
| 1142 |
raise errors.NotAllowedOnRDN(attr=info) |
| 1143 |
except ldap.FILTER_ERROR: |
| 1144 |
raise errors.BadSearchFilter(info=info) |
| 1145 |
except ldap.NOT_ALLOWED_ON_NONLEAF: |
| 1146 |
raise errors.NotAllowedOnNonLeaf() |
| 1147 |
except ldap.SERVER_DOWN: |
| 1148 |
raise errors.NetworkError(uri=self.ldap_uri, |
| 1149 |
error=info) |
| 1150 |
except ldap.LOCAL_ERROR: |
| 1151 |
raise errors.ACIError(info=info) |
| 1152 |
except ldap.SUCCESS: |
| 1153 |
pass |
| 1154 |
except ldap.CONNECT_ERROR: |
| 1155 |
raise errors.DatabaseError(desc=desc, info=info) |
| 1156 |
except ldap.UNWILLING_TO_PERFORM: |
| 1157 |
raise errors.DatabaseError(desc=desc, info=info) |
| 1158 |
except ldap.AUTH_UNKNOWN: |
| 1159 |
raise errors.ACIError(info='%s (%s)' % (info,desc)) |
| 1160 |
except ldap.LDAPError as e: |
| 1161 |
if 'NOT_ALLOWED_TO_DELEGATE' in info: |
| 1162 |
raise errors.ACIError( |
| 1163 |
info="KDC returned NOT_ALLOWED_TO_DELEGATE") |
| 1164 |
logger.debug( |
| 1165 |
'Unhandled LDAPError: %s: %s', type(e).__name__, str(e)) |
| 1166 |
raise errors.DatabaseError(desc=desc, info=info) |
| 1167 |
|
| 1168 |
@staticmethod |
| 1169 |
def handle_truncated_result(truncated): |
| 1170 |
if not truncated: |
| 1171 |
return |
| 1172 |
|
| 1173 |
if truncated is TRUNCATED_ADMIN_LIMIT: |
| 1174 |
raise errors.AdminLimitExceeded() |
| 1175 |
elif truncated is TRUNCATED_SIZE_LIMIT: |
| 1176 |
raise errors.SizeLimitExceeded() |
| 1177 |
elif truncated is TRUNCATED_TIME_LIMIT: |
| 1178 |
raise errors.TimeLimitExceeded() |
| 1179 |
else: |
| 1180 |
raise errors.LimitsExceeded() |
| 1181 |
|
| 1182 |
@property |
| 1183 |
def schema(self): |
| 1184 |
"""schema associated with this LDAP server""" |
| 1185 |
return self._get_schema() |
| 1186 |
|
| 1187 |
def get_allowed_attributes(self, objectclasses, raise_on_unknown=False, |
| 1188 |
attributes="all"): |
| 1189 |
if self.schema is None: |
| 1190 |
return None |
| 1191 |
allowed_attributes = [] |
| 1192 |
for oc in objectclasses: |
| 1193 |
obj = self.schema.get_obj(ldap.schema.ObjectClass, oc) |
| 1194 |
if obj is not None: |
| 1195 |
if attributes == "must": |
| 1196 |
# Only return required(must) attrs |
| 1197 |
allowed_attributes += obj.must |
| 1198 |
elif attributes == "may": |
| 1199 |
# Only return allowed(may) attrs |
| 1200 |
allowed_attributes += obj.may |
| 1201 |
else: |
| 1202 |
# Return both allowed & required attrs |
| 1203 |
allowed_attributes += obj.must + obj.may |
| 1204 |
elif raise_on_unknown: |
| 1205 |
raise errors.NotFound( |
| 1206 |
reason=_('objectclass %s not found') % oc) |
| 1207 |
return [unicode(a).lower() for a in list(set(allowed_attributes))] |
| 1208 |
|
| 1209 |
def __enter__(self): |
| 1210 |
return self |
| 1211 |
|
| 1212 |
def __exit__(self, exc_type, exc_value, traceback): |
| 1213 |
self.close() |
| 1214 |
|
| 1215 |
def close(self): |
| 1216 |
""" |
| 1217 |
Close the connection. |
| 1218 |
""" |
| 1219 |
self._conn = None |
| 1220 |
|
| 1221 |
def _connect(self): |
| 1222 |
with self.error_handler(): |
| 1223 |
conn = ldap_initialize(self.ldap_uri, cacertfile=self._cacert) |
| 1224 |
# SASL_NOCANON is set to ON in Fedora's default ldap.conf and |
| 1225 |
# in the ldap_initialize() function. |
| 1226 |
if not self._sasl_nocanon: |
| 1227 |
conn.set_option(ldap.OPT_X_SASL_NOCANON, ldap.OPT_OFF) |
| 1228 |
|
| 1229 |
if self._start_tls and self.protocol == 'ldap': |
| 1230 |
# STARTTLS applies only to ldap:// connections |
| 1231 |
conn.start_tls_s() |
| 1232 |
|
| 1233 |
return conn |
| 1234 |
|
| 1235 |
def simple_bind(self, bind_dn, bind_password, server_controls=None, |
| 1236 |
client_controls=None, insecure_bind=False): |
| 1237 |
""" |
| 1238 |
Perform simple bind operation. |
| 1239 |
""" |
| 1240 |
if (self.protocol == 'ldap' and not self._start_tls and |
| 1241 |
bind_password and not insecure_bind): |
| 1242 |
# non-empty bind must use a secure connection unless |
| 1243 |
# insecure bind is explicitly enabled |
| 1244 |
raise ValueError('simple_bind over insecure LDAP connection') |
| 1245 |
with self.error_handler(): |
| 1246 |
self._flush_schema() |
| 1247 |
assert isinstance(bind_dn, DN) |
| 1248 |
bind_dn = str(bind_dn) |
| 1249 |
bind_password = self.encode(bind_password) |
| 1250 |
self.conn.simple_bind_s( |
| 1251 |
bind_dn, bind_password, server_controls, client_controls) |
| 1252 |
|
| 1253 |
def external_bind(self, server_controls=None, client_controls=None): |
| 1254 |
""" |
| 1255 |
Perform SASL bind operation using the SASL EXTERNAL mechanism. |
| 1256 |
""" |
| 1257 |
user_name = pwd.getpwuid(os.geteuid()).pw_name |
| 1258 |
with self.error_handler(): |
| 1259 |
auth_tokens = ldap.sasl.external(user_name) |
| 1260 |
self._flush_schema() |
| 1261 |
self.conn.sasl_interactive_bind_s( |
| 1262 |
'', auth_tokens, server_controls, client_controls) |
| 1263 |
|
| 1264 |
def gssapi_bind(self, server_controls=None, client_controls=None): |
| 1265 |
""" |
| 1266 |
Perform SASL bind operation using the SASL GSSAPI mechanism. |
| 1267 |
""" |
| 1268 |
with self.error_handler(): |
| 1269 |
if self.protocol == 'ldapi': |
| 1270 |
auth_tokens = SASL_GSS_SPNEGO |
| 1271 |
else: |
| 1272 |
auth_tokens = SASL_GSSAPI |
| 1273 |
self._flush_schema() |
| 1274 |
self.conn.sasl_interactive_bind_s( |
| 1275 |
'', auth_tokens, server_controls, client_controls) |
| 1276 |
|
| 1277 |
def unbind(self): |
| 1278 |
""" |
| 1279 |
Perform unbind operation. |
| 1280 |
""" |
| 1281 |
with self.error_handler(): |
| 1282 |
self._flush_schema() |
| 1283 |
self.conn.unbind_s() |
| 1284 |
|
| 1285 |
def make_dn_from_attr(self, attr, value, parent_dn=None): |
| 1286 |
""" |
| 1287 |
Make distinguished name from attribute. |
| 1288 |
|
| 1289 |
Keyword arguments: |
| 1290 |
parent_dn -- DN of the parent entry (default '') |
| 1291 |
""" |
| 1292 |
if parent_dn is None: |
| 1293 |
parent_dn = DN() |
| 1294 |
|
| 1295 |
if isinstance(value, (list, tuple)): |
| 1296 |
value = value[0] |
| 1297 |
|
| 1298 |
return DN((attr, value), parent_dn) |
| 1299 |
|
| 1300 |
def make_dn(self, entry_attrs, primary_key='cn', parent_dn=None): |
| 1301 |
""" |
| 1302 |
Make distinguished name from entry attributes. |
| 1303 |
|
| 1304 |
Keyword arguments: |
| 1305 |
primary_key -- attribute from which to make RDN (default 'cn') |
| 1306 |
parent_dn -- DN of the parent entry (default '') |
| 1307 |
""" |
| 1308 |
|
| 1309 |
assert primary_key in entry_attrs |
| 1310 |
assert isinstance(parent_dn, DN) |
| 1311 |
|
| 1312 |
return DN((primary_key, entry_attrs[primary_key]), parent_dn) |
| 1313 |
|
| 1314 |
def make_entry(self, _dn=None, _obj=None, **kwargs): |
| 1315 |
return LDAPEntry(self, _dn, _obj, **kwargs) |
| 1316 |
|
| 1317 |
# generating filters for find_entry |
| 1318 |
# some examples: |
| 1319 |
# f1 = ldap2.make_filter_from_attr(u'firstName', u'Pavel') |
| 1320 |
# f2 = ldap2.make_filter_from_attr(u'lastName', u'Zuna') |
| 1321 |
# f = ldap2.combine_filters([f1, f2], ldap2.MATCH_ALL) |
| 1322 |
# # f should be (&(firstName=Pavel)(lastName=Zuna)) |
| 1323 |
# # it should be equivalent to: |
| 1324 |
# entry_attrs = {u'firstName': u'Pavel', u'lastName': u'Zuna'} |
| 1325 |
# f = ldap2.make_filter(entry_attrs, rules=ldap2.MATCH_ALL) |
| 1326 |
|
| 1327 |
@classmethod |
| 1328 |
def combine_filters(cls, filters, rules='|'): |
| 1329 |
""" |
| 1330 |
Combine filters into one for ldap2.find_entries. |
| 1331 |
|
| 1332 |
Keyword arguments: |
| 1333 |
rules -- see ldap2.make_filter |
| 1334 |
""" |
| 1335 |
|
| 1336 |
assert isinstance(filters, (list, tuple)) |
| 1337 |
|
| 1338 |
filters = [fx for fx in filters if fx] |
| 1339 |
if filters and rules == cls.MATCH_NONE: # unary operator |
| 1340 |
return '(%s%s)' % (cls.MATCH_NONE, |
| 1341 |
cls.combine_filters(filters, cls.MATCH_ANY)) |
| 1342 |
|
| 1343 |
if len(filters) > 1: |
| 1344 |
flt = '(%s' % rules |
| 1345 |
else: |
| 1346 |
flt = '' |
| 1347 |
for f in filters: |
| 1348 |
if not f.startswith('('): |
| 1349 |
f = '(%s)' % f |
| 1350 |
flt = '%s%s' % (flt, f) |
| 1351 |
if len(filters) > 1: |
| 1352 |
flt = '%s)' % flt |
| 1353 |
return flt |
| 1354 |
|
| 1355 |
@classmethod |
| 1356 |
def make_filter_from_attr( |
| 1357 |
cls, attr, value, rules='|', exact=True, |
| 1358 |
leading_wildcard=True, trailing_wildcard=True): |
| 1359 |
""" |
| 1360 |
Make filter for ldap2.find_entries from attribute. |
| 1361 |
|
| 1362 |
Keyword arguments: |
| 1363 |
rules -- see ldap2.make_filter |
| 1364 |
exact -- boolean, True - make filter as (attr=value) |
| 1365 |
False - make filter as (attr=*value*) |
| 1366 |
leading_wildcard -- boolean: |
| 1367 |
True - allow heading filter wildcard when exact=False |
| 1368 |
False - forbid heading filter wildcard when exact=False |
| 1369 |
trailing_wildcard -- boolean: |
| 1370 |
True - allow trailing filter wildcard when exact=False |
| 1371 |
False - forbid trailing filter wildcard when exact=False |
| 1372 |
""" |
| 1373 |
if isinstance(value, (list, tuple)): |
| 1374 |
flts = [ |
| 1375 |
cls.make_filter_from_attr( |
| 1376 |
attr, v, exact=exact, |
| 1377 |
leading_wildcard=leading_wildcard, |
| 1378 |
trailing_wildcard=trailing_wildcard) |
| 1379 |
for v in value |
| 1380 |
] |
| 1381 |
return cls.combine_filters(flts, rules) |
| 1382 |
elif value is not None: |
| 1383 |
if isinstance(value, x509.IPACertificate): |
| 1384 |
value = value.public_bytes(serialization.Encoding.DER) |
| 1385 |
if isinstance(value, bytes): |
| 1386 |
value = binascii.hexlify(value).decode('ascii') |
| 1387 |
# value[-2:0] is empty string for the initial '\\' |
| 1388 |
value = u'\\'.join( |
| 1389 |
value[i:i+2] for i in six.moves.range(-2, len(value), 2)) |
| 1390 |
elif isinstance(value, datetime): |
| 1391 |
value = value.strftime( |
| 1392 |
LDAP_GENERALIZED_TIME_FORMAT) |
| 1393 |
value = ldap.filter.escape_filter_chars(value) |
| 1394 |
else: |
| 1395 |
value = str(value) |
| 1396 |
value = ldap.filter.escape_filter_chars(value) |
| 1397 |
|
| 1398 |
if not exact: |
| 1399 |
template = '%s' |
| 1400 |
if leading_wildcard: |
| 1401 |
template = '*' + template |
| 1402 |
if trailing_wildcard: |
| 1403 |
template = template + '*' |
| 1404 |
value = template % value |
| 1405 |
if rules == cls.MATCH_NONE: |
| 1406 |
return '(!(%s=%s))' % (attr, value) |
| 1407 |
return '(%s=%s)' % (attr, value) |
| 1408 |
return '' |
| 1409 |
|
| 1410 |
@classmethod |
| 1411 |
def make_filter( |
| 1412 |
cls, entry_attrs, attrs_list=None, rules='|', exact=True, |
| 1413 |
leading_wildcard=True, trailing_wildcard=True): |
| 1414 |
""" |
| 1415 |
Make filter for ldap2.find_entries from entry attributes. |
| 1416 |
|
| 1417 |
Keyword arguments: |
| 1418 |
attrs_list -- list of attributes to use, all if None (default None) |
| 1419 |
rules -- specifies how to determine a match (default ldap2.MATCH_ANY) |
| 1420 |
exact -- boolean, True - make filter as (attr=value) |
| 1421 |
False - make filter as (attr=*value*) |
| 1422 |
leading_wildcard -- boolean: |
| 1423 |
True - allow heading filter wildcard when exact=False |
| 1424 |
False - forbid heading filter wildcard when exact=False |
| 1425 |
trailing_wildcard -- boolean: |
| 1426 |
True - allow trailing filter wildcard when exact=False |
| 1427 |
False - forbid trailing filter wildcard when exact=False |
| 1428 |
|
| 1429 |
rules can be one of the following: |
| 1430 |
ldap2.MATCH_NONE - match entries that do not match any attribute |
| 1431 |
ldap2.MATCH_ALL - match entries that match all attributes |
| 1432 |
ldap2.MATCH_ANY - match entries that match any of attribute |
| 1433 |
""" |
| 1434 |
if rules == cls.MATCH_NONE: |
| 1435 |
make_filter_rules = cls.MATCH_ANY |
| 1436 |
else: |
| 1437 |
make_filter_rules = rules |
| 1438 |
flts = [] |
| 1439 |
if attrs_list is None: |
| 1440 |
for (k, v) in entry_attrs.items(): |
| 1441 |
flts.append( |
| 1442 |
cls.make_filter_from_attr( |
| 1443 |
k, v, make_filter_rules, exact, |
| 1444 |
leading_wildcard, trailing_wildcard) |
| 1445 |
) |
| 1446 |
else: |
| 1447 |
for a in attrs_list: |
| 1448 |
value = entry_attrs.get(a, None) |
| 1449 |
if value is not None: |
| 1450 |
flts.append( |
| 1451 |
cls.make_filter_from_attr( |
| 1452 |
a, value, make_filter_rules, exact, |
| 1453 |
leading_wildcard, trailing_wildcard) |
| 1454 |
) |
| 1455 |
return cls.combine_filters(flts, rules) |
| 1456 |
|
| 1457 |
def get_entries(self, base_dn, scope=ldap.SCOPE_SUBTREE, filter=None, |
| 1458 |
attrs_list=None, get_effective_rights=False, **kwargs): |
| 1459 |
"""Return a list of matching entries. |
| 1460 |
|
| 1461 |
:raises: errors.LimitsExceeded if the list is truncated by the server |
| 1462 |
:raises: errors.NotFound if result set is empty |
| 1463 |
or base_dn doesn't exist |
| 1464 |
|
| 1465 |
:param base_dn: dn of the entry at which to start the search |
| 1466 |
:param scope: search scope, see LDAP docs (default ldap2.SCOPE_SUBTREE) |
| 1467 |
:param filter: LDAP filter to apply |
| 1468 |
:param attrs_list: ist of attributes to return, all if None (default) |
| 1469 |
:param get_effective_rights: use GetEffectiveRights control |
| 1470 |
:param kwargs: additional keyword arguments. See find_entries method |
| 1471 |
for their description. |
| 1472 |
""" |
| 1473 |
entries, truncated = self.find_entries( |
| 1474 |
base_dn=base_dn, scope=scope, filter=filter, attrs_list=attrs_list, |
| 1475 |
get_effective_rights=get_effective_rights, |
| 1476 |
**kwargs) |
| 1477 |
try: |
| 1478 |
self.handle_truncated_result(truncated) |
| 1479 |
except errors.LimitsExceeded as e: |
| 1480 |
logger.error( |
| 1481 |
"%s while getting entries (base DN: %s, filter: %s)", |
| 1482 |
e, base_dn, filter |
| 1483 |
) |
| 1484 |
raise |
| 1485 |
|
| 1486 |
return entries |
| 1487 |
|
| 1488 |
def find_entries( |
| 1489 |
self, filter=None, attrs_list=None, base_dn=None, |
| 1490 |
scope=ldap.SCOPE_SUBTREE, time_limit=None, size_limit=None, |
| 1491 |
paged_search=False, get_effective_rights=False): |
| 1492 |
""" |
| 1493 |
Return a list of entries and indication of whether the results were |
| 1494 |
truncated ([(dn, entry_attrs)], truncated) matching specified search |
| 1495 |
parameters followed by truncated flag. If the truncated flag is True, |
| 1496 |
search hit a server limit and its results are incomplete. |
| 1497 |
|
| 1498 |
Keyword arguments: |
| 1499 |
:param attrs_list: list of attributes to return, all if None |
| 1500 |
(default None) |
| 1501 |
:param base_dn: dn of the entry at which to start the search |
| 1502 |
(default '') |
| 1503 |
:param scope: search scope, see LDAP docs (default ldap2.SCOPE_SUBTREE) |
| 1504 |
:param time_limit: time limit in seconds (default unlimited) |
| 1505 |
:param size_limit: size (number of entries returned) limit |
| 1506 |
(default unlimited) |
| 1507 |
:param paged_search: search using paged results control |
| 1508 |
:param get_effective_rights: use GetEffectiveRights control |
| 1509 |
|
| 1510 |
:raises: errors.NotFound if result set is empty |
| 1511 |
or base_dn doesn't exist |
| 1512 |
""" |
| 1513 |
if base_dn is None: |
| 1514 |
base_dn = DN() |
| 1515 |
assert isinstance(base_dn, DN) |
| 1516 |
if not filter: |
| 1517 |
filter = '(objectClass=*)' |
| 1518 |
res = [] |
| 1519 |
truncated = False |
| 1520 |
|
| 1521 |
if time_limit is None: |
| 1522 |
time_limit = self.time_limit |
| 1523 |
if time_limit == 0: |
| 1524 |
time_limit = -1.0 |
| 1525 |
|
| 1526 |
if size_limit is None: |
| 1527 |
size_limit = self.size_limit |
| 1528 |
|
| 1529 |
if not isinstance(size_limit, int): |
| 1530 |
size_limit = int(size_limit) |
| 1531 |
if not isinstance(time_limit, float): |
| 1532 |
time_limit = float(time_limit) |
| 1533 |
|
| 1534 |
if attrs_list: |
| 1535 |
attrs_list = [a.lower() for a in set(attrs_list)] |
| 1536 |
|
| 1537 |
base_sctrls = [] |
| 1538 |
if get_effective_rights: |
| 1539 |
base_sctrls.append(self.__get_effective_rights_control()) |
| 1540 |
|
| 1541 |
cookie = '' |
| 1542 |
page_size = (size_limit if size_limit > 0 else 2000) - 1 |
| 1543 |
if page_size == 0: |
| 1544 |
paged_search = False |
| 1545 |
|
| 1546 |
# pass arguments to python-ldap |
| 1547 |
with self.error_handler(): |
| 1548 |
if six.PY2: |
| 1549 |
filter = self.encode(filter) |
| 1550 |
attrs_list = self.encode(attrs_list) |
| 1551 |
|
| 1552 |
while True: |
| 1553 |
if paged_search: |
| 1554 |
sctrls = base_sctrls + [ |
| 1555 |
SimplePagedResultsControl(0, page_size, cookie) |
| 1556 |
] |
| 1557 |
else: |
| 1558 |
sctrls = base_sctrls or None |
| 1559 |
|
| 1560 |
try: |
| 1561 |
id = self.conn.search_ext( |
| 1562 |
str(base_dn), scope, filter, attrs_list, |
| 1563 |
serverctrls=sctrls, timeout=time_limit, |
| 1564 |
sizelimit=size_limit |
| 1565 |
) |
| 1566 |
while True: |
| 1567 |
result = self.conn.result3(id, 0) |
| 1568 |
objtype, res_list, _res_id, res_ctrls = result |
| 1569 |
if objtype == ldap.RES_SEARCH_RESULT: |
| 1570 |
break |
| 1571 |
res_list = self._convert_result(res_list) |
| 1572 |
if res_list: |
| 1573 |
res.append(res_list[0]) |
| 1574 |
|
| 1575 |
if paged_search: |
| 1576 |
# Get cookie for the next page |
| 1577 |
for ctrl in res_ctrls: |
| 1578 |
if isinstance(ctrl, SimplePagedResultsControl): |
| 1579 |
cookie = ctrl.cookie |
| 1580 |
break |
| 1581 |
else: |
| 1582 |
cookie = '' |
| 1583 |
except ldap.ADMINLIMIT_EXCEEDED: |
| 1584 |
truncated = TRUNCATED_ADMIN_LIMIT |
| 1585 |
break |
| 1586 |
except ldap.SIZELIMIT_EXCEEDED: |
| 1587 |
truncated = TRUNCATED_SIZE_LIMIT |
| 1588 |
break |
| 1589 |
except ldap.TIMELIMIT_EXCEEDED: |
| 1590 |
truncated = TRUNCATED_TIME_LIMIT |
| 1591 |
break |
| 1592 |
except ldap.LDAPError as e: |
| 1593 |
# If paged search is in progress, try to cancel it |
| 1594 |
if paged_search and cookie: |
| 1595 |
sctrls = [SimplePagedResultsControl(0, 0, cookie)] |
| 1596 |
try: |
| 1597 |
self.conn.search_ext_s( |
| 1598 |
str(base_dn), scope, filter, attrs_list, |
| 1599 |
serverctrls=sctrls, timeout=time_limit, |
| 1600 |
sizelimit=size_limit) |
| 1601 |
except ldap.LDAPError as e2: |
| 1602 |
logger.warning( |
| 1603 |
"Error cancelling paged search: %s", e2) |
| 1604 |
cookie = '' |
| 1605 |
|
| 1606 |
try: |
| 1607 |
raise e |
| 1608 |
except (ldap.ADMINLIMIT_EXCEEDED, ldap.TIMELIMIT_EXCEEDED, |
| 1609 |
ldap.SIZELIMIT_EXCEEDED): |
| 1610 |
truncated = True |
| 1611 |
break |
| 1612 |
|
| 1613 |
if not paged_search or not cookie: |
| 1614 |
break |
| 1615 |
|
| 1616 |
if not res and not truncated: |
| 1617 |
raise errors.EmptyResult(reason='no matching entry found') |
| 1618 |
|
| 1619 |
return (res, truncated) |
| 1620 |
|
| 1621 |
def __get_effective_rights_control(self): |
| 1622 |
"""Construct a GetEffectiveRights control for current user.""" |
| 1623 |
bind_dn = self.conn.whoami_s()[4:] |
| 1624 |
return GetEffectiveRightsControl( |
| 1625 |
True, "dn: {0}".format(bind_dn).encode('utf-8')) |
| 1626 |
|
| 1627 |
def find_entry_by_attr(self, attr, value, object_class, attrs_list=None, |
| 1628 |
base_dn=None): |
| 1629 |
""" |
| 1630 |
Find entry (dn, entry_attrs) by attribute and object class. |
| 1631 |
|
| 1632 |
Keyword arguments: |
| 1633 |
attrs_list - list of attributes to return, all if None (default None) |
| 1634 |
base_dn - dn of the entry at which to start the search (default '') |
| 1635 |
""" |
| 1636 |
|
| 1637 |
if base_dn is None: |
| 1638 |
base_dn = DN() |
| 1639 |
assert isinstance(base_dn, DN) |
| 1640 |
|
| 1641 |
search_kw = {attr: value, 'objectClass': object_class} |
| 1642 |
filter = self.make_filter(search_kw, rules=self.MATCH_ALL) |
| 1643 |
entries = self.get_entries( |
| 1644 |
base_dn, filter=filter, attrs_list=attrs_list) |
| 1645 |
|
| 1646 |
if len(entries) > 1: |
| 1647 |
raise errors.SingleMatchExpected(found=len(entries)) |
| 1648 |
|
| 1649 |
return entries[0] |
| 1650 |
|
| 1651 |
def get_entry(self, dn, attrs_list=None, time_limit=None, |
| 1652 |
size_limit=None, get_effective_rights=False): |
| 1653 |
""" |
| 1654 |
Get entry (dn, entry_attrs) by dn. |
| 1655 |
|
| 1656 |
Keyword arguments: |
| 1657 |
attrs_list - list of attributes to return, all if None (default None) |
| 1658 |
""" |
| 1659 |
|
| 1660 |
assert isinstance(dn, DN) |
| 1661 |
|
| 1662 |
entries = self.get_entries( |
| 1663 |
dn, self.SCOPE_BASE, None, attrs_list, time_limit=time_limit, |
| 1664 |
size_limit=size_limit, get_effective_rights=get_effective_rights, |
| 1665 |
) |
| 1666 |
|
| 1667 |
return entries[0] |
| 1668 |
|
| 1669 |
def add_entry(self, entry): |
| 1670 |
"""Create a new entry. |
| 1671 |
|
| 1672 |
This should be called as add_entry(entry). |
| 1673 |
""" |
| 1674 |
# remove all [] values (python-ldap hates 'em) |
| 1675 |
attrs = dict((k, v) for k, v in entry.raw.items() if v) |
| 1676 |
|
| 1677 |
with self.error_handler(): |
| 1678 |
attrs = self.encode(attrs) |
| 1679 |
self.conn.add_s(str(entry.dn), list(attrs.items())) |
| 1680 |
|
| 1681 |
entry.reset_modlist() |
| 1682 |
|
| 1683 |
def move_entry(self, dn, new_dn, del_old=True): |
| 1684 |
""" |
| 1685 |
Move an entry (either to a new superior or/and changing relative distinguished name) |
| 1686 |
|
| 1687 |
Keyword arguments: |
| 1688 |
dn: DN of the source entry |
| 1689 |
new_dn: DN of the target entry |
| 1690 |
del_old -- delete old RDN value (default True) |
| 1691 |
|
| 1692 |
:raises: |
| 1693 |
errors.NotFound if source entry or target superior entry doesn't exist |
| 1694 |
errors.EmptyModlist if source and target are identical |
| 1695 |
""" |
| 1696 |
assert isinstance(dn, DN) |
| 1697 |
assert isinstance(new_dn, DN) |
| 1698 |
|
| 1699 |
if new_dn == dn: |
| 1700 |
raise errors.EmptyModlist() |
| 1701 |
|
| 1702 |
new_rdn = new_dn[0] |
| 1703 |
|
| 1704 |
if new_dn[1:] == dn[1:]: |
| 1705 |
new_superior = None |
| 1706 |
else: |
| 1707 |
new_superior = str(DN(*new_dn[1:])) |
| 1708 |
|
| 1709 |
with self.error_handler(): |
| 1710 |
self.conn.rename_s(str(dn), str(new_rdn), newsuperior=new_superior, |
| 1711 |
delold=int(del_old)) |
| 1712 |
time.sleep(.3) # Give memberOf plugin a chance to work |
| 1713 |
|
| 1714 |
def update_entry(self, entry): |
| 1715 |
"""Update entry's attributes. |
| 1716 |
|
| 1717 |
This should be called as update_entry(entry). |
| 1718 |
""" |
| 1719 |
# generate modlist |
| 1720 |
modlist = entry.generate_modlist() |
| 1721 |
if not modlist: |
| 1722 |
raise errors.EmptyModlist() |
| 1723 |
logger.debug("update_entry modlist %s", modlist) |
| 1724 |
|
| 1725 |
# pass arguments to python-ldap |
| 1726 |
with self.error_handler(): |
| 1727 |
modlist = [(a, str(b), self.encode(c)) |
| 1728 |
for a, b, c in modlist] |
| 1729 |
self.conn.modify_s(str(entry.dn), modlist) |
| 1730 |
|
| 1731 |
entry.reset_modlist() |
| 1732 |
|
| 1733 |
def delete_entry(self, entry_or_dn): |
| 1734 |
"""Delete an entry given either the DN or the entry itself""" |
| 1735 |
if isinstance(entry_or_dn, DN): |
| 1736 |
dn = entry_or_dn |
| 1737 |
else: |
| 1738 |
dn = entry_or_dn.dn |
| 1739 |
|
| 1740 |
with self.error_handler(): |
| 1741 |
self.conn.delete_s(str(dn)) |
| 1742 |
|
| 1743 |
def entry_exists(self, dn): |
| 1744 |
""" |
| 1745 |
Test whether the given object exists in LDAP. |
| 1746 |
""" |
| 1747 |
assert isinstance(dn, DN) |
| 1748 |
try: |
| 1749 |
self.get_entry(dn, attrs_list=[]) |
| 1750 |
except errors.NotFound: |
| 1751 |
return False |
| 1752 |
else: |
| 1753 |
return True |
| 1754 |
|
| 1755 |
|
| 1756 |
def get_ldap_uri(host='', port=389, cacert=None, ldapi=False, realm=None, |
| 1757 |
protocol=None): |
| 1758 |
if protocol is None: |
| 1759 |
if ldapi: |
| 1760 |
protocol = 'ldapi' |
| 1761 |
elif cacert is not None: |
| 1762 |
protocol = 'ldaps' |
| 1763 |
else: |
| 1764 |
protocol = 'ldap' |
| 1765 |
|
| 1766 |
if protocol == 'ldaps': |
| 1767 |
return 'ldaps://%s' % format_netloc(host, port) |
| 1768 |
elif protocol == 'ldapi': |
| 1769 |
return 'ldapi://%%2fvar%%2frun%%2fslapd-%s.socket' % ( |
| 1770 |
"-".join(realm.split("."))) |
| 1771 |
elif protocol == 'ldap': |
| 1772 |
return 'ldap://%s' % format_netloc(host, port) |
| 1773 |
else: |
| 1774 |
raise ValueError('Protocol %r not supported' % protocol) |
| 1775 |
|
| 1776 |
|
| 1777 |
class CacheEntry: |
| 1778 |
def __init__(self, entry=None, attrs_list=None, exception=None, |
| 1779 |
get_effective_rights=False, all=False): |
| 1780 |
self.entry = entry |
| 1781 |
self.attrs_list = attrs_list |
| 1782 |
self.exception = exception |
| 1783 |
self.all = all |
| 1784 |
|
| 1785 |
|
| 1786 |
class LDAPCache(LDAPClient): |
| 1787 |
"""A very basic LRU Cache using an OrderedDict""" |
| 1788 |
|
| 1789 |
def __init__(self, ldap_uri, start_tls=False, force_schema_updates=False, |
| 1790 |
no_schema=False, decode_attrs=True, cacert=None, |
| 1791 |
sasl_nocanon=True, enable_cache=True, cache_size=100, |
| 1792 |
debug_cache=False): |
| 1793 |
|
| 1794 |
self.cache = OrderedDict() |
| 1795 |
self._enable_cache = True # initialize to zero to satisfy pylint |
| 1796 |
self._debug_cache = False # initialize to zero to satisfy pylint |
| 1797 |
|
| 1798 |
object.__setattr__(self, '_cache_misses', 0) |
| 1799 |
object.__setattr__(self, '_cache_hits', 0) |
| 1800 |
object.__setattr__(self, '_enable_cache', |
| 1801 |
enable_cache and cache_size > 0) |
| 1802 |
object.__setattr__(self, '_debug_cache', debug_cache) |
| 1803 |
object.__setattr__(self, '_cache_size', cache_size) |
| 1804 |
|
| 1805 |
super(LDAPCache, self).__init__( |
| 1806 |
ldap_uri, start_tls, force_schema_updates, no_schema, |
| 1807 |
decode_attrs, cacert, sasl_nocanon |
| 1808 |
) |
| 1809 |
|
| 1810 |
@property |
| 1811 |
def hit(self): |
| 1812 |
return self._cache_hits # pylint: disable=no-member |
| 1813 |
|
| 1814 |
@property |
| 1815 |
def miss(self): |
| 1816 |
return self._cache_misses # pylint: disable=no-member |
| 1817 |
|
| 1818 |
@property |
| 1819 |
def max_entries(self): |
| 1820 |
return self._cache_size # pylint: disable=no-member |
| 1821 |
|
| 1822 |
def emit(self, msg, *args, **kwargs): |
| 1823 |
if self._enable_cache and self._debug_cache: |
| 1824 |
logger.debug(msg, *args, **kwargs) |
| 1825 |
|
| 1826 |
def copy_entry(self, dn, entry, attrs=[]): |
| 1827 |
new_entry = LDAPEntry(self, DN(dn)) |
| 1828 |
|
| 1829 |
# Return either the whole entry or only those attrs requested |
| 1830 |
if not attrs: |
| 1831 |
new_entry.raw.update(deepcopy(dict(entry.raw))) |
| 1832 |
else: |
| 1833 |
for attr, original_values in entry.raw.items(): |
| 1834 |
if attr.lower() not in attrs: |
| 1835 |
continue |
| 1836 |
new_entry.raw[attr.lower()] = deepcopy(original_values) |
| 1837 |
new_entry._orig_raw = deepcopy(dict(entry.raw)) |
| 1838 |
new_entry.reset_modlist() |
| 1839 |
|
| 1840 |
return new_entry |
| 1841 |
|
| 1842 |
def add_cache_entry(self, dn, attrs_list=None, get_all=False, |
| 1843 |
entry=None, exception=None): |
| 1844 |
# idnsname - caching prevents delete when mod value to None |
| 1845 |
# cospriority - in a Class of Service object, uncacheable |
| 1846 |
# usercertificate* - caching subtypes is tricky, trade less |
| 1847 |
# complexity for performance |
| 1848 |
# |
| 1849 |
# TODO: teach the cache about subtypes |
| 1850 |
|
| 1851 |
BANNED_ATTRS = { |
| 1852 |
'idnsname', |
| 1853 |
'cospriority', |
| 1854 |
'usercertificate', |
| 1855 |
'usercertificate;binary' |
| 1856 |
} |
| 1857 |
if not self._enable_cache: |
| 1858 |
return |
| 1859 |
|
| 1860 |
self.remove_cache_entry(dn) |
| 1861 |
|
| 1862 |
if ( |
| 1863 |
DN('cn=config') in dn |
| 1864 |
or DN('cn=kerberos') in dn |
| 1865 |
or DN('o=ipaca') in dn |
| 1866 |
): |
| 1867 |
return |
| 1868 |
|
| 1869 |
if exception: |
| 1870 |
self.emit("EXC: Caching exception %s", exception) |
| 1871 |
self.cache[dn] = CacheEntry(exception=exception) |
| 1872 |
else: |
| 1873 |
if not BANNED_ATTRS.intersection(attrs_list): |
| 1874 |
self.cache[dn] = CacheEntry( |
| 1875 |
entry=entry.copy(), |
| 1876 |
attrs_list=attrs_list.copy(), |
| 1877 |
all=get_all, |
| 1878 |
) |
| 1879 |
else: |
| 1880 |
return |
| 1881 |
|
| 1882 |
self.emit("ADD: %s: %s all=%s", dn, attrs_list, get_all) |
| 1883 |
|
| 1884 |
self.cache.move_to_end(dn) |
| 1885 |
|
| 1886 |
if len(self.cache) > self.max_entries: |
| 1887 |
(dn, entry) = self.cache.popitem(last=False) |
| 1888 |
self.emit("LRU: removed %s", dn) |
| 1889 |
|
| 1890 |
def clear_cache(self): |
| 1891 |
self.cache_status('FINAL') |
| 1892 |
object.__setattr__(self, 'cache', OrderedDict()) |
| 1893 |
object.__setattr__(self, '_cache_hits', 0) |
| 1894 |
object.__setattr__(self, '_cache_misses', 0) |
| 1895 |
|
| 1896 |
def cache_status(self, type): |
| 1897 |
self.emit("%s: Hits %d Misses %d Size %d", |
| 1898 |
type, self.hit, self.miss, len(self.cache)) |
| 1899 |
|
| 1900 |
def remove_cache_entry(self, dn): |
| 1901 |
assert isinstance(dn, DN) |
| 1902 |
self.emit('DROP: %s', dn) |
| 1903 |
if dn in self.cache: |
| 1904 |
del self.cache[dn] |
| 1905 |
else: |
| 1906 |
self.emit('DROP: not in cache %s', dn) |
| 1907 |
|
| 1908 |
# Begin LDAPClient methods |
| 1909 |
|
| 1910 |
def add_entry(self, entry): |
| 1911 |
self.emit('add_entry') |
| 1912 |
self.remove_cache_entry(entry.dn) |
| 1913 |
super(LDAPCache, self).add_entry(entry) |
| 1914 |
|
| 1915 |
def update_entry(self, entry): |
| 1916 |
self.emit('update_entry') |
| 1917 |
self.remove_cache_entry(entry.dn) |
| 1918 |
super(LDAPCache, self).update_entry(entry) |
| 1919 |
|
| 1920 |
def delete_entry(self, entry_or_dn): |
| 1921 |
self.emit('delete_entry') |
| 1922 |
if isinstance(entry_or_dn, DN): |
| 1923 |
dn = entry_or_dn |
| 1924 |
else: |
| 1925 |
dn = entry_or_dn.dn |
| 1926 |
|
| 1927 |
self.remove_cache_entry(dn) |
| 1928 |
|
| 1929 |
super(LDAPCache, self).delete_entry(dn) |
| 1930 |
|
| 1931 |
def move_entry(self, dn, new_dn, del_old=True): |
| 1932 |
self.emit('move_entry') |
| 1933 |
self.remove_cache_entry(dn) |
| 1934 |
self.remove_cache_entry(new_dn) |
| 1935 |
|
| 1936 |
super(LDAPCache, self).move_entry(dn, new_dn, del_old) |
| 1937 |
|
| 1938 |
def modify_s(self, dn, modlist): |
| 1939 |
self.emit('modify_s') |
| 1940 |
if not isinstance(dn, DN): |
| 1941 |
dn = DN(dn) |
| 1942 |
|
| 1943 |
self.emit('modlist %s', modlist) |
| 1944 |
for (_op, attr, mod_dn) in modlist: |
| 1945 |
if attr.lower() in ('member', |
| 1946 |
'ipaallowedtoperform_write_keys', |
| 1947 |
'managedby_host'): |
| 1948 |
for d in mod_dn: |
| 1949 |
if not isinstance(d, (DN, RDN)): |
| 1950 |
d = DN(d.decode('utf-8')) |
| 1951 |
self.emit('modify_s %s', d) |
| 1952 |
self.remove_cache_entry(d) |
| 1953 |
|
| 1954 |
self.emit('modify_s %s', dn) |
| 1955 |
self.remove_cache_entry(dn) |
| 1956 |
|
| 1957 |
return super(LDAPCache, self).modify_s(dn, modlist) |
| 1958 |
|
| 1959 |
def get_entry(self, dn, attrs_list=None, time_limit=None, |
| 1960 |
size_limit=None, get_effective_rights=False): |
| 1961 |
if not self._enable_cache: |
| 1962 |
return super(LDAPCache, self).get_entry( |
| 1963 |
dn, attrs_list, time_limit, size_limit, get_effective_rights |
| 1964 |
) |
| 1965 |
self.emit("Cache lookup: %s", dn) |
| 1966 |
|
| 1967 |
entry = self.cache.get(dn) |
| 1968 |
if get_effective_rights and entry: |
| 1969 |
# We don't cache this so do the query but don't drop the |
| 1970 |
# entry. |
| 1971 |
entry = None |
| 1972 |
|
| 1973 |
if entry and entry.exception: |
| 1974 |
hits = self._cache_hits + 1 # pylint: disable=no-member |
| 1975 |
object.__setattr__(self, '_cache_hits', hits) |
| 1976 |
self.emit("HIT: Re-raising %s", entry.exception) |
| 1977 |
self.cache_status('HIT') |
| 1978 |
raise entry.exception |
| 1979 |
|
| 1980 |
self.emit("Requested attrs_list %s", attrs_list) |
| 1981 |
if entry: |
| 1982 |
self.emit("Cached attrs_list %s", entry.attrs_list) |
| 1983 |
|
| 1984 |
if not attrs_list: |
| 1985 |
attrs_list = ['*'] |
| 1986 |
elif attrs_list == ['']: |
| 1987 |
attrs_list = ['dn'] |
| 1988 |
|
| 1989 |
get_all = False |
| 1990 |
if ( |
| 1991 |
entry |
| 1992 |
and (attrs_list in (['*'], [''])) |
| 1993 |
and entry.all |
| 1994 |
): |
| 1995 |
get_all = True |
| 1996 |
|
| 1997 |
if entry and entry.all and get_all: |
| 1998 |
hits = self._cache_hits + 1 # pylint: disable=no-member |
| 1999 |
object.__setattr__(self, '_cache_hits', hits) |
| 2000 |
self.cache_status('HIT') |
| 2001 |
return self.copy_entry(dn, entry.entry) |
| 2002 |
|
| 2003 |
# Be sure we have all the requested attributes before returning |
| 2004 |
# a cached entry. |
| 2005 |
if entry and attrs_list: |
| 2006 |
req_attrs = set(attr.lower() for attr in set(attrs_list)) |
| 2007 |
cache_attrs = set(attr.lower() for attr in entry.attrs_list) |
| 2008 |
if req_attrs.issubset(cache_attrs): |
| 2009 |
hits = self._cache_hits + 1 # pylint: disable=no-member |
| 2010 |
object.__setattr__(self, '_cache_hits', hits) |
| 2011 |
self.cache_status('HIT') |
| 2012 |
|
| 2013 |
return self.copy_entry(dn, entry.entry, req_attrs) |
| 2014 |
|
| 2015 |
try: |
| 2016 |
entry = super(LDAPCache, self).get_entry( |
| 2017 |
dn, attrs_list, time_limit, size_limit, get_effective_rights |
| 2018 |
) |
| 2019 |
except (errors.NotFound, errors.EmptyResult) as e: |
| 2020 |
# only cache these exceptions |
| 2021 |
self.add_cache_entry(dn, exception=e) |
| 2022 |
misses = self._cache_misses + 1 # pylint: disable=no-member |
| 2023 |
object.__setattr__(self, '_cache_misses', misses) |
| 2024 |
self.cache_status('MISS: %s' % e) |
| 2025 |
raise |
| 2026 |
# pylint: disable=try-except-raise |
| 2027 |
except Exception: |
| 2028 |
# re-raise anything we aren't caching |
| 2029 |
raise |
| 2030 |
else: |
| 2031 |
if attrs_list in (['*'], ['']): |
| 2032 |
get_all = True |
| 2033 |
self.add_cache_entry( |
| 2034 |
dn, |
| 2035 |
attrs_list=set(k.lower() for k in entry._names.keys()), |
| 2036 |
get_all=get_all, |
| 2037 |
entry=self.copy_entry(dn, entry), |
| 2038 |
) |
| 2039 |
misses = self._cache_misses + 1 # pylint: disable=no-member |
| 2040 |
object.__setattr__(self, '_cache_misses', misses) |
| 2041 |
self.cache_status('MISS') |
| 2042 |
return entry |