2013-01-31 05:19:02 -06:00
|
|
|
# Authors: Rich Megginson <richm@redhat.com>
|
|
|
|
# Rob Crittenden <rcritten@redhat.com>
|
|
|
|
# John Dennis <jdennis@redhat.com>
|
|
|
|
#
|
|
|
|
# Copyright (C) 2007 Red Hat
|
|
|
|
# see file 'COPYING' for use and warranty information
|
|
|
|
#
|
|
|
|
# This program is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
#
|
|
|
|
|
2017-01-23 03:26:50 -06:00
|
|
|
import binascii
|
2018-02-21 07:35:25 -06:00
|
|
|
import errno
|
2017-05-23 11:35:57 -05:00
|
|
|
import logging
|
2013-01-31 05:19:02 -06:00
|
|
|
import time
|
2014-01-09 04:14:56 -06:00
|
|
|
import datetime
|
2013-01-31 05:19:02 -06:00
|
|
|
from decimal import Decimal
|
|
|
|
from copy import deepcopy
|
|
|
|
import contextlib
|
2014-08-27 08:06:42 -05:00
|
|
|
import os
|
|
|
|
import pwd
|
2017-12-04 10:29:05 -06:00
|
|
|
import warnings
|
2016-11-23 04:01:56 -06:00
|
|
|
|
2017-07-03 10:10:34 -05:00
|
|
|
from cryptography import x509 as crypto_x509
|
2018-11-22 11:31:38 -06:00
|
|
|
from cryptography.hazmat.primitives import serialization
|
2017-07-03 10:10:34 -05:00
|
|
|
|
2013-01-31 05:19:02 -06:00
|
|
|
import ldap
|
|
|
|
import ldap.sasl
|
|
|
|
import ldap.filter
|
2018-02-07 18:04:48 -06:00
|
|
|
from ldap.controls import SimplePagedResultsControl, GetEffectiveRightsControl
|
2018-11-29 07:49:43 -06:00
|
|
|
import ldapurl
|
2015-08-10 11:29:33 -05:00
|
|
|
import six
|
2013-01-31 05:19:02 -06:00
|
|
|
|
2017-02-14 02:58:44 -06:00
|
|
|
# pylint: disable=ipa-forbidden-import
|
2017-07-03 10:10:34 -05:00
|
|
|
from ipalib import errors, x509, _
|
2019-05-01 13:25:31 -05:00
|
|
|
from ipalib.constants import LDAP_GENERALIZED_TIME_FORMAT
|
2017-02-14 02:58:44 -06:00
|
|
|
# pylint: enable=ipa-forbidden-import
|
2018-11-29 07:49:43 -06:00
|
|
|
from ipaplatform.paths import paths
|
2016-10-05 09:09:56 -05:00
|
|
|
from ipapython.ipautil import format_netloc, CIDict
|
2015-12-16 09:06:03 -06:00
|
|
|
from ipapython.dn import DN
|
2014-03-27 08:43:32 -05:00
|
|
|
from ipapython.dnsutil import DNSName
|
2016-06-23 11:23:00 -05:00
|
|
|
from ipapython.kerberos import Principal
|
2013-01-31 05:19:02 -06:00
|
|
|
|
2018-07-04 03:07:49 -05:00
|
|
|
# pylint: disable=no-name-in-module, import-error
|
|
|
|
if six.PY3:
|
|
|
|
from collections.abc import MutableMapping
|
|
|
|
else:
|
|
|
|
from collections import MutableMapping
|
|
|
|
# pylint: enable=no-name-in-module, import-error
|
|
|
|
|
2015-09-11 06:43:28 -05:00
|
|
|
if six.PY3:
|
|
|
|
unicode = str
|
|
|
|
|
2017-05-23 11:35:57 -05:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2013-01-31 05:19:02 -06:00
|
|
|
# Global variable to define SASL auth
|
|
|
|
SASL_GSSAPI = ldap.sasl.sasl({}, 'GSSAPI')
|
2017-03-06 13:19:30 -06:00
|
|
|
SASL_GSS_SPNEGO = ldap.sasl.sasl({}, 'GSS-SPNEGO')
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
_debug_log_ldap = False
|
|
|
|
|
|
|
|
_missing = object()
|
|
|
|
|
2014-08-27 08:06:42 -05:00
|
|
|
# Autobind modes
|
|
|
|
AUTOBIND_AUTO = 1
|
|
|
|
AUTOBIND_ENABLED = 2
|
|
|
|
AUTOBIND_DISABLED = 3
|
2013-01-31 05:19:02 -06:00
|
|
|
|
2016-03-18 03:49:41 -05:00
|
|
|
TRUNCATED_SIZE_LIMIT = object()
|
|
|
|
TRUNCATED_TIME_LIMIT = object()
|
|
|
|
TRUNCATED_ADMIN_LIMIT = object()
|
|
|
|
|
2016-10-05 10:42:32 -05:00
|
|
|
DIRMAN_DN = DN(('cn', 'directory manager'))
|
|
|
|
|
2016-03-18 03:49:41 -05:00
|
|
|
|
2017-12-12 09:40:44 -06:00
|
|
|
if six.PY2 and hasattr(ldap, 'LDAPBytesWarning'):
|
2017-12-04 10:29:05 -06:00
|
|
|
# XXX silence python-ldap's BytesWarnings
|
|
|
|
warnings.filterwarnings(
|
|
|
|
action="ignore",
|
2017-12-12 09:40:44 -06:00
|
|
|
category=ldap.LDAPBytesWarning, # pylint: disable=no-member
|
2017-12-04 10:29:05 -06:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2018-11-29 07:49:43 -06:00
|
|
|
def realm_to_serverid(realm_name):
|
|
|
|
"""Convert Kerberos realm name to 389-DS server id"""
|
|
|
|
return "-".join(realm_name.split("."))
|
|
|
|
|
|
|
|
|
|
|
|
def realm_to_ldapi_uri(realm_name):
|
|
|
|
"""Get ldapi:// URI to 389-DS's Unix socket"""
|
|
|
|
serverid = realm_to_serverid(realm_name)
|
|
|
|
socketname = paths.SLAPD_INSTANCE_SOCKET_TEMPLATE % (serverid,)
|
|
|
|
return 'ldapi://' + ldapurl.ldapUrlEscape(socketname)
|
|
|
|
|
|
|
|
|
2019-05-01 13:25:31 -05:00
|
|
|
def ldap_initialize(uri, cacertfile=None):
|
2018-02-15 05:30:06 -06:00
|
|
|
"""Wrapper around ldap.initialize()
|
2018-02-21 07:35:25 -06:00
|
|
|
|
|
|
|
The function undoes global and local ldap.conf settings that may cause
|
|
|
|
issues or reduce security:
|
|
|
|
|
|
|
|
* Canonization of SASL host names is disabled.
|
|
|
|
* With cacertfile=None, the connection uses OpenSSL's default verify
|
|
|
|
locations, also known as system-wide trust store.
|
|
|
|
* Cert validation is enforced.
|
|
|
|
* SSLv2 and SSLv3 are disabled.
|
2018-02-15 05:30:06 -06:00
|
|
|
"""
|
|
|
|
conn = ldap.initialize(uri)
|
|
|
|
|
2018-02-21 07:35:25 -06:00
|
|
|
# Do not perform reverse DNS lookups to canonicalize SASL host names
|
|
|
|
conn.set_option(ldap.OPT_X_SASL_NOCANON, ldap.OPT_ON)
|
|
|
|
|
2018-02-15 05:30:06 -06:00
|
|
|
if not uri.startswith('ldapi://'):
|
|
|
|
if cacertfile:
|
2018-02-21 07:35:25 -06:00
|
|
|
if not os.path.isfile(cacertfile):
|
|
|
|
raise IOError(errno.ENOENT, cacertfile)
|
2018-02-15 05:30:06 -06:00
|
|
|
conn.set_option(ldap.OPT_X_TLS_CACERTFILE, cacertfile)
|
|
|
|
|
2018-02-21 07:35:25 -06:00
|
|
|
# SSLv3 and SSLv2 are insecure
|
2020-01-17 09:59:55 -06:00
|
|
|
# OpenLDAP 2.4 sets minimum version with SSL_CTX_set_options(). The
|
|
|
|
# system-wide crypto-policies for TLS minimum version are applied
|
|
|
|
# with SSL_CTX_set_min_proto_version(). The set_option() call cannot
|
|
|
|
# enable lower versions than allowed by crypto-policy, e.g.
|
|
|
|
# openssl.cnf MinProtocol=TLS1.2 + OPT_X_TLS_PROTOCOL_MIN=TLS1.0
|
|
|
|
# result in TLS 1.2 as minimum protocol version.
|
2018-02-21 07:35:25 -06:00
|
|
|
conn.set_option(ldap.OPT_X_TLS_PROTOCOL_MIN, 0x301) # TLS 1.0
|
|
|
|
# libldap defaults to cert validation, but the default can be
|
|
|
|
# overridden in global or user local ldap.conf.
|
|
|
|
conn.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_DEMAND)
|
|
|
|
# reinitialize TLS context to materialize settings
|
|
|
|
conn.set_option(ldap.OPT_X_TLS_NEWCTX, 0)
|
2018-02-15 05:30:06 -06:00
|
|
|
|
|
|
|
return conn
|
|
|
|
|
|
|
|
|
2018-09-26 04:59:50 -05:00
|
|
|
class _ServerSchema:
|
2013-01-31 05:19:02 -06:00
|
|
|
'''
|
|
|
|
Properties of a schema retrieved from an LDAP server.
|
|
|
|
'''
|
|
|
|
|
|
|
|
def __init__(self, server, schema):
|
|
|
|
self.server = server
|
|
|
|
self.schema = schema
|
|
|
|
self.retrieve_timestamp = time.time()
|
|
|
|
|
|
|
|
|
2018-09-26 04:59:50 -05:00
|
|
|
class SchemaCache:
|
2013-01-31 05:19:02 -06:00
|
|
|
'''
|
|
|
|
Cache the schema's from individual LDAP servers.
|
|
|
|
'''
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self.servers = {}
|
|
|
|
|
|
|
|
def get_schema(self, url, conn, force_update=False):
|
|
|
|
'''
|
|
|
|
Return schema belonging to a specific LDAP server.
|
|
|
|
|
|
|
|
For performance reasons the schema is retrieved once and
|
|
|
|
cached unless force_update is True. force_update flushes the
|
|
|
|
existing schema for the server from the cache and reacquires
|
|
|
|
it.
|
|
|
|
'''
|
|
|
|
|
|
|
|
if force_update:
|
|
|
|
self.flush(url)
|
|
|
|
|
|
|
|
server_schema = self.servers.get(url)
|
|
|
|
if server_schema is None:
|
|
|
|
schema = self._retrieve_schema_from_server(url, conn)
|
|
|
|
server_schema = _ServerSchema(url, schema)
|
|
|
|
self.servers[url] = server_schema
|
|
|
|
return server_schema.schema
|
|
|
|
|
|
|
|
def flush(self, url):
|
2017-05-23 11:35:57 -05:00
|
|
|
logger.debug('flushing %s from SchemaCache', url)
|
2013-01-31 05:19:02 -06:00
|
|
|
try:
|
|
|
|
del self.servers[url]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
def _retrieve_schema_from_server(self, url, conn):
|
|
|
|
"""
|
|
|
|
Retrieve the LDAP schema from the provided url and determine if
|
|
|
|
User-Private Groups (upg) are configured.
|
|
|
|
|
|
|
|
Bind using kerberos credentials. If in the context of the
|
|
|
|
in-tree "lite" server then use the current ccache. If in the context of
|
|
|
|
Apache then create a new ccache and bind using the Apache HTTP service
|
|
|
|
principal.
|
|
|
|
|
|
|
|
If a connection is provided then it the credentials bound to it are
|
|
|
|
used. The connection is not closed when the request is done.
|
|
|
|
"""
|
|
|
|
assert conn is not None
|
|
|
|
|
2017-05-23 11:35:57 -05:00
|
|
|
logger.debug(
|
2013-01-31 05:19:02 -06:00
|
|
|
'retrieving schema for SchemaCache url=%s conn=%s', url, conn)
|
|
|
|
|
|
|
|
try:
|
|
|
|
try:
|
|
|
|
schema_entry = conn.search_s('cn=schema', ldap.SCOPE_BASE,
|
|
|
|
attrlist=['attributetypes', 'objectclasses'])[0]
|
|
|
|
except ldap.NO_SUCH_OBJECT:
|
|
|
|
# try different location for schema
|
|
|
|
# openldap has schema located in cn=subschema
|
2017-05-23 11:35:57 -05:00
|
|
|
logger.debug('cn=schema not found, fallback to cn=subschema')
|
2013-01-31 05:19:02 -06:00
|
|
|
schema_entry = conn.search_s('cn=subschema', ldap.SCOPE_BASE,
|
|
|
|
attrlist=['attributetypes', 'objectclasses'])[0]
|
|
|
|
except ldap.SERVER_DOWN:
|
|
|
|
raise errors.NetworkError(uri=url,
|
|
|
|
error=u'LDAP Server Down, unable to retrieve LDAP schema')
|
2015-07-30 09:49:29 -05:00
|
|
|
except ldap.LDAPError as e:
|
2013-01-31 05:19:02 -06:00
|
|
|
desc = e.args[0]['desc'].strip()
|
|
|
|
info = e.args[0].get('info', '').strip()
|
|
|
|
raise errors.DatabaseError(desc = u'uri=%s' % url,
|
|
|
|
info = u'Unable to retrieve LDAP schema: %s: %s' % (desc, info))
|
2018-07-12 09:21:34 -05:00
|
|
|
|
|
|
|
# no 'cn=schema' entry in LDAP? some servers use 'cn=subschema'
|
|
|
|
# TODO: DS uses 'cn=schema', support for other server?
|
|
|
|
# raise a more appropriate exception
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
return ldap.schema.SubSchema(schema_entry[1])
|
|
|
|
|
|
|
|
schema_cache = SchemaCache()
|
|
|
|
|
|
|
|
|
2018-07-04 03:07:49 -05:00
|
|
|
class LDAPEntry(MutableMapping):
|
2013-02-27 02:16:49 -06:00
|
|
|
__slots__ = ('_conn', '_dn', '_names', '_nice', '_raw', '_sync',
|
2017-06-02 05:58:19 -05:00
|
|
|
'_not_list', '_orig_raw', '_raw_view',
|
|
|
|
'_single_value_view')
|
2013-01-31 05:19:02 -06:00
|
|
|
|
2017-08-22 07:12:40 -05:00
|
|
|
__hash__ = None
|
|
|
|
|
2013-01-31 05:19:02 -06:00
|
|
|
def __init__(self, _conn, _dn=None, _obj=None, **kwargs):
|
|
|
|
"""
|
|
|
|
LDAPEntry constructor.
|
|
|
|
|
|
|
|
Takes 1 to 3 positional arguments and an arbitrary number of keyword
|
|
|
|
arguments. The 3 forms of positional arguments are:
|
|
|
|
|
|
|
|
* LDAPEntry(entry) - create a shallow copy of an existing LDAPEntry.
|
|
|
|
* LDAPEntry(dn, entry) - create a shallow copy of an existing
|
|
|
|
LDAPEntry with a different DN.
|
|
|
|
* LDAPEntry(conn, dn, mapping) - create a new LDAPEntry using the
|
2015-01-14 10:49:35 -06:00
|
|
|
specified LDAPClient and DN and optionally initialize
|
2013-01-31 05:19:02 -06:00
|
|
|
attributes from the specified mapping object.
|
|
|
|
|
|
|
|
Keyword arguments can be used to override values of specific attributes.
|
|
|
|
"""
|
2016-02-25 06:46:33 -06:00
|
|
|
super(LDAPEntry, self).__init__() # pylint: disable=no-member
|
2013-09-10 05:20:24 -05:00
|
|
|
|
2013-01-31 05:19:02 -06:00
|
|
|
if isinstance(_conn, LDAPEntry):
|
|
|
|
assert _dn is None
|
|
|
|
_dn = _conn
|
|
|
|
_conn = _conn._conn
|
2015-01-14 10:49:35 -06:00
|
|
|
assert isinstance(_conn, LDAPClient)
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
if isinstance(_dn, LDAPEntry):
|
|
|
|
assert _obj is None
|
|
|
|
_obj = _dn
|
2013-02-26 04:27:55 -06:00
|
|
|
_dn = _dn._dn
|
2013-01-31 05:19:02 -06:00
|
|
|
assert isinstance(_dn, DN)
|
|
|
|
|
2013-02-26 04:27:55 -06:00
|
|
|
if _obj is None:
|
|
|
|
_obj = {}
|
|
|
|
|
2013-01-31 05:19:02 -06:00
|
|
|
self._conn = _conn
|
|
|
|
self._dn = _dn
|
|
|
|
self._names = CIDict()
|
2013-02-27 02:16:49 -06:00
|
|
|
self._nice = {}
|
|
|
|
self._raw = {}
|
|
|
|
self._sync = {}
|
2013-02-26 04:49:01 -06:00
|
|
|
self._not_list = set()
|
2017-06-02 05:58:19 -05:00
|
|
|
self._orig_raw = {}
|
2013-02-27 02:16:49 -06:00
|
|
|
self._raw_view = None
|
2013-09-10 05:20:24 -05:00
|
|
|
self._single_value_view = None
|
2013-02-26 04:27:55 -06:00
|
|
|
|
|
|
|
if isinstance(_obj, LDAPEntry):
|
|
|
|
#pylint: disable=E1103
|
2013-02-26 04:49:01 -06:00
|
|
|
self._not_list = set(_obj._not_list)
|
2017-06-02 05:58:19 -05:00
|
|
|
self._orig_raw = dict(_obj._orig_raw)
|
2013-02-27 02:16:49 -06:00
|
|
|
if _obj.conn is _conn:
|
|
|
|
self._names = CIDict(_obj._names)
|
|
|
|
self._nice = dict(_obj._nice)
|
|
|
|
self._raw = dict(_obj._raw)
|
|
|
|
self._sync = dict(_obj._sync)
|
|
|
|
else:
|
|
|
|
self.raw.update(_obj.raw)
|
2013-02-26 04:27:55 -06:00
|
|
|
|
|
|
|
_obj = {}
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
self.update(_obj, **kwargs)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def conn(self):
|
|
|
|
return self._conn
|
|
|
|
|
|
|
|
@property
|
|
|
|
def dn(self):
|
|
|
|
return self._dn
|
|
|
|
|
|
|
|
@dn.setter
|
|
|
|
def dn(self, value):
|
|
|
|
assert isinstance(value, DN)
|
|
|
|
self._dn = value
|
|
|
|
|
2013-02-27 02:16:49 -06:00
|
|
|
@property
|
|
|
|
def raw(self):
|
|
|
|
if self._raw_view is None:
|
|
|
|
self._raw_view = RawLDAPEntryView(self)
|
|
|
|
return self._raw_view
|
|
|
|
|
2013-09-10 05:20:24 -05:00
|
|
|
@property
|
|
|
|
def single_value(self):
|
|
|
|
if self._single_value_view is None:
|
|
|
|
self._single_value_view = SingleValueLDAPEntryView(self)
|
|
|
|
return self._single_value_view
|
|
|
|
|
2013-01-31 05:19:02 -06:00
|
|
|
def __repr__(self):
|
2013-11-06 05:40:02 -06:00
|
|
|
data = dict(self._raw)
|
Use Python3-compatible dict method names
Python 2 has keys()/values()/items(), which return lists,
iterkeys()/itervalues()/iteritems(), which return iterators,
and viewkeys()/viewvalues()/viewitems() which return views.
Python 3 has only keys()/values()/items(), which return views.
To get iterators, one can use iter() or a for loop/comprehension;
for lists there's the list() constructor.
When iterating through the entire dict, without modifying the dict,
the difference between Python 2's items() and iteritems() is
negligible, especially on small dicts (the main overhead is
extra memory, not CPU time). In the interest of simpler code,
this patch changes many instances of iteritems() to items(),
iterkeys() to keys() etc.
In other cases, helpers like six.itervalues are used.
Reviewed-By: Christian Heimes <cheimes@redhat.com>
Reviewed-By: Jan Cholasta <jcholast@redhat.com>
2015-08-11 06:51:14 -05:00
|
|
|
data.update((k, v) for k, v in self._nice.items() if v is not None)
|
2013-11-06 05:40:02 -06:00
|
|
|
return '%s(%r, %r)' % (type(self).__name__, self._dn, data)
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
def copy(self):
|
|
|
|
return LDAPEntry(self)
|
|
|
|
|
2013-02-27 02:16:49 -06:00
|
|
|
def _sync_attr(self, name):
|
|
|
|
nice = self._nice[name]
|
|
|
|
assert isinstance(nice, list)
|
|
|
|
|
|
|
|
raw = self._raw[name]
|
|
|
|
assert isinstance(raw, list)
|
|
|
|
|
|
|
|
nice_sync, raw_sync = self._sync.setdefault(name, ([], []))
|
|
|
|
if nice == nice_sync and raw == raw_sync:
|
|
|
|
return
|
|
|
|
|
|
|
|
nice_adds = set(nice) - set(nice_sync)
|
|
|
|
nice_dels = set(nice_sync) - set(nice)
|
|
|
|
raw_adds = set(raw) - set(raw_sync)
|
|
|
|
raw_dels = set(raw_sync) - set(raw)
|
|
|
|
|
|
|
|
for value in nice_dels:
|
|
|
|
value = self._conn.encode(value)
|
|
|
|
if value in raw_adds:
|
|
|
|
continue
|
|
|
|
raw.remove(value)
|
|
|
|
|
|
|
|
for value in raw_dels:
|
2016-06-08 11:09:15 -05:00
|
|
|
try:
|
|
|
|
value = self._conn.decode(value, name)
|
|
|
|
except ValueError as e:
|
|
|
|
raise ValueError("{error} in LDAP entry '{dn}'".format(
|
|
|
|
error=e, dn=self._dn))
|
2013-02-27 02:16:49 -06:00
|
|
|
if value in nice_adds:
|
|
|
|
continue
|
|
|
|
nice.remove(value)
|
|
|
|
|
2017-02-07 07:11:24 -06:00
|
|
|
for value in sorted(nice_adds, key=nice.index):
|
2013-02-27 02:16:49 -06:00
|
|
|
value = self._conn.encode(value)
|
|
|
|
if value in raw_dels:
|
|
|
|
continue
|
|
|
|
raw.append(value)
|
|
|
|
|
2017-02-07 07:11:24 -06:00
|
|
|
for value in sorted(raw_adds, key=raw.index):
|
2016-06-08 11:09:15 -05:00
|
|
|
try:
|
|
|
|
value = self._conn.decode(value, name)
|
|
|
|
except ValueError as e:
|
|
|
|
raise ValueError("{error} in LDAP entry '{dn}'".format(
|
|
|
|
error=e, dn=self._dn))
|
2013-02-27 02:16:49 -06:00
|
|
|
if value in nice_dels:
|
|
|
|
continue
|
|
|
|
nice.append(value)
|
|
|
|
|
|
|
|
self._sync[name] = (deepcopy(nice), deepcopy(raw))
|
|
|
|
|
|
|
|
if len(nice) > 1:
|
|
|
|
self._not_list.discard(name)
|
|
|
|
|
2013-01-31 05:19:02 -06:00
|
|
|
def _attr_name(self, name):
|
2018-09-26 05:24:33 -05:00
|
|
|
if not isinstance(name, str):
|
2013-01-31 05:19:02 -06:00
|
|
|
raise TypeError(
|
|
|
|
"attribute name must be unicode or str, got %s object %r" % (
|
|
|
|
name.__class__.__name__, name))
|
|
|
|
|
2015-09-11 07:02:13 -05:00
|
|
|
if isinstance(name, bytes):
|
2013-01-31 05:19:02 -06:00
|
|
|
name = name.decode('utf-8')
|
|
|
|
|
|
|
|
return name
|
|
|
|
|
2013-02-27 02:16:49 -06:00
|
|
|
def _add_attr_name(self, name):
|
2013-02-26 04:27:55 -06:00
|
|
|
if name in self._names:
|
2014-03-27 11:53:13 -05:00
|
|
|
return self._names[name]
|
|
|
|
|
|
|
|
if self._conn.schema is not None:
|
2015-10-14 08:02:51 -05:00
|
|
|
if six.PY2:
|
|
|
|
encoded_name = name.encode('utf-8')
|
|
|
|
else:
|
|
|
|
encoded_name = name
|
2014-03-27 11:53:13 -05:00
|
|
|
attrtype = self._conn.schema.get_obj(
|
2015-10-14 08:02:51 -05:00
|
|
|
ldap.schema.AttributeType, encoded_name)
|
2014-03-27 11:53:13 -05:00
|
|
|
if attrtype is not None:
|
|
|
|
for altname in attrtype.names:
|
2015-10-14 08:02:51 -05:00
|
|
|
if six.PY2:
|
|
|
|
altname = altname.decode('utf-8')
|
2014-03-27 11:53:13 -05:00
|
|
|
self._names[altname] = name
|
2013-01-31 05:19:02 -06:00
|
|
|
|
2014-03-27 11:53:13 -05:00
|
|
|
self._names[name] = name
|
2013-02-27 02:16:49 -06:00
|
|
|
|
2017-06-02 05:58:19 -05:00
|
|
|
for oldname in list(self._orig_raw):
|
2014-03-27 11:53:13 -05:00
|
|
|
if self._names.get(oldname) == name:
|
2017-06-02 05:58:19 -05:00
|
|
|
self._orig_raw[name] = self._orig_raw.pop(oldname)
|
2014-03-27 11:53:13 -05:00
|
|
|
break
|
|
|
|
|
|
|
|
return name
|
2013-12-10 04:53:32 -06:00
|
|
|
|
2013-02-27 02:16:49 -06:00
|
|
|
def _set_nice(self, name, value):
|
|
|
|
name = self._attr_name(name)
|
2014-03-27 11:53:13 -05:00
|
|
|
name = self._add_attr_name(name)
|
2013-02-27 02:16:49 -06:00
|
|
|
|
2013-02-26 04:49:01 -06:00
|
|
|
if not isinstance(value, list):
|
|
|
|
if value is None:
|
|
|
|
value = []
|
|
|
|
else:
|
|
|
|
value = [value]
|
|
|
|
self._not_list.add(name)
|
|
|
|
else:
|
|
|
|
self._not_list.discard(name)
|
|
|
|
|
2013-02-27 02:16:49 -06:00
|
|
|
if self._nice.get(name) is not value:
|
|
|
|
self._nice[name] = value
|
|
|
|
self._raw[name] = None
|
|
|
|
self._sync.pop(name, None)
|
|
|
|
|
|
|
|
if self._raw[name] is not None:
|
|
|
|
self._sync_attr(name)
|
|
|
|
|
|
|
|
def _set_raw(self, name, value):
|
|
|
|
name = self._attr_name(name)
|
|
|
|
|
|
|
|
if not isinstance(value, list):
|
|
|
|
raise TypeError("%s value must be list, got %s object %r" % (
|
|
|
|
name, value.__class__.__name__, value))
|
|
|
|
for (i, item) in enumerate(value):
|
2015-09-11 07:02:13 -05:00
|
|
|
if not isinstance(item, bytes):
|
2017-02-02 09:51:21 -06:00
|
|
|
raise TypeError(
|
|
|
|
"%s[%d] value must be bytes, got %s object %r" % (
|
|
|
|
name, i, item.__class__.__name__, item)
|
|
|
|
)
|
2013-02-27 02:16:49 -06:00
|
|
|
|
2014-03-27 11:53:13 -05:00
|
|
|
name = self._add_attr_name(name)
|
2013-02-27 02:16:49 -06:00
|
|
|
|
|
|
|
if self._raw.get(name) is not value:
|
|
|
|
self._raw[name] = value
|
|
|
|
self._nice[name] = None
|
|
|
|
self._sync.pop(name, None)
|
|
|
|
|
|
|
|
if self._nice[name] is not None:
|
|
|
|
self._sync_attr(name)
|
|
|
|
|
|
|
|
def __setitem__(self, name, value):
|
|
|
|
self._set_nice(name, value)
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
def _get_attr_name(self, name):
|
|
|
|
name = self._attr_name(name)
|
|
|
|
name = self._names[name]
|
|
|
|
return name
|
|
|
|
|
2013-02-27 02:16:49 -06:00
|
|
|
def _get_nice(self, name):
|
2013-02-26 04:27:55 -06:00
|
|
|
name = self._get_attr_name(name)
|
2013-02-26 04:49:01 -06:00
|
|
|
|
2013-02-27 02:16:49 -06:00
|
|
|
value = self._nice[name]
|
|
|
|
if value is None:
|
|
|
|
value = self._nice[name] = []
|
2013-02-26 04:49:01 -06:00
|
|
|
assert isinstance(value, list)
|
|
|
|
|
2013-02-27 02:16:49 -06:00
|
|
|
if self._raw[name] is not None:
|
|
|
|
self._sync_attr(name)
|
|
|
|
|
2013-02-26 04:49:01 -06:00
|
|
|
if name in self._not_list:
|
|
|
|
assert len(value) <= 1
|
|
|
|
if value:
|
|
|
|
value = value[0]
|
|
|
|
else:
|
|
|
|
value = None
|
|
|
|
|
|
|
|
return value
|
2013-01-31 05:19:02 -06:00
|
|
|
|
2013-02-27 02:16:49 -06:00
|
|
|
def _get_raw(self, name):
|
|
|
|
name = self._get_attr_name(name)
|
|
|
|
|
|
|
|
value = self._raw[name]
|
|
|
|
if value is None:
|
|
|
|
value = self._raw[name] = []
|
|
|
|
assert isinstance(value, list)
|
|
|
|
|
|
|
|
if self._nice[name] is not None:
|
|
|
|
self._sync_attr(name)
|
|
|
|
|
|
|
|
return value
|
|
|
|
|
|
|
|
def __getitem__(self, name):
|
|
|
|
return self._get_nice(name)
|
|
|
|
|
2013-02-26 04:27:55 -06:00
|
|
|
def __delitem__(self, name):
|
2013-01-31 05:19:02 -06:00
|
|
|
name = self._get_attr_name(name)
|
|
|
|
|
2016-05-06 11:12:02 -05:00
|
|
|
for (altname, keyname) in list(self._names.items()):
|
2013-01-31 05:19:02 -06:00
|
|
|
if keyname == name:
|
|
|
|
del self._names[altname]
|
|
|
|
|
2013-02-27 02:16:49 -06:00
|
|
|
del self._nice[name]
|
|
|
|
del self._raw[name]
|
|
|
|
self._sync.pop(name, None)
|
2013-02-26 04:49:01 -06:00
|
|
|
self._not_list.discard(name)
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
def clear(self):
|
|
|
|
self._names.clear()
|
2013-02-27 02:16:49 -06:00
|
|
|
self._nice.clear()
|
|
|
|
self._raw.clear()
|
|
|
|
self._sync.clear()
|
2013-02-26 04:49:01 -06:00
|
|
|
self._not_list.clear()
|
2013-02-26 04:27:55 -06:00
|
|
|
|
|
|
|
def __len__(self):
|
2013-02-27 02:16:49 -06:00
|
|
|
return len(self._nice)
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
def __contains__(self, name):
|
2013-02-26 04:27:55 -06:00
|
|
|
return name in self._names
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
def has_key(self, name):
|
|
|
|
return name in self
|
|
|
|
|
2013-02-26 04:27:55 -06:00
|
|
|
def __eq__(self, other):
|
|
|
|
if not isinstance(other, LDAPEntry):
|
|
|
|
return NotImplemented
|
|
|
|
return other is self
|
|
|
|
|
|
|
|
def __ne__(self, other):
|
|
|
|
if not isinstance(other, LDAPEntry):
|
|
|
|
return NotImplemented
|
|
|
|
return other is not self
|
|
|
|
|
2013-12-10 04:53:32 -06:00
|
|
|
def reset_modlist(self, other=None):
|
|
|
|
if other is None:
|
|
|
|
other = self
|
|
|
|
assert isinstance(other, LDAPEntry)
|
2017-06-02 05:58:19 -05:00
|
|
|
self._orig_raw = deepcopy(dict(other.raw))
|
2013-12-10 04:53:32 -06:00
|
|
|
|
2013-12-10 04:45:10 -06:00
|
|
|
def generate_modlist(self):
|
|
|
|
modlist = []
|
|
|
|
|
Use Python3-compatible dict method names
Python 2 has keys()/values()/items(), which return lists,
iterkeys()/itervalues()/iteritems(), which return iterators,
and viewkeys()/viewvalues()/viewitems() which return views.
Python 3 has only keys()/values()/items(), which return views.
To get iterators, one can use iter() or a for loop/comprehension;
for lists there's the list() constructor.
When iterating through the entire dict, without modifying the dict,
the difference between Python 2's items() and iteritems() is
negligible, especially on small dicts (the main overhead is
extra memory, not CPU time). In the interest of simpler code,
this patch changes many instances of iteritems() to items(),
iterkeys() to keys() etc.
In other cases, helpers like six.itervalues are used.
Reviewed-By: Christian Heimes <cheimes@redhat.com>
Reviewed-By: Jan Cholasta <jcholast@redhat.com>
2015-08-11 06:51:14 -05:00
|
|
|
names = set(self)
|
2017-06-02 05:58:19 -05:00
|
|
|
names.update(self._orig_raw)
|
2013-12-10 04:45:10 -06:00
|
|
|
for name in names:
|
2014-02-04 04:39:35 -06:00
|
|
|
new = self.raw.get(name, [])
|
2017-06-02 05:58:19 -05:00
|
|
|
old = self._orig_raw.get(name, [])
|
2013-12-10 04:45:10 -06:00
|
|
|
if old and not new:
|
|
|
|
modlist.append((ldap.MOD_DELETE, name, None))
|
|
|
|
continue
|
2014-02-04 04:39:35 -06:00
|
|
|
if not old and new:
|
2013-12-10 04:45:10 -06:00
|
|
|
modlist.append((ldap.MOD_REPLACE, name, new))
|
|
|
|
continue
|
|
|
|
|
|
|
|
# We used to convert to sets and use difference to calculate
|
|
|
|
# the changes but this did not preserve order which is important
|
|
|
|
# particularly for schema
|
|
|
|
adds = [value for value in new if value not in old]
|
|
|
|
dels = [value for value in old if value not in new]
|
2015-01-26 10:33:50 -06:00
|
|
|
if adds and self.conn.get_attribute_single_value(name):
|
2013-12-10 04:45:10 -06:00
|
|
|
if len(adds) > 1:
|
|
|
|
raise errors.OnlyOneValueAllowed(attr=name)
|
|
|
|
modlist.append((ldap.MOD_REPLACE, name, adds))
|
|
|
|
else:
|
ipaldap: avoid invalid modlist when attribute encoding differs
ipaldap does not take into account the possibility of the attribute
encoding returned by python-ldap differing from the attribute
encoding produced by FreeIPA. In particular this can occur with DNs
with special characters that require escaping. For example,
python-ldap (or the underlying LDAP library) escapes special
characters using hex encoding:
CN=Test Sub-CA 201604041620,OU=ftweedal,O=Red Hat\2C Inc.,L=Brisbane,C=AU
Whereas FreeIPA, when encoding the DN, escapes the character
directly:
CN=Test Sub-CA 201604041620,OU=ftweedal,O=Red Hat\, Inc.,L=Brisbane,C=AU
Therefore it is possible to generate an invalid modlist. For
example, during external CA certificate renewal, if the issuer DN
includes a comma in one of the attribute values (as above), an
invalid modlist will be generated:
[ (ldap.MOD_ADD, 'ipacaissuerdn',
[b'CN=Test Sub-CA 201604041620,OU=ftweedal,O=Red Hat\, Inc.,L=Brisbane,C=AU'])
, (ldap.MOD_DELETE, 'ipacaissuerdn',
[b'CN=Test Sub-CA 201604041620,OU=ftweedal,O=Red Hat\2C Inc.,L=Brisbane,C=AU'])
]
Although encoded differently, these are the same value. If this
modification is applied to the object, attributeOrValueExists (error
20) occurs.
To avoid the issue, put deletes before adds in the modlist. If a
value is present (with different encodings) as both an addition and
a deletion, it must be because the original object contained the
value with a different encoding. Therefore it is safe to delete it,
then add it back.
Note that the modlist is not optimal. In the simplest case (like
above example), there should be no modification to perform. It is
considerably more complex (and more computation) to implement this
because the raw attribute values must be decoded before comparison.
Fixes: https://pagure.io/freeipa/issue/7750
Reviewed-By: Christian Heimes <cheimes@redhat.com>
2018-11-05 21:17:17 -06:00
|
|
|
# dels before adds, in case the same value occurs in
|
|
|
|
# both due to encoding differences
|
|
|
|
# (https://pagure.io/freeipa/issue/7750)
|
2013-12-10 04:45:10 -06:00
|
|
|
if dels:
|
|
|
|
modlist.append((ldap.MOD_DELETE, name, dels))
|
ipaldap: avoid invalid modlist when attribute encoding differs
ipaldap does not take into account the possibility of the attribute
encoding returned by python-ldap differing from the attribute
encoding produced by FreeIPA. In particular this can occur with DNs
with special characters that require escaping. For example,
python-ldap (or the underlying LDAP library) escapes special
characters using hex encoding:
CN=Test Sub-CA 201604041620,OU=ftweedal,O=Red Hat\2C Inc.,L=Brisbane,C=AU
Whereas FreeIPA, when encoding the DN, escapes the character
directly:
CN=Test Sub-CA 201604041620,OU=ftweedal,O=Red Hat\, Inc.,L=Brisbane,C=AU
Therefore it is possible to generate an invalid modlist. For
example, during external CA certificate renewal, if the issuer DN
includes a comma in one of the attribute values (as above), an
invalid modlist will be generated:
[ (ldap.MOD_ADD, 'ipacaissuerdn',
[b'CN=Test Sub-CA 201604041620,OU=ftweedal,O=Red Hat\, Inc.,L=Brisbane,C=AU'])
, (ldap.MOD_DELETE, 'ipacaissuerdn',
[b'CN=Test Sub-CA 201604041620,OU=ftweedal,O=Red Hat\2C Inc.,L=Brisbane,C=AU'])
]
Although encoded differently, these are the same value. If this
modification is applied to the object, attributeOrValueExists (error
20) occurs.
To avoid the issue, put deletes before adds in the modlist. If a
value is present (with different encodings) as both an addition and
a deletion, it must be because the original object contained the
value with a different encoding. Therefore it is safe to delete it,
then add it back.
Note that the modlist is not optimal. In the simplest case (like
above example), there should be no modification to perform. It is
considerably more complex (and more computation) to implement this
because the raw attribute values must be decoded before comparison.
Fixes: https://pagure.io/freeipa/issue/7750
Reviewed-By: Christian Heimes <cheimes@redhat.com>
2018-11-05 21:17:17 -06:00
|
|
|
if adds:
|
|
|
|
modlist.append((ldap.MOD_ADD, name, adds))
|
2013-12-10 04:45:10 -06:00
|
|
|
|
|
|
|
# Usually the modlist order does not matter.
|
|
|
|
# However, for schema updates, we want 'attributetypes' before
|
|
|
|
# 'objectclasses'.
|
|
|
|
# A simple sort will ensure this.
|
|
|
|
modlist.sort(key=lambda m: m[1].lower() != 'attributetypes')
|
|
|
|
|
|
|
|
return modlist
|
|
|
|
|
2013-01-31 05:19:02 -06:00
|
|
|
def __iter__(self):
|
2014-10-23 08:44:40 -05:00
|
|
|
return iter(self._nice)
|
2013-02-26 04:27:55 -06:00
|
|
|
|
|
|
|
|
2018-07-04 03:07:49 -05:00
|
|
|
class LDAPEntryView(MutableMapping):
|
2013-02-27 02:16:49 -06:00
|
|
|
__slots__ = ('_entry',)
|
|
|
|
|
|
|
|
def __init__(self, entry):
|
|
|
|
assert isinstance(entry, LDAPEntry)
|
|
|
|
self._entry = entry
|
|
|
|
|
|
|
|
def __delitem__(self, name):
|
|
|
|
del self._entry[name]
|
|
|
|
|
|
|
|
def clear(self):
|
|
|
|
self._entry.clear()
|
|
|
|
|
|
|
|
def __iter__(self):
|
Use Python3-compatible dict method names
Python 2 has keys()/values()/items(), which return lists,
iterkeys()/itervalues()/iteritems(), which return iterators,
and viewkeys()/viewvalues()/viewitems() which return views.
Python 3 has only keys()/values()/items(), which return views.
To get iterators, one can use iter() or a for loop/comprehension;
for lists there's the list() constructor.
When iterating through the entire dict, without modifying the dict,
the difference between Python 2's items() and iteritems() is
negligible, especially on small dicts (the main overhead is
extra memory, not CPU time). In the interest of simpler code,
this patch changes many instances of iteritems() to items(),
iterkeys() to keys() etc.
In other cases, helpers like six.itervalues are used.
Reviewed-By: Christian Heimes <cheimes@redhat.com>
Reviewed-By: Jan Cholasta <jcholast@redhat.com>
2015-08-11 06:51:14 -05:00
|
|
|
return iter(self._entry)
|
2013-02-27 02:16:49 -06:00
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
return len(self._entry)
|
|
|
|
|
|
|
|
def __contains__(self, name):
|
|
|
|
return name in self._entry
|
|
|
|
|
|
|
|
def has_key(self, name):
|
|
|
|
return name in self
|
|
|
|
|
|
|
|
class RawLDAPEntryView(LDAPEntryView):
|
|
|
|
def __getitem__(self, name):
|
|
|
|
return self._entry._get_raw(name)
|
|
|
|
|
|
|
|
def __setitem__(self, name, value):
|
|
|
|
self._entry._set_raw(name, value)
|
|
|
|
|
2013-09-10 05:20:24 -05:00
|
|
|
class SingleValueLDAPEntryView(LDAPEntryView):
|
|
|
|
def __getitem__(self, name):
|
|
|
|
value = self._entry[name]
|
|
|
|
if not isinstance(value, list):
|
|
|
|
# FIXME: remove when we enforce lists
|
|
|
|
return value
|
|
|
|
elif not value:
|
|
|
|
return None
|
|
|
|
elif len(value) == 1:
|
|
|
|
return value[0]
|
|
|
|
else:
|
|
|
|
raise ValueError(
|
|
|
|
'%s has %s values, one expected' % (name, len(value)))
|
|
|
|
|
|
|
|
def __setitem__(self, name, value):
|
|
|
|
if value is None:
|
|
|
|
self._entry[name] = None
|
|
|
|
else:
|
|
|
|
self._entry[name] = [value]
|
|
|
|
|
2013-01-31 05:19:02 -06:00
|
|
|
|
2018-09-26 04:59:50 -05:00
|
|
|
class LDAPClient:
|
2013-01-31 05:19:02 -06:00
|
|
|
"""LDAP backend class
|
|
|
|
|
|
|
|
This class abstracts a LDAP connection, providing methods that work with
|
|
|
|
LADPEntries.
|
|
|
|
|
2015-01-26 10:33:50 -06:00
|
|
|
The purpose of this class is to provide a boundary between IPA and
|
|
|
|
python-ldap. In IPA we use IPA defined types because they are
|
|
|
|
richer and are designed to meet our needs. We also require that we
|
|
|
|
consistently use those types without exception. On the other hand
|
|
|
|
python-ldap uses different types. The goal is to be able to have
|
|
|
|
IPA code call python-ldap methods using the types native to
|
|
|
|
IPA. This class accomplishes that goal by exposing python-ldap
|
|
|
|
methods which take IPA types, convert them to python-ldap types,
|
|
|
|
call python-ldap, and then convert the results returned by
|
|
|
|
python-ldap into IPA types.
|
2013-01-31 05:19:02 -06:00
|
|
|
"""
|
|
|
|
|
|
|
|
# rules for generating filters from entries
|
|
|
|
MATCH_ANY = '|' # (|(filter1)(filter2))
|
|
|
|
MATCH_ALL = '&' # (&(filter1)(filter2))
|
|
|
|
MATCH_NONE = '!' # (!(filter1)(filter2))
|
|
|
|
|
|
|
|
# search scope for find_entries()
|
|
|
|
SCOPE_BASE = ldap.SCOPE_BASE
|
|
|
|
SCOPE_ONELEVEL = ldap.SCOPE_ONELEVEL
|
|
|
|
SCOPE_SUBTREE = ldap.SCOPE_SUBTREE
|
|
|
|
|
2015-01-26 10:33:50 -06:00
|
|
|
_SYNTAX_MAPPING = {
|
2015-09-11 07:02:13 -05:00
|
|
|
'1.3.6.1.4.1.1466.115.121.1.1' : bytes, # ACI item
|
|
|
|
'1.3.6.1.4.1.1466.115.121.1.4' : bytes, # Audio
|
|
|
|
'1.3.6.1.4.1.1466.115.121.1.5' : bytes, # Binary
|
|
|
|
'1.3.6.1.4.1.1466.115.121.1.8' : bytes, # Certificate
|
|
|
|
'1.3.6.1.4.1.1466.115.121.1.9' : bytes, # Certificate List
|
|
|
|
'1.3.6.1.4.1.1466.115.121.1.10' : bytes, # Certificate Pair
|
2015-01-26 10:33:50 -06:00
|
|
|
'1.3.6.1.4.1.1466.115.121.1.12' : DN, # Distinguished Name
|
2015-09-11 07:02:13 -05:00
|
|
|
'1.3.6.1.4.1.1466.115.121.1.23' : bytes, # Fax
|
2015-01-26 10:33:50 -06:00
|
|
|
'1.3.6.1.4.1.1466.115.121.1.24' : datetime.datetime,
|
2015-09-11 07:02:13 -05:00
|
|
|
'1.3.6.1.4.1.1466.115.121.1.28' : bytes, # JPEG
|
|
|
|
'1.3.6.1.4.1.1466.115.121.1.40' : bytes, # OctetString (same as Binary)
|
|
|
|
'1.3.6.1.4.1.1466.115.121.1.49' : bytes, # Supported Algorithm
|
|
|
|
'1.3.6.1.4.1.1466.115.121.1.51' : bytes, # Teletext Terminal Identifier
|
2015-01-26 10:33:50 -06:00
|
|
|
|
|
|
|
'2.16.840.1.113730.3.8.3.3' : DN, # enrolledBy
|
|
|
|
'2.16.840.1.113730.3.8.3.18' : DN, # managedBy
|
|
|
|
'2.16.840.1.113730.3.8.3.5' : DN, # memberUser
|
|
|
|
'2.16.840.1.113730.3.8.3.7' : DN, # memberHost
|
|
|
|
'2.16.840.1.113730.3.8.3.20' : DN, # memberService
|
|
|
|
'2.16.840.1.113730.3.8.11.4' : DN, # ipaNTFallbackPrimaryGroup
|
|
|
|
'2.16.840.1.113730.3.8.11.21' : DN, # ipaAllowToImpersonate
|
|
|
|
'2.16.840.1.113730.3.8.11.22' : DN, # ipaAllowedTarget
|
|
|
|
'2.16.840.1.113730.3.8.7.1' : DN, # memberAllowCmd
|
|
|
|
'2.16.840.1.113730.3.8.7.2' : DN, # memberDenyCmd
|
|
|
|
|
|
|
|
'2.16.840.1.113719.1.301.4.14.1' : DN, # krbRealmReferences
|
|
|
|
'2.16.840.1.113719.1.301.4.17.1' : DN, # krbKdcServers
|
|
|
|
'2.16.840.1.113719.1.301.4.18.1' : DN, # krbPwdServers
|
|
|
|
'2.16.840.1.113719.1.301.4.26.1' : DN, # krbPrincipalReferences
|
|
|
|
'2.16.840.1.113719.1.301.4.29.1' : DN, # krbAdmServers
|
|
|
|
'2.16.840.1.113719.1.301.4.36.1' : DN, # krbPwdPolicyReference
|
|
|
|
'2.16.840.1.113719.1.301.4.40.1' : DN, # krbTicketPolicyReference
|
|
|
|
'2.16.840.1.113719.1.301.4.41.1' : DN, # krbSubTrees
|
|
|
|
'2.16.840.1.113719.1.301.4.52.1' : DN, # krbObjectReferences
|
|
|
|
'2.16.840.1.113719.1.301.4.53.1' : DN, # krbPrincContainerRef
|
|
|
|
}
|
|
|
|
|
|
|
|
# In most cases we lookup the syntax from the schema returned by
|
|
|
|
# the server. However, sometimes attributes may not be defined in
|
|
|
|
# the schema (e.g. extensibleObject which permits undefined
|
|
|
|
# attributes), or the schema was incorrectly defined (i.e. giving
|
|
|
|
# an attribute the syntax DirectoryString when in fact it's really
|
|
|
|
# a DN). This (hopefully sparse) table allows us to trap these
|
|
|
|
# anomalies and force them to be the syntax we know to be in use.
|
|
|
|
#
|
|
|
|
# FWIW, many entries under cn=config are undefined :-(
|
|
|
|
|
|
|
|
_SYNTAX_OVERRIDE = CIDict({
|
|
|
|
'managedtemplate': DN,
|
|
|
|
'managedbase': DN,
|
2015-03-31 03:59:37 -05:00
|
|
|
'memberindirect': DN,
|
|
|
|
'memberofindirect':DN,
|
2015-01-26 10:33:50 -06:00
|
|
|
'originscope': DN,
|
|
|
|
'idnsname': DNSName,
|
|
|
|
'idnssoamname': DNSName,
|
|
|
|
'idnssoarname': DNSName,
|
|
|
|
'dnszoneidnsname': DNSName,
|
2016-06-23 11:23:00 -05:00
|
|
|
'krbcanonicalname': Principal,
|
|
|
|
'krbprincipalname': Principal,
|
2017-07-03 10:10:34 -05:00
|
|
|
'usercertificate': crypto_x509.Certificate,
|
|
|
|
'usercertificate;binary': crypto_x509.Certificate,
|
|
|
|
'cACertificate': crypto_x509.Certificate,
|
|
|
|
'cACertificate;binary': crypto_x509.Certificate,
|
2015-01-26 10:33:50 -06:00
|
|
|
'nsds5replicalastupdatestart': unicode,
|
|
|
|
'nsds5replicalastupdateend': unicode,
|
|
|
|
'nsds5replicalastinitstart': unicode,
|
|
|
|
'nsds5replicalastinitend': unicode,
|
|
|
|
})
|
|
|
|
_SINGLE_VALUE_OVERRIDE = CIDict({
|
|
|
|
'nsslapd-ssl-check-hostname': True,
|
|
|
|
'nsslapd-lookthroughlimit': True,
|
|
|
|
'nsslapd-idlistscanlimit': True,
|
|
|
|
'nsslapd-anonlimitsdn': True,
|
|
|
|
'nsslapd-minssf-exclude-rootdse': True,
|
2020-05-08 05:01:03 -05:00
|
|
|
'nsslapd-enable-upgrade-hash': True,
|
2020-09-24 05:32:37 -05:00
|
|
|
'nsslapd-db-locks': True,
|
2020-11-04 05:39:23 -06:00
|
|
|
'nsslapd-logging-hr-timestamps-enabled': True,
|
2015-01-26 10:33:50 -06:00
|
|
|
})
|
|
|
|
|
2015-11-18 03:31:05 -06:00
|
|
|
time_limit = -1.0 # unlimited
|
|
|
|
size_limit = 0 # unlimited
|
|
|
|
|
2015-01-26 09:16:01 -06:00
|
|
|
def __init__(self, ldap_uri, start_tls=False, force_schema_updates=False,
|
2016-11-01 08:52:33 -05:00
|
|
|
no_schema=False, decode_attrs=True, cacert=None,
|
2018-02-21 07:35:25 -06:00
|
|
|
sasl_nocanon=True):
|
2015-01-26 10:33:50 -06:00
|
|
|
"""Create LDAPClient object.
|
|
|
|
|
|
|
|
:param ldap_uri: The LDAP URI to connect to
|
|
|
|
:param start_tls: Use STARTTLS
|
|
|
|
:param force_schema_updates:
|
|
|
|
If true, this object will always request a new schema from the
|
|
|
|
server. If false, a cached schema will be reused if it exists.
|
|
|
|
|
|
|
|
Generally, it should be true if the API context is 'installer' or
|
|
|
|
'updates', but it must be given explicitly since the API object
|
|
|
|
is not always available
|
|
|
|
:param no_schema: If true, schema is never requested from the server.
|
|
|
|
:param decode_attrs:
|
|
|
|
If true, attributes are decoded to Python types according to their
|
|
|
|
syntax.
|
|
|
|
"""
|
2017-02-23 04:15:52 -06:00
|
|
|
if ldap_uri is not None:
|
2018-11-30 03:28:02 -06:00
|
|
|
# special case for ldap2 server plugin
|
2017-02-23 04:15:52 -06:00
|
|
|
self.ldap_uri = ldap_uri
|
2018-11-30 03:28:02 -06:00
|
|
|
assert self.protocol in {'ldaps', 'ldapi', 'ldap'}
|
2015-01-26 09:16:01 -06:00
|
|
|
self._start_tls = start_tls
|
|
|
|
self._force_schema_updates = force_schema_updates
|
|
|
|
self._no_schema = no_schema
|
|
|
|
self._decode_attrs = decode_attrs
|
2016-11-01 08:52:33 -05:00
|
|
|
self._cacert = cacert
|
|
|
|
self._sasl_nocanon = sasl_nocanon
|
|
|
|
|
2015-01-26 10:33:50 -06:00
|
|
|
self._has_schema = False
|
|
|
|
self._schema = None
|
2013-01-31 05:19:02 -06:00
|
|
|
|
2018-11-30 03:28:02 -06:00
|
|
|
if ldap_uri is not None:
|
|
|
|
self._conn = self._connect()
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def from_realm(cls, realm_name, **kwargs):
|
|
|
|
"""Create a LDAPI connection to local 389-DS instance
|
|
|
|
"""
|
|
|
|
uri = realm_to_ldapi_uri(realm_name)
|
|
|
|
return cls(uri, start_tls=False, cacert=None, **kwargs)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def from_hostname_secure(cls, hostname, cacert=paths.IPA_CA_CRT,
|
|
|
|
start_tls=True, **kwargs):
|
|
|
|
"""Create LDAP or LDAPS connection to a remote 389-DS instance
|
|
|
|
|
|
|
|
This constructor is opinionated and doesn't let you shoot yourself in
|
|
|
|
the foot. It always creates a secure connection. By default it
|
|
|
|
returns a LDAP connection to port 389 and performs STARTTLS using the
|
|
|
|
default CA cert. With start_tls=False, it creates a LDAPS connection
|
|
|
|
to port 636 instead.
|
|
|
|
|
|
|
|
Note: Microsoft AD does not support SASL encryption and integrity
|
|
|
|
verification with a TLS connection. For AD, use a plain connection
|
|
|
|
with GSSAPI and a MIN_SSF >= 56. SASL GSSAPI and SASL GSS SPNEGO
|
|
|
|
ensure data integrity and confidentiality with SSF > 1. Also see
|
|
|
|
https://msdn.microsoft.com/en-us/library/cc223500.aspx
|
|
|
|
"""
|
|
|
|
if start_tls:
|
|
|
|
uri = 'ldap://%s' % format_netloc(hostname, 389)
|
|
|
|
else:
|
|
|
|
uri = 'ldaps://%s' % format_netloc(hostname, 636)
|
|
|
|
return cls(uri, start_tls=start_tls, cacert=cacert, **kwargs)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def from_hostname_plain(cls, hostname, **kwargs):
|
|
|
|
"""Create a plain LDAP connection with TLS/SSL
|
|
|
|
|
|
|
|
Note: A plain TLS connection should only be used in combination with
|
|
|
|
GSSAPI bind.
|
|
|
|
"""
|
|
|
|
assert 'start_tls' not in kwargs
|
|
|
|
assert 'cacert' not in kwargs
|
|
|
|
uri = 'ldap://%s' % format_netloc(hostname, 389)
|
|
|
|
return cls(uri, **kwargs)
|
2015-01-26 09:16:01 -06:00
|
|
|
|
2016-11-01 08:52:33 -05:00
|
|
|
def __str__(self):
|
|
|
|
return self.ldap_uri
|
|
|
|
|
|
|
|
def modify_s(self, dn, modlist):
|
|
|
|
# FIXME: for backwards compatibility only
|
|
|
|
assert isinstance(dn, DN)
|
|
|
|
dn = str(dn)
|
2017-01-27 10:00:42 -06:00
|
|
|
modlist = [(a, b, self.encode(c)) for a, b, c in modlist]
|
2016-11-01 08:52:33 -05:00
|
|
|
return self.conn.modify_s(dn, modlist)
|
|
|
|
|
2015-01-26 09:16:01 -06:00
|
|
|
@property
|
|
|
|
def conn(self):
|
|
|
|
return self._conn
|
2013-01-31 05:19:02 -06:00
|
|
|
|
2018-11-30 03:28:02 -06:00
|
|
|
@property
|
|
|
|
def protocol(self):
|
|
|
|
if self.ldap_uri:
|
|
|
|
return self.ldap_uri.split('://', 1)[0]
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
2015-01-26 10:33:50 -06:00
|
|
|
def _get_schema(self):
|
|
|
|
if self._no_schema:
|
|
|
|
return None
|
|
|
|
|
|
|
|
if not self._has_schema:
|
|
|
|
try:
|
|
|
|
schema = schema_cache.get_schema(
|
2015-01-20 06:36:14 -06:00
|
|
|
self.ldap_uri, self.conn,
|
2015-01-26 10:33:50 -06:00
|
|
|
force_update=self._force_schema_updates)
|
|
|
|
except (errors.ExecutionError, IndexError):
|
|
|
|
schema = None
|
|
|
|
|
|
|
|
# bypass ldap2's locking
|
|
|
|
object.__setattr__(self, '_schema', schema)
|
|
|
|
object.__setattr__(self, '_has_schema', True)
|
|
|
|
|
|
|
|
return self._schema
|
|
|
|
|
|
|
|
def _flush_schema(self):
|
|
|
|
'''
|
|
|
|
Force this instance to forget it's cached schema and reacquire
|
|
|
|
it from the schema cache.
|
|
|
|
'''
|
|
|
|
|
|
|
|
# Currently this is called during bind operations to assure
|
|
|
|
# we're working with valid schema for a specific
|
|
|
|
# connection. This causes self._get_schema() to query the
|
|
|
|
# schema cache for the server's schema passing along a flag
|
|
|
|
# indicating if we're in a context that requires freshly
|
|
|
|
# loading the schema vs. returning the last cached version of
|
|
|
|
# the schema. If we're in a mode that permits use of
|
|
|
|
# previously cached schema the flush and reacquire is a very
|
|
|
|
# low cost operation.
|
|
|
|
#
|
|
|
|
# The schema is reacquired whenever this object is
|
|
|
|
# instantiated or when binding occurs. The schema is not
|
|
|
|
# reacquired for operations during a bound connection, it is
|
|
|
|
# presumed schema cannot change during this interval. This
|
|
|
|
# provides for maximum efficiency in contexts which do need
|
|
|
|
# schema refreshing by only peforming the refresh inbetween
|
|
|
|
# logical operations that have the potential to cause a schema
|
|
|
|
# change.
|
|
|
|
|
|
|
|
# bypass ldap2's locking
|
|
|
|
object.__setattr__(self, '_has_schema', False)
|
|
|
|
object.__setattr__(self, '_schema', None)
|
|
|
|
|
|
|
|
def get_attribute_type(self, name_or_oid):
|
|
|
|
if not self._decode_attrs:
|
2015-09-11 07:02:13 -05:00
|
|
|
return bytes
|
2015-01-26 10:33:50 -06:00
|
|
|
|
2015-10-14 08:02:51 -05:00
|
|
|
if six.PY2:
|
|
|
|
if isinstance(name_or_oid, unicode):
|
|
|
|
name_or_oid = name_or_oid.encode('utf-8')
|
2015-01-26 10:33:50 -06:00
|
|
|
|
|
|
|
# Is this a special case attribute?
|
|
|
|
if name_or_oid in self._SYNTAX_OVERRIDE:
|
|
|
|
return self._SYNTAX_OVERRIDE[name_or_oid]
|
|
|
|
|
|
|
|
schema = self._get_schema()
|
|
|
|
if schema is not None:
|
|
|
|
# Try to lookup the syntax in the schema returned by the server
|
|
|
|
obj = schema.get_obj(ldap.schema.AttributeType, name_or_oid)
|
|
|
|
if obj is not None and obj.syntax in self._SYNTAX_MAPPING:
|
|
|
|
return self._SYNTAX_MAPPING[obj.syntax]
|
|
|
|
|
|
|
|
return unicode
|
|
|
|
|
|
|
|
def has_dn_syntax(self, name_or_oid):
|
|
|
|
"""
|
|
|
|
Check the schema to see if the attribute uses DN syntax.
|
|
|
|
|
|
|
|
Returns True/False
|
|
|
|
"""
|
|
|
|
return self.get_attribute_type(name_or_oid) is DN
|
|
|
|
|
|
|
|
def get_attribute_single_value(self, name_or_oid):
|
|
|
|
"""
|
|
|
|
Check the schema to see if the attribute is single-valued.
|
|
|
|
|
|
|
|
If the attribute is in the schema then returns True/False
|
|
|
|
|
|
|
|
If there is a problem loading the schema or the attribute is
|
|
|
|
not in the schema return None
|
|
|
|
"""
|
2016-04-29 10:13:08 -05:00
|
|
|
if six.PY2 and isinstance(name_or_oid, unicode):
|
2015-01-26 10:33:50 -06:00
|
|
|
name_or_oid = name_or_oid.encode('utf-8')
|
|
|
|
|
|
|
|
if name_or_oid in self._SINGLE_VALUE_OVERRIDE:
|
|
|
|
return self._SINGLE_VALUE_OVERRIDE[name_or_oid]
|
|
|
|
|
|
|
|
schema = self._get_schema()
|
|
|
|
if schema is not None:
|
|
|
|
obj = schema.get_obj(ldap.schema.AttributeType, name_or_oid)
|
|
|
|
if obj is not None:
|
|
|
|
return obj.single_value
|
|
|
|
|
|
|
|
return None
|
2015-01-14 10:49:35 -06:00
|
|
|
|
2015-01-14 09:51:52 -06:00
|
|
|
def encode(self, val):
|
2015-01-26 10:33:50 -06:00
|
|
|
"""
|
2017-07-03 10:10:34 -05:00
|
|
|
Encode attribute value to LDAP representation (str/bytes).
|
2015-01-26 10:33:50 -06:00
|
|
|
"""
|
|
|
|
# Booleans are both an instance of bool and int, therefore
|
|
|
|
# test for bool before int otherwise the int clause will be
|
|
|
|
# entered for a boolean value instead of the boolean clause.
|
|
|
|
if isinstance(val, bool):
|
|
|
|
if val:
|
2017-02-10 10:13:15 -06:00
|
|
|
return b'TRUE'
|
2015-01-26 10:33:50 -06:00
|
|
|
else:
|
2017-02-10 10:13:15 -06:00
|
|
|
return b'FALSE'
|
2018-09-26 05:33:30 -05:00
|
|
|
elif isinstance(val, (unicode, int, Decimal, DN, Principal)):
|
2018-09-26 05:39:56 -05:00
|
|
|
return str(val).encode('utf-8')
|
2015-01-26 10:33:50 -06:00
|
|
|
elif isinstance(val, DNSName):
|
2017-02-06 11:42:08 -06:00
|
|
|
return val.to_text().encode('ascii')
|
2015-09-11 07:02:13 -05:00
|
|
|
elif isinstance(val, bytes):
|
2015-01-26 10:33:50 -06:00
|
|
|
return val
|
|
|
|
elif isinstance(val, list):
|
|
|
|
return [self.encode(m) for m in val]
|
|
|
|
elif isinstance(val, tuple):
|
|
|
|
return tuple(self.encode(m) for m in val)
|
|
|
|
elif isinstance(val, dict):
|
2017-01-09 12:01:29 -06:00
|
|
|
# key in dict must be str not bytes
|
|
|
|
dct = dict((k, self.encode(v)) for k, v in val.items())
|
2015-01-26 10:33:50 -06:00
|
|
|
return dct
|
|
|
|
elif isinstance(val, datetime.datetime):
|
2017-06-02 07:47:25 -05:00
|
|
|
return val.strftime(LDAP_GENERALIZED_TIME_FORMAT).encode('utf-8')
|
2017-07-03 10:10:34 -05:00
|
|
|
elif isinstance(val, crypto_x509.Certificate):
|
|
|
|
return val.public_bytes(x509.Encoding.DER)
|
2015-01-26 10:33:50 -06:00
|
|
|
elif val is None:
|
|
|
|
return None
|
|
|
|
else:
|
|
|
|
raise TypeError("attempt to pass unsupported type to ldap, value=%s type=%s" %(val, type(val)))
|
2015-01-14 09:51:52 -06:00
|
|
|
|
|
|
|
def decode(self, val, attr):
|
2015-01-26 10:33:50 -06:00
|
|
|
"""
|
2017-07-03 10:10:34 -05:00
|
|
|
Decode attribute value from LDAP representation (str/bytes).
|
2015-01-26 10:33:50 -06:00
|
|
|
"""
|
2015-09-11 07:02:13 -05:00
|
|
|
if isinstance(val, bytes):
|
2015-01-26 10:33:50 -06:00
|
|
|
target_type = self.get_attribute_type(attr)
|
|
|
|
try:
|
2015-09-11 07:02:13 -05:00
|
|
|
if target_type is bytes:
|
2015-01-26 10:33:50 -06:00
|
|
|
return val
|
|
|
|
elif target_type is unicode:
|
|
|
|
return val.decode('utf-8')
|
|
|
|
elif target_type is datetime.datetime:
|
2017-01-13 05:16:28 -06:00
|
|
|
return datetime.datetime.strptime(
|
|
|
|
val.decode('utf-8'), LDAP_GENERALIZED_TIME_FORMAT)
|
2015-08-31 02:26:27 -05:00
|
|
|
elif target_type is DNSName:
|
2017-01-13 05:16:28 -06:00
|
|
|
return DNSName.from_text(val.decode('utf-8'))
|
|
|
|
elif target_type in (DN, Principal):
|
|
|
|
return target_type(val.decode('utf-8'))
|
2017-07-03 10:10:34 -05:00
|
|
|
elif target_type is crypto_x509.Certificate:
|
|
|
|
return x509.load_der_x509_certificate(val)
|
2015-01-26 10:33:50 -06:00
|
|
|
else:
|
|
|
|
return target_type(val)
|
2016-10-07 08:07:49 -05:00
|
|
|
except Exception:
|
2015-01-26 10:33:50 -06:00
|
|
|
msg = 'unable to convert the attribute %r value %r to type %s' % (attr, val, target_type)
|
2017-05-23 11:35:57 -05:00
|
|
|
logger.error('%s', msg)
|
2015-01-26 10:33:50 -06:00
|
|
|
raise ValueError(msg)
|
|
|
|
elif isinstance(val, list):
|
|
|
|
return [self.decode(m, attr) for m in val]
|
|
|
|
elif isinstance(val, tuple):
|
|
|
|
return tuple(self.decode(m, attr) for m in val)
|
|
|
|
elif isinstance(val, dict):
|
2017-01-13 06:04:07 -06:00
|
|
|
dct = {
|
|
|
|
k.decode('utf-8'): self.decode(v, k) for k, v in val.items()
|
|
|
|
}
|
2015-01-26 10:33:50 -06:00
|
|
|
return dct
|
|
|
|
elif val is None:
|
|
|
|
return None
|
|
|
|
else:
|
|
|
|
raise TypeError("attempt to pass unsupported type from ldap, value=%s type=%s" %(val, type(val)))
|
2015-01-14 09:51:52 -06:00
|
|
|
|
|
|
|
def _convert_result(self, result):
|
|
|
|
'''
|
|
|
|
result is a python-ldap result tuple of the form (dn, attrs),
|
|
|
|
where dn is a string containing the dn (distinguished name) of
|
|
|
|
the entry, and attrs is a dictionary containing the attributes
|
|
|
|
associated with the entry. The keys of attrs are strings, and
|
|
|
|
the associated values are lists of strings.
|
|
|
|
|
|
|
|
We convert the tuple to an LDAPEntry object.
|
|
|
|
'''
|
|
|
|
|
|
|
|
ipa_result = []
|
|
|
|
for dn_tuple in result:
|
|
|
|
original_dn = dn_tuple[0]
|
|
|
|
original_attrs = dn_tuple[1]
|
|
|
|
|
|
|
|
# original_dn is None if referral instead of an entry was
|
|
|
|
# returned from the LDAP server, we need to skip this item
|
|
|
|
if original_dn is None:
|
|
|
|
log_msg = 'Referral entry ignored: {ref}'\
|
|
|
|
.format(ref=str(original_attrs))
|
2017-05-23 11:35:57 -05:00
|
|
|
logger.debug('%s', log_msg)
|
2015-01-14 09:51:52 -06:00
|
|
|
|
|
|
|
continue
|
|
|
|
|
2015-01-14 10:49:35 -06:00
|
|
|
ipa_entry = LDAPEntry(self, DN(original_dn))
|
2015-01-14 09:51:52 -06:00
|
|
|
|
|
|
|
for attr, original_values in original_attrs.items():
|
|
|
|
ipa_entry.raw[attr] = original_values
|
|
|
|
ipa_entry.reset_modlist()
|
|
|
|
|
|
|
|
ipa_result.append(ipa_entry)
|
|
|
|
|
|
|
|
if _debug_log_ldap:
|
2017-05-23 11:35:57 -05:00
|
|
|
logger.debug('ldap.result: %s', ipa_result)
|
2015-01-14 09:51:52 -06:00
|
|
|
return ipa_result
|
|
|
|
|
2013-01-31 05:19:02 -06:00
|
|
|
@contextlib.contextmanager
|
|
|
|
def error_handler(self, arg_desc=None):
|
|
|
|
"""Context manager that handles LDAPErrors
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
try:
|
|
|
|
yield
|
|
|
|
except ldap.TIMEOUT:
|
2013-01-31 07:26:38 -06:00
|
|
|
raise errors.DatabaseTimeout()
|
2015-07-30 09:49:29 -05:00
|
|
|
except ldap.LDAPError as e:
|
2013-01-31 05:19:02 -06:00
|
|
|
desc = e.args[0]['desc'].strip()
|
|
|
|
info = e.args[0].get('info', '').strip()
|
|
|
|
if arg_desc is not None:
|
|
|
|
info = "%s arguments: %s" % (info, arg_desc)
|
|
|
|
raise
|
|
|
|
except ldap.NO_SUCH_OBJECT:
|
|
|
|
raise errors.NotFound(reason=arg_desc or 'no such entry')
|
|
|
|
except ldap.ALREADY_EXISTS:
|
2018-07-10 07:03:28 -05:00
|
|
|
# entry already exists
|
2013-01-31 05:19:02 -06:00
|
|
|
raise errors.DuplicateEntry()
|
2018-07-10 07:03:28 -05:00
|
|
|
except ldap.TYPE_OR_VALUE_EXISTS:
|
|
|
|
# attribute type or attribute value already exists, usually only
|
|
|
|
# occurs, when two machines try to write at the same time.
|
|
|
|
raise errors.DuplicateEntry(message=desc)
|
2013-01-31 05:19:02 -06:00
|
|
|
except ldap.CONSTRAINT_VIOLATION:
|
|
|
|
# This error gets thrown by the uniqueness plugin
|
|
|
|
_msg = 'Another entry with the same attribute value already exists'
|
|
|
|
if info.startswith(_msg):
|
|
|
|
raise errors.DuplicateEntry()
|
|
|
|
else:
|
|
|
|
raise errors.DatabaseError(desc=desc, info=info)
|
|
|
|
except ldap.INSUFFICIENT_ACCESS:
|
|
|
|
raise errors.ACIError(info=info)
|
|
|
|
except ldap.INVALID_CREDENTIALS:
|
|
|
|
raise errors.ACIError(info="%s %s" % (info, desc))
|
2013-01-31 07:26:38 -06:00
|
|
|
except ldap.INAPPROPRIATE_AUTH:
|
|
|
|
raise errors.ACIError(info="%s: %s" % (desc, info))
|
2013-01-31 05:19:02 -06:00
|
|
|
except ldap.NO_SUCH_ATTRIBUTE:
|
|
|
|
# this is raised when a 'delete' attribute isn't found.
|
|
|
|
# it indicates the previous attribute was removed by another
|
|
|
|
# update, making the oldentry stale.
|
|
|
|
raise errors.MidairCollision()
|
|
|
|
except ldap.INVALID_SYNTAX:
|
|
|
|
raise errors.InvalidSyntax(attr=info)
|
|
|
|
except ldap.OBJECT_CLASS_VIOLATION:
|
|
|
|
raise errors.ObjectclassViolation(info=info)
|
|
|
|
except ldap.ADMINLIMIT_EXCEEDED:
|
2016-03-18 03:49:41 -05:00
|
|
|
raise errors.AdminLimitExceeded()
|
2013-01-31 05:19:02 -06:00
|
|
|
except ldap.SIZELIMIT_EXCEEDED:
|
2016-03-18 03:49:41 -05:00
|
|
|
raise errors.SizeLimitExceeded()
|
2013-01-31 05:19:02 -06:00
|
|
|
except ldap.TIMELIMIT_EXCEEDED:
|
2016-03-18 03:49:41 -05:00
|
|
|
raise errors.TimeLimitExceeded()
|
2013-01-31 05:19:02 -06:00
|
|
|
except ldap.NOT_ALLOWED_ON_RDN:
|
|
|
|
raise errors.NotAllowedOnRDN(attr=info)
|
|
|
|
except ldap.FILTER_ERROR:
|
|
|
|
raise errors.BadSearchFilter(info=info)
|
|
|
|
except ldap.NOT_ALLOWED_ON_NONLEAF:
|
|
|
|
raise errors.NotAllowedOnNonLeaf()
|
|
|
|
except ldap.SERVER_DOWN:
|
|
|
|
raise errors.NetworkError(uri=self.ldap_uri,
|
2013-01-31 07:26:38 -06:00
|
|
|
error=info)
|
2013-01-31 05:19:02 -06:00
|
|
|
except ldap.LOCAL_ERROR:
|
|
|
|
raise errors.ACIError(info=info)
|
|
|
|
except ldap.SUCCESS:
|
|
|
|
pass
|
2013-01-31 07:26:38 -06:00
|
|
|
except ldap.CONNECT_ERROR:
|
|
|
|
raise errors.DatabaseError(desc=desc, info=info)
|
2014-07-02 08:30:18 -05:00
|
|
|
except ldap.UNWILLING_TO_PERFORM:
|
|
|
|
raise errors.DatabaseError(desc=desc, info=info)
|
|
|
|
except ldap.AUTH_UNKNOWN:
|
|
|
|
raise errors.ACIError(info='%s (%s)' % (info,desc))
|
2015-07-30 09:49:29 -05:00
|
|
|
except ldap.LDAPError as e:
|
2013-01-31 05:19:02 -06:00
|
|
|
if 'NOT_ALLOWED_TO_DELEGATE' in info:
|
|
|
|
raise errors.ACIError(
|
|
|
|
info="KDC returned NOT_ALLOWED_TO_DELEGATE")
|
2017-05-23 11:35:57 -05:00
|
|
|
logger.debug(
|
|
|
|
'Unhandled LDAPError: %s: %s', type(e).__name__, str(e))
|
2013-01-31 05:19:02 -06:00
|
|
|
raise errors.DatabaseError(desc=desc, info=info)
|
|
|
|
|
2016-03-18 03:49:41 -05:00
|
|
|
@staticmethod
|
|
|
|
def handle_truncated_result(truncated):
|
|
|
|
if not truncated:
|
|
|
|
return
|
|
|
|
|
|
|
|
if truncated is TRUNCATED_ADMIN_LIMIT:
|
|
|
|
raise errors.AdminLimitExceeded()
|
|
|
|
elif truncated is TRUNCATED_SIZE_LIMIT:
|
|
|
|
raise errors.SizeLimitExceeded()
|
|
|
|
elif truncated is TRUNCATED_TIME_LIMIT:
|
|
|
|
raise errors.TimeLimitExceeded()
|
|
|
|
else:
|
|
|
|
raise errors.LimitsExceeded()
|
|
|
|
|
2013-01-31 05:19:02 -06:00
|
|
|
@property
|
|
|
|
def schema(self):
|
|
|
|
"""schema associated with this LDAP server"""
|
2015-01-26 10:33:50 -06:00
|
|
|
return self._get_schema()
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
def get_allowed_attributes(self, objectclasses, raise_on_unknown=False):
|
|
|
|
if self.schema is None:
|
|
|
|
return None
|
|
|
|
allowed_attributes = []
|
|
|
|
for oc in objectclasses:
|
|
|
|
obj = self.schema.get_obj(ldap.schema.ObjectClass, oc)
|
|
|
|
if obj is not None:
|
|
|
|
allowed_attributes += obj.must + obj.may
|
|
|
|
elif raise_on_unknown:
|
|
|
|
raise errors.NotFound(
|
|
|
|
reason=_('objectclass %s not found') % oc)
|
|
|
|
return [unicode(a).lower() for a in list(set(allowed_attributes))]
|
|
|
|
|
2015-01-26 09:16:01 -06:00
|
|
|
def __enter__(self):
|
|
|
|
return self
|
|
|
|
|
2016-10-05 10:42:32 -05:00
|
|
|
|
2015-01-26 09:16:01 -06:00
|
|
|
def __exit__(self, exc_type, exc_value, traceback):
|
|
|
|
self.close()
|
|
|
|
|
|
|
|
def close(self):
|
|
|
|
"""
|
|
|
|
Close the connection.
|
|
|
|
"""
|
2015-09-02 07:04:17 -05:00
|
|
|
self._conn = None
|
2015-01-26 09:16:01 -06:00
|
|
|
|
|
|
|
def _connect(self):
|
|
|
|
with self.error_handler():
|
2018-02-15 05:30:06 -06:00
|
|
|
conn = ldap_initialize(self.ldap_uri, cacertfile=self._cacert)
|
2018-02-21 07:35:25 -06:00
|
|
|
# SASL_NOCANON is set to ON in Fedora's default ldap.conf and
|
|
|
|
# in the ldap_initialize() function.
|
|
|
|
if not self._sasl_nocanon:
|
|
|
|
conn.set_option(ldap.OPT_X_SASL_NOCANON, ldap.OPT_OFF)
|
2016-11-01 08:52:33 -05:00
|
|
|
|
2018-11-30 03:28:02 -06:00
|
|
|
if self._start_tls and self.protocol == 'ldap':
|
|
|
|
# STARTTLS applies only to ldap:// connections
|
2015-09-02 07:04:17 -05:00
|
|
|
conn.start_tls_s()
|
2015-01-26 09:16:01 -06:00
|
|
|
|
2015-09-02 07:04:17 -05:00
|
|
|
return conn
|
2015-01-26 09:16:01 -06:00
|
|
|
|
2014-11-21 13:08:17 -06:00
|
|
|
def simple_bind(self, bind_dn, bind_password, server_controls=None,
|
2019-08-13 10:22:01 -05:00
|
|
|
client_controls=None, insecure_bind=False):
|
2014-11-21 13:08:17 -06:00
|
|
|
"""
|
|
|
|
Perform simple bind operation.
|
|
|
|
"""
|
2019-08-13 10:22:01 -05:00
|
|
|
if (self.protocol == 'ldap' and not self._start_tls and
|
|
|
|
bind_password and not insecure_bind):
|
|
|
|
# non-empty bind must use a secure connection unless
|
|
|
|
# insecure bind is explicitly enabled
|
2018-11-30 03:28:02 -06:00
|
|
|
raise ValueError('simple_bind over insecure LDAP connection')
|
2014-11-21 13:08:17 -06:00
|
|
|
with self.error_handler():
|
2015-01-26 10:33:50 -06:00
|
|
|
self._flush_schema()
|
2015-01-14 09:51:52 -06:00
|
|
|
assert isinstance(bind_dn, DN)
|
|
|
|
bind_dn = str(bind_dn)
|
|
|
|
bind_password = self.encode(bind_password)
|
2015-09-02 07:04:17 -05:00
|
|
|
self.conn.simple_bind_s(
|
2014-11-21 13:08:17 -06:00
|
|
|
bind_dn, bind_password, server_controls, client_controls)
|
|
|
|
|
2016-10-06 01:45:43 -05:00
|
|
|
def external_bind(self, server_controls=None, client_controls=None):
|
2014-11-21 13:08:17 -06:00
|
|
|
"""
|
|
|
|
Perform SASL bind operation using the SASL EXTERNAL mechanism.
|
|
|
|
"""
|
2016-10-06 01:45:43 -05:00
|
|
|
user_name = pwd.getpwuid(os.geteuid()).pw_name
|
2014-11-21 13:08:17 -06:00
|
|
|
with self.error_handler():
|
|
|
|
auth_tokens = ldap.sasl.external(user_name)
|
2015-01-26 10:33:50 -06:00
|
|
|
self._flush_schema()
|
2015-09-02 07:04:17 -05:00
|
|
|
self.conn.sasl_interactive_bind_s(
|
2015-01-14 09:51:52 -06:00
|
|
|
'', auth_tokens, server_controls, client_controls)
|
2014-11-21 13:08:17 -06:00
|
|
|
|
|
|
|
def gssapi_bind(self, server_controls=None, client_controls=None):
|
|
|
|
"""
|
|
|
|
Perform SASL bind operation using the SASL GSSAPI mechanism.
|
|
|
|
"""
|
|
|
|
with self.error_handler():
|
2018-11-30 03:28:02 -06:00
|
|
|
if self.protocol == 'ldapi':
|
2017-03-06 13:19:30 -06:00
|
|
|
auth_tokens = SASL_GSS_SPNEGO
|
|
|
|
else:
|
|
|
|
auth_tokens = SASL_GSSAPI
|
2015-01-26 10:33:50 -06:00
|
|
|
self._flush_schema()
|
2015-09-02 07:04:17 -05:00
|
|
|
self.conn.sasl_interactive_bind_s(
|
2015-01-14 09:51:52 -06:00
|
|
|
'', auth_tokens, server_controls, client_controls)
|
2014-11-21 13:08:17 -06:00
|
|
|
|
|
|
|
def unbind(self):
|
|
|
|
"""
|
|
|
|
Perform unbind operation.
|
|
|
|
"""
|
|
|
|
with self.error_handler():
|
2015-01-26 10:33:50 -06:00
|
|
|
self._flush_schema()
|
2015-09-02 07:04:17 -05:00
|
|
|
self.conn.unbind_s()
|
2014-11-21 13:08:17 -06:00
|
|
|
|
2013-01-31 05:19:02 -06:00
|
|
|
def make_dn_from_attr(self, attr, value, parent_dn=None):
|
|
|
|
"""
|
|
|
|
Make distinguished name from attribute.
|
|
|
|
|
|
|
|
Keyword arguments:
|
|
|
|
parent_dn -- DN of the parent entry (default '')
|
|
|
|
"""
|
|
|
|
if parent_dn is None:
|
|
|
|
parent_dn = DN()
|
|
|
|
|
|
|
|
if isinstance(value, (list, tuple)):
|
|
|
|
value = value[0]
|
|
|
|
|
|
|
|
return DN((attr, value), parent_dn)
|
|
|
|
|
|
|
|
def make_dn(self, entry_attrs, primary_key='cn', parent_dn=None):
|
|
|
|
"""
|
|
|
|
Make distinguished name from entry attributes.
|
|
|
|
|
|
|
|
Keyword arguments:
|
|
|
|
primary_key -- attribute from which to make RDN (default 'cn')
|
|
|
|
parent_dn -- DN of the parent entry (default '')
|
|
|
|
"""
|
|
|
|
|
|
|
|
assert primary_key in entry_attrs
|
|
|
|
assert isinstance(parent_dn, DN)
|
|
|
|
|
|
|
|
return DN((primary_key, entry_attrs[primary_key]), parent_dn)
|
|
|
|
|
|
|
|
def make_entry(self, _dn=None, _obj=None, **kwargs):
|
2015-01-14 10:49:35 -06:00
|
|
|
return LDAPEntry(self, _dn, _obj, **kwargs)
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
# generating filters for find_entry
|
|
|
|
# some examples:
|
|
|
|
# f1 = ldap2.make_filter_from_attr(u'firstName', u'Pavel')
|
|
|
|
# f2 = ldap2.make_filter_from_attr(u'lastName', u'Zuna')
|
|
|
|
# f = ldap2.combine_filters([f1, f2], ldap2.MATCH_ALL)
|
|
|
|
# # f should be (&(firstName=Pavel)(lastName=Zuna))
|
|
|
|
# # it should be equivalent to:
|
|
|
|
# entry_attrs = {u'firstName': u'Pavel', u'lastName': u'Zuna'}
|
|
|
|
# f = ldap2.make_filter(entry_attrs, rules=ldap2.MATCH_ALL)
|
|
|
|
|
2016-06-16 19:05:49 -05:00
|
|
|
@classmethod
|
|
|
|
def combine_filters(cls, filters, rules='|'):
|
2013-01-31 05:19:02 -06:00
|
|
|
"""
|
|
|
|
Combine filters into one for ldap2.find_entries.
|
|
|
|
|
|
|
|
Keyword arguments:
|
|
|
|
rules -- see ldap2.make_filter
|
|
|
|
"""
|
|
|
|
|
|
|
|
assert isinstance(filters, (list, tuple))
|
|
|
|
|
2018-05-17 09:49:27 -05:00
|
|
|
filters = [fx for fx in filters if fx]
|
2016-06-16 19:05:49 -05:00
|
|
|
if filters and rules == cls.MATCH_NONE: # unary operator
|
|
|
|
return '(%s%s)' % (cls.MATCH_NONE,
|
|
|
|
cls.combine_filters(filters, cls.MATCH_ANY))
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
if len(filters) > 1:
|
|
|
|
flt = '(%s' % rules
|
|
|
|
else:
|
|
|
|
flt = ''
|
|
|
|
for f in filters:
|
|
|
|
if not f.startswith('('):
|
|
|
|
f = '(%s)' % f
|
|
|
|
flt = '%s%s' % (flt, f)
|
|
|
|
if len(filters) > 1:
|
|
|
|
flt = '%s)' % flt
|
|
|
|
return flt
|
|
|
|
|
2016-06-16 19:05:49 -05:00
|
|
|
@classmethod
|
2013-01-31 05:19:02 -06:00
|
|
|
def make_filter_from_attr(
|
2016-06-16 19:05:49 -05:00
|
|
|
cls, attr, value, rules='|', exact=True,
|
2013-01-31 05:19:02 -06:00
|
|
|
leading_wildcard=True, trailing_wildcard=True):
|
|
|
|
"""
|
|
|
|
Make filter for ldap2.find_entries from attribute.
|
|
|
|
|
|
|
|
Keyword arguments:
|
|
|
|
rules -- see ldap2.make_filter
|
|
|
|
exact -- boolean, True - make filter as (attr=value)
|
|
|
|
False - make filter as (attr=*value*)
|
|
|
|
leading_wildcard -- boolean:
|
|
|
|
True - allow heading filter wildcard when exact=False
|
|
|
|
False - forbid heading filter wildcard when exact=False
|
|
|
|
trailing_wildcard -- boolean:
|
|
|
|
True - allow trailing filter wildcard when exact=False
|
|
|
|
False - forbid trailing filter wildcard when exact=False
|
|
|
|
"""
|
|
|
|
if isinstance(value, (list, tuple)):
|
|
|
|
flts = [
|
2016-06-16 19:05:49 -05:00
|
|
|
cls.make_filter_from_attr(
|
2013-01-31 05:19:02 -06:00
|
|
|
attr, v, exact=exact,
|
|
|
|
leading_wildcard=leading_wildcard,
|
|
|
|
trailing_wildcard=trailing_wildcard)
|
|
|
|
for v in value
|
|
|
|
]
|
2016-06-16 19:05:49 -05:00
|
|
|
return cls.combine_filters(flts, rules)
|
2013-01-31 05:19:02 -06:00
|
|
|
elif value is not None:
|
2018-11-22 11:31:38 -06:00
|
|
|
if isinstance(value, crypto_x509.Certificate):
|
|
|
|
value = value.public_bytes(serialization.Encoding.DER)
|
2016-03-16 07:09:11 -05:00
|
|
|
if isinstance(value, bytes):
|
2017-01-23 03:26:50 -06:00
|
|
|
value = binascii.hexlify(value).decode('ascii')
|
|
|
|
# value[-2:0] is empty string for the initial '\\'
|
|
|
|
value = u'\\'.join(
|
|
|
|
value[i:i+2] for i in six.moves.range(-2, len(value), 2))
|
2016-03-16 07:09:11 -05:00
|
|
|
else:
|
2018-09-26 05:39:56 -05:00
|
|
|
value = str(value)
|
2017-01-23 03:26:50 -06:00
|
|
|
value = ldap.filter.escape_filter_chars(value)
|
2017-01-11 06:03:53 -06:00
|
|
|
|
2013-01-31 05:19:02 -06:00
|
|
|
if not exact:
|
|
|
|
template = '%s'
|
|
|
|
if leading_wildcard:
|
|
|
|
template = '*' + template
|
|
|
|
if trailing_wildcard:
|
|
|
|
template = template + '*'
|
|
|
|
value = template % value
|
2016-06-16 19:05:49 -05:00
|
|
|
if rules == cls.MATCH_NONE:
|
2013-01-31 05:19:02 -06:00
|
|
|
return '(!(%s=%s))' % (attr, value)
|
|
|
|
return '(%s=%s)' % (attr, value)
|
|
|
|
return ''
|
|
|
|
|
2016-06-16 19:05:49 -05:00
|
|
|
@classmethod
|
2013-01-31 05:19:02 -06:00
|
|
|
def make_filter(
|
2016-06-16 19:05:49 -05:00
|
|
|
cls, entry_attrs, attrs_list=None, rules='|', exact=True,
|
2013-01-31 05:19:02 -06:00
|
|
|
leading_wildcard=True, trailing_wildcard=True):
|
|
|
|
"""
|
|
|
|
Make filter for ldap2.find_entries from entry attributes.
|
|
|
|
|
|
|
|
Keyword arguments:
|
|
|
|
attrs_list -- list of attributes to use, all if None (default None)
|
|
|
|
rules -- specifies how to determine a match (default ldap2.MATCH_ANY)
|
|
|
|
exact -- boolean, True - make filter as (attr=value)
|
|
|
|
False - make filter as (attr=*value*)
|
|
|
|
leading_wildcard -- boolean:
|
|
|
|
True - allow heading filter wildcard when exact=False
|
|
|
|
False - forbid heading filter wildcard when exact=False
|
|
|
|
trailing_wildcard -- boolean:
|
|
|
|
True - allow trailing filter wildcard when exact=False
|
|
|
|
False - forbid trailing filter wildcard when exact=False
|
|
|
|
|
|
|
|
rules can be one of the following:
|
|
|
|
ldap2.MATCH_NONE - match entries that do not match any attribute
|
|
|
|
ldap2.MATCH_ALL - match entries that match all attributes
|
|
|
|
ldap2.MATCH_ANY - match entries that match any of attribute
|
|
|
|
"""
|
2016-06-16 19:05:49 -05:00
|
|
|
if rules == cls.MATCH_NONE:
|
|
|
|
make_filter_rules = cls.MATCH_ANY
|
2013-01-31 05:19:02 -06:00
|
|
|
else:
|
|
|
|
make_filter_rules = rules
|
|
|
|
flts = []
|
|
|
|
if attrs_list is None:
|
Use Python3-compatible dict method names
Python 2 has keys()/values()/items(), which return lists,
iterkeys()/itervalues()/iteritems(), which return iterators,
and viewkeys()/viewvalues()/viewitems() which return views.
Python 3 has only keys()/values()/items(), which return views.
To get iterators, one can use iter() or a for loop/comprehension;
for lists there's the list() constructor.
When iterating through the entire dict, without modifying the dict,
the difference between Python 2's items() and iteritems() is
negligible, especially on small dicts (the main overhead is
extra memory, not CPU time). In the interest of simpler code,
this patch changes many instances of iteritems() to items(),
iterkeys() to keys() etc.
In other cases, helpers like six.itervalues are used.
Reviewed-By: Christian Heimes <cheimes@redhat.com>
Reviewed-By: Jan Cholasta <jcholast@redhat.com>
2015-08-11 06:51:14 -05:00
|
|
|
for (k, v) in entry_attrs.items():
|
2013-01-31 05:19:02 -06:00
|
|
|
flts.append(
|
2016-06-16 19:05:49 -05:00
|
|
|
cls.make_filter_from_attr(
|
2013-01-31 05:19:02 -06:00
|
|
|
k, v, make_filter_rules, exact,
|
|
|
|
leading_wildcard, trailing_wildcard)
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
for a in attrs_list:
|
|
|
|
value = entry_attrs.get(a, None)
|
|
|
|
if value is not None:
|
|
|
|
flts.append(
|
2016-06-16 19:05:49 -05:00
|
|
|
cls.make_filter_from_attr(
|
2013-01-31 05:19:02 -06:00
|
|
|
a, value, make_filter_rules, exact,
|
|
|
|
leading_wildcard, trailing_wildcard)
|
|
|
|
)
|
2016-06-16 19:05:49 -05:00
|
|
|
return cls.combine_filters(flts, rules)
|
2013-01-31 05:19:02 -06:00
|
|
|
|
2013-07-17 06:34:36 -05:00
|
|
|
def get_entries(self, base_dn, scope=ldap.SCOPE_SUBTREE, filter=None,
|
2018-02-07 18:04:48 -06:00
|
|
|
attrs_list=None, get_effective_rights=False, **kwargs):
|
2013-01-31 05:19:02 -06:00
|
|
|
"""Return a list of matching entries.
|
|
|
|
|
2014-06-18 10:31:53 -05:00
|
|
|
:raises: errors.LimitsExceeded if the list is truncated by the server
|
|
|
|
:raises: errors.NotFound if result set is empty
|
|
|
|
or base_dn doesn't exist
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
:param base_dn: dn of the entry at which to start the search
|
|
|
|
:param scope: search scope, see LDAP docs (default ldap2.SCOPE_SUBTREE)
|
|
|
|
:param filter: LDAP filter to apply
|
|
|
|
:param attrs_list: ist of attributes to return, all if None (default)
|
2018-02-07 18:04:48 -06:00
|
|
|
:param get_effective_rights: use GetEffectiveRights control
|
2016-03-18 03:49:41 -05:00
|
|
|
:param kwargs: additional keyword arguments. See find_entries method
|
|
|
|
for their description.
|
2013-01-31 05:19:02 -06:00
|
|
|
"""
|
|
|
|
entries, truncated = self.find_entries(
|
2016-08-11 07:08:33 -05:00
|
|
|
base_dn=base_dn, scope=scope, filter=filter, attrs_list=attrs_list,
|
2018-02-07 18:04:48 -06:00
|
|
|
get_effective_rights=get_effective_rights,
|
2016-08-11 07:08:33 -05:00
|
|
|
**kwargs)
|
2016-03-18 03:49:41 -05:00
|
|
|
try:
|
|
|
|
self.handle_truncated_result(truncated)
|
|
|
|
except errors.LimitsExceeded as e:
|
2017-05-23 11:35:57 -05:00
|
|
|
logger.error(
|
|
|
|
"%s while getting entries (base DN: %s, filter: %s)",
|
|
|
|
e, base_dn, filter
|
2016-03-18 03:49:41 -05:00
|
|
|
)
|
|
|
|
raise
|
|
|
|
|
2013-01-31 05:19:02 -06:00
|
|
|
return entries
|
|
|
|
|
2018-02-07 18:04:48 -06:00
|
|
|
def find_entries(
|
|
|
|
self, filter=None, attrs_list=None, base_dn=None,
|
|
|
|
scope=ldap.SCOPE_SUBTREE, time_limit=None, size_limit=None,
|
|
|
|
paged_search=False, get_effective_rights=False):
|
2013-01-31 05:19:02 -06:00
|
|
|
"""
|
|
|
|
Return a list of entries and indication of whether the results were
|
|
|
|
truncated ([(dn, entry_attrs)], truncated) matching specified search
|
|
|
|
parameters followed by truncated flag. If the truncated flag is True,
|
|
|
|
search hit a server limit and its results are incomplete.
|
|
|
|
|
|
|
|
Keyword arguments:
|
2018-02-07 18:04:48 -06:00
|
|
|
:param attrs_list: list of attributes to return, all if None
|
|
|
|
(default None)
|
|
|
|
:param base_dn: dn of the entry at which to start the search
|
|
|
|
(default '')
|
|
|
|
:param scope: search scope, see LDAP docs (default ldap2.SCOPE_SUBTREE)
|
|
|
|
:param time_limit: time limit in seconds (default unlimited)
|
|
|
|
:param size_limit: size (number of entries returned) limit
|
|
|
|
(default unlimited)
|
|
|
|
:param paged_search: search using paged results control
|
|
|
|
:param get_effective_rights: use GetEffectiveRights control
|
2014-06-18 10:31:53 -05:00
|
|
|
|
|
|
|
:raises: errors.NotFound if result set is empty
|
|
|
|
or base_dn doesn't exist
|
2013-01-31 05:19:02 -06:00
|
|
|
"""
|
|
|
|
if base_dn is None:
|
|
|
|
base_dn = DN()
|
|
|
|
assert isinstance(base_dn, DN)
|
|
|
|
if not filter:
|
|
|
|
filter = '(objectClass=*)'
|
|
|
|
res = []
|
|
|
|
truncated = False
|
|
|
|
|
2015-11-18 03:31:05 -06:00
|
|
|
if time_limit is None:
|
|
|
|
time_limit = self.time_limit
|
|
|
|
if time_limit == 0:
|
2013-10-31 06:47:53 -05:00
|
|
|
time_limit = -1.0
|
2015-11-18 03:31:05 -06:00
|
|
|
|
2013-10-31 06:47:53 -05:00
|
|
|
if size_limit is None:
|
2015-11-18 03:31:05 -06:00
|
|
|
size_limit = self.size_limit
|
|
|
|
|
2013-01-31 05:19:02 -06:00
|
|
|
if not isinstance(size_limit, int):
|
|
|
|
size_limit = int(size_limit)
|
|
|
|
if not isinstance(time_limit, float):
|
|
|
|
time_limit = float(time_limit)
|
|
|
|
|
|
|
|
if attrs_list:
|
2013-10-31 06:47:53 -05:00
|
|
|
attrs_list = [a.lower() for a in set(attrs_list)]
|
2013-01-31 05:19:02 -06:00
|
|
|
|
2018-02-07 18:04:48 -06:00
|
|
|
base_sctrls = []
|
|
|
|
if get_effective_rights:
|
|
|
|
base_sctrls.append(self.__get_effective_rights_control())
|
|
|
|
|
2013-10-31 07:31:24 -05:00
|
|
|
cookie = ''
|
|
|
|
page_size = (size_limit if size_limit > 0 else 2000) - 1
|
|
|
|
if page_size == 0:
|
|
|
|
paged_search = False
|
|
|
|
|
2013-01-31 05:19:02 -06:00
|
|
|
# pass arguments to python-ldap
|
|
|
|
with self.error_handler():
|
2015-09-17 11:46:14 -05:00
|
|
|
if six.PY2:
|
|
|
|
filter = self.encode(filter)
|
|
|
|
attrs_list = self.encode(attrs_list)
|
2015-01-14 09:51:52 -06:00
|
|
|
|
2013-10-31 07:31:24 -05:00
|
|
|
while True:
|
|
|
|
if paged_search:
|
2018-02-07 18:04:48 -06:00
|
|
|
sctrls = base_sctrls + [
|
|
|
|
SimplePagedResultsControl(0, page_size, cookie)
|
|
|
|
]
|
|
|
|
else:
|
|
|
|
sctrls = base_sctrls or None
|
2013-10-31 07:31:24 -05:00
|
|
|
|
|
|
|
try:
|
|
|
|
id = self.conn.search_ext(
|
2015-01-14 09:51:52 -06:00
|
|
|
str(base_dn), scope, filter, attrs_list,
|
2013-10-31 07:31:24 -05:00
|
|
|
serverctrls=sctrls, timeout=time_limit,
|
|
|
|
sizelimit=size_limit
|
|
|
|
)
|
|
|
|
while True:
|
|
|
|
result = self.conn.result3(id, 0)
|
2016-10-07 08:07:49 -05:00
|
|
|
objtype, res_list, _res_id, res_ctrls = result
|
2016-09-29 06:46:05 -05:00
|
|
|
if objtype == ldap.RES_SEARCH_RESULT:
|
2013-10-31 07:31:24 -05:00
|
|
|
break
|
2016-09-29 06:46:05 -05:00
|
|
|
res_list = self._convert_result(res_list)
|
|
|
|
if res_list:
|
2013-10-31 07:31:24 -05:00
|
|
|
res.append(res_list[0])
|
|
|
|
|
|
|
|
if paged_search:
|
|
|
|
# Get cookie for the next page
|
|
|
|
for ctrl in res_ctrls:
|
|
|
|
if isinstance(ctrl, SimplePagedResultsControl):
|
|
|
|
cookie = ctrl.cookie
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
cookie = ''
|
2016-03-18 03:49:41 -05:00
|
|
|
except ldap.ADMINLIMIT_EXCEEDED:
|
|
|
|
truncated = TRUNCATED_ADMIN_LIMIT
|
|
|
|
break
|
|
|
|
except ldap.SIZELIMIT_EXCEEDED:
|
|
|
|
truncated = TRUNCATED_SIZE_LIMIT
|
|
|
|
break
|
|
|
|
except ldap.TIMELIMIT_EXCEEDED:
|
|
|
|
truncated = TRUNCATED_TIME_LIMIT
|
|
|
|
break
|
2015-07-30 09:49:29 -05:00
|
|
|
except ldap.LDAPError as e:
|
2013-10-31 07:31:24 -05:00
|
|
|
# If paged search is in progress, try to cancel it
|
|
|
|
if paged_search and cookie:
|
|
|
|
sctrls = [SimplePagedResultsControl(0, 0, cookie)]
|
|
|
|
try:
|
|
|
|
self.conn.search_ext_s(
|
2015-01-14 09:51:52 -06:00
|
|
|
str(base_dn), scope, filter, attrs_list,
|
2013-10-31 07:31:24 -05:00
|
|
|
serverctrls=sctrls, timeout=time_limit,
|
|
|
|
sizelimit=size_limit)
|
2020-04-27 07:33:17 -05:00
|
|
|
except ldap.LDAPError as e2:
|
2017-05-23 11:35:57 -05:00
|
|
|
logger.warning(
|
2020-04-27 07:33:17 -05:00
|
|
|
"Error cancelling paged search: %s", e2)
|
2013-10-31 07:31:24 -05:00
|
|
|
cookie = ''
|
|
|
|
|
|
|
|
try:
|
|
|
|
raise e
|
|
|
|
except (ldap.ADMINLIMIT_EXCEEDED, ldap.TIMELIMIT_EXCEEDED,
|
|
|
|
ldap.SIZELIMIT_EXCEEDED):
|
|
|
|
truncated = True
|
2013-01-31 05:19:02 -06:00
|
|
|
break
|
2013-10-31 07:31:24 -05:00
|
|
|
|
|
|
|
if not paged_search or not cookie:
|
|
|
|
break
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
if not res and not truncated:
|
2014-11-19 05:00:07 -06:00
|
|
|
raise errors.EmptyResult(reason='no matching entry found')
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
return (res, truncated)
|
|
|
|
|
2018-02-07 18:04:48 -06:00
|
|
|
def __get_effective_rights_control(self):
|
|
|
|
"""Construct a GetEffectiveRights control for current user."""
|
|
|
|
bind_dn = self.conn.whoami_s()[4:]
|
|
|
|
return GetEffectiveRightsControl(
|
|
|
|
True, "dn: {0}".format(bind_dn).encode('utf-8'))
|
|
|
|
|
2013-01-31 05:19:02 -06:00
|
|
|
def find_entry_by_attr(self, attr, value, object_class, attrs_list=None,
|
|
|
|
base_dn=None):
|
|
|
|
"""
|
|
|
|
Find entry (dn, entry_attrs) by attribute and object class.
|
|
|
|
|
|
|
|
Keyword arguments:
|
|
|
|
attrs_list - list of attributes to return, all if None (default None)
|
|
|
|
base_dn - dn of the entry at which to start the search (default '')
|
|
|
|
"""
|
|
|
|
|
|
|
|
if base_dn is None:
|
|
|
|
base_dn = DN()
|
|
|
|
assert isinstance(base_dn, DN)
|
|
|
|
|
|
|
|
search_kw = {attr: value, 'objectClass': object_class}
|
|
|
|
filter = self.make_filter(search_kw, rules=self.MATCH_ALL)
|
2016-03-18 03:49:41 -05:00
|
|
|
entries = self.get_entries(
|
|
|
|
base_dn, filter=filter, attrs_list=attrs_list)
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
if len(entries) > 1:
|
|
|
|
raise errors.SingleMatchExpected(found=len(entries))
|
2016-03-18 03:49:41 -05:00
|
|
|
|
|
|
|
return entries[0]
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
def get_entry(self, dn, attrs_list=None, time_limit=None,
|
2018-02-07 18:04:48 -06:00
|
|
|
size_limit=None, get_effective_rights=False):
|
2013-01-31 05:19:02 -06:00
|
|
|
"""
|
|
|
|
Get entry (dn, entry_attrs) by dn.
|
|
|
|
|
|
|
|
Keyword arguments:
|
|
|
|
attrs_list - list of attributes to return, all if None (default None)
|
|
|
|
"""
|
|
|
|
|
|
|
|
assert isinstance(dn, DN)
|
|
|
|
|
2016-03-18 03:49:41 -05:00
|
|
|
entries = self.get_entries(
|
|
|
|
dn, self.SCOPE_BASE, None, attrs_list, time_limit=time_limit,
|
2018-02-07 18:04:48 -06:00
|
|
|
size_limit=size_limit, get_effective_rights=get_effective_rights,
|
2013-01-31 05:19:02 -06:00
|
|
|
)
|
|
|
|
|
2013-10-31 11:53:44 -05:00
|
|
|
return entries[0]
|
2013-01-31 05:19:02 -06:00
|
|
|
|
2014-10-23 08:44:40 -05:00
|
|
|
def add_entry(self, entry):
|
2013-01-31 05:19:02 -06:00
|
|
|
"""Create a new entry.
|
|
|
|
|
|
|
|
This should be called as add_entry(entry).
|
|
|
|
"""
|
|
|
|
# remove all [] values (python-ldap hates 'em)
|
Use Python3-compatible dict method names
Python 2 has keys()/values()/items(), which return lists,
iterkeys()/itervalues()/iteritems(), which return iterators,
and viewkeys()/viewvalues()/viewitems() which return views.
Python 3 has only keys()/values()/items(), which return views.
To get iterators, one can use iter() or a for loop/comprehension;
for lists there's the list() constructor.
When iterating through the entire dict, without modifying the dict,
the difference between Python 2's items() and iteritems() is
negligible, especially on small dicts (the main overhead is
extra memory, not CPU time). In the interest of simpler code,
this patch changes many instances of iteritems() to items(),
iterkeys() to keys() etc.
In other cases, helpers like six.itervalues are used.
Reviewed-By: Christian Heimes <cheimes@redhat.com>
Reviewed-By: Jan Cholasta <jcholast@redhat.com>
2015-08-11 06:51:14 -05:00
|
|
|
attrs = dict((k, v) for k, v in entry.raw.items() if v)
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
with self.error_handler():
|
2015-01-14 09:51:52 -06:00
|
|
|
attrs = self.encode(attrs)
|
Use Python3-compatible dict method names
Python 2 has keys()/values()/items(), which return lists,
iterkeys()/itervalues()/iteritems(), which return iterators,
and viewkeys()/viewvalues()/viewitems() which return views.
Python 3 has only keys()/values()/items(), which return views.
To get iterators, one can use iter() or a for loop/comprehension;
for lists there's the list() constructor.
When iterating through the entire dict, without modifying the dict,
the difference between Python 2's items() and iteritems() is
negligible, especially on small dicts (the main overhead is
extra memory, not CPU time). In the interest of simpler code,
this patch changes many instances of iteritems() to items(),
iterkeys() to keys() etc.
In other cases, helpers like six.itervalues are used.
Reviewed-By: Christian Heimes <cheimes@redhat.com>
Reviewed-By: Jan Cholasta <jcholast@redhat.com>
2015-08-11 06:51:14 -05:00
|
|
|
self.conn.add_s(str(entry.dn), list(attrs.items()))
|
2013-12-10 04:13:48 -06:00
|
|
|
|
2014-01-07 05:46:59 -06:00
|
|
|
entry.reset_modlist()
|
2013-01-31 05:19:02 -06:00
|
|
|
|
2015-04-15 08:48:21 -05:00
|
|
|
def move_entry(self, dn, new_dn, del_old=True):
|
2013-01-31 05:19:02 -06:00
|
|
|
"""
|
2015-04-15 08:48:21 -05:00
|
|
|
Move an entry (either to a new superior or/and changing relative distinguished name)
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
Keyword arguments:
|
2015-04-15 08:48:21 -05:00
|
|
|
dn: DN of the source entry
|
|
|
|
new_dn: DN of the target entry
|
2013-01-31 05:19:02 -06:00
|
|
|
del_old -- delete old RDN value (default True)
|
|
|
|
|
2015-04-15 08:48:21 -05:00
|
|
|
:raises:
|
|
|
|
errors.NotFound if source entry or target superior entry doesn't exist
|
|
|
|
errors.EmptyModlist if source and target are identical
|
|
|
|
"""
|
2013-01-31 05:19:02 -06:00
|
|
|
assert isinstance(dn, DN)
|
2015-04-15 08:48:21 -05:00
|
|
|
assert isinstance(new_dn, DN)
|
2013-01-31 05:19:02 -06:00
|
|
|
|
2015-04-15 08:48:21 -05:00
|
|
|
if new_dn == dn:
|
2013-01-31 05:19:02 -06:00
|
|
|
raise errors.EmptyModlist()
|
2015-04-15 08:48:21 -05:00
|
|
|
|
|
|
|
new_rdn = new_dn[0]
|
|
|
|
|
|
|
|
if new_dn[1:] == dn[1:]:
|
|
|
|
new_superior = None
|
|
|
|
else:
|
2015-01-14 09:51:52 -06:00
|
|
|
new_superior = str(DN(*new_dn[1:]))
|
2015-04-15 08:48:21 -05:00
|
|
|
|
2013-01-31 05:19:02 -06:00
|
|
|
with self.error_handler():
|
2015-01-14 09:51:52 -06:00
|
|
|
self.conn.rename_s(str(dn), str(new_rdn), newsuperior=new_superior,
|
2015-04-15 08:48:21 -05:00
|
|
|
delold=int(del_old))
|
2013-01-31 05:19:02 -06:00
|
|
|
time.sleep(.3) # Give memberOf plugin a chance to work
|
|
|
|
|
2014-10-23 08:44:40 -05:00
|
|
|
def update_entry(self, entry):
|
2013-01-31 05:19:02 -06:00
|
|
|
"""Update entry's attributes.
|
|
|
|
|
|
|
|
This should be called as update_entry(entry).
|
|
|
|
"""
|
|
|
|
# generate modlist
|
2013-12-10 04:45:10 -06:00
|
|
|
modlist = entry.generate_modlist()
|
2013-01-31 05:19:02 -06:00
|
|
|
if not modlist:
|
|
|
|
raise errors.EmptyModlist()
|
|
|
|
|
|
|
|
# pass arguments to python-ldap
|
|
|
|
with self.error_handler():
|
2016-04-29 10:13:08 -05:00
|
|
|
modlist = [(a, str(b), self.encode(c))
|
2015-01-14 09:51:52 -06:00
|
|
|
for a, b, c in modlist]
|
|
|
|
self.conn.modify_s(str(entry.dn), modlist)
|
2013-12-10 04:13:48 -06:00
|
|
|
|
2014-01-07 05:46:59 -06:00
|
|
|
entry.reset_modlist()
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
def delete_entry(self, entry_or_dn):
|
|
|
|
"""Delete an entry given either the DN or the entry itself"""
|
|
|
|
if isinstance(entry_or_dn, DN):
|
|
|
|
dn = entry_or_dn
|
|
|
|
else:
|
|
|
|
dn = entry_or_dn.dn
|
|
|
|
|
|
|
|
with self.error_handler():
|
2015-01-14 09:51:52 -06:00
|
|
|
self.conn.delete_s(str(dn))
|
2013-01-31 05:19:02 -06:00
|
|
|
|
2014-08-27 08:06:42 -05:00
|
|
|
def entry_exists(self, dn):
|
|
|
|
"""
|
|
|
|
Test whether the given object exists in LDAP.
|
|
|
|
"""
|
|
|
|
assert isinstance(dn, DN)
|
|
|
|
try:
|
|
|
|
self.get_entry(dn, attrs_list=[])
|
|
|
|
except errors.NotFound:
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return True
|
|
|
|
|
2013-01-31 05:19:02 -06:00
|
|
|
|
2016-11-01 08:52:33 -05:00
|
|
|
def get_ldap_uri(host='', port=389, cacert=None, ldapi=False, realm=None,
|
|
|
|
protocol=None):
|
|
|
|
if protocol is None:
|
|
|
|
if ldapi:
|
|
|
|
protocol = 'ldapi'
|
|
|
|
elif cacert is not None:
|
|
|
|
protocol = 'ldaps'
|
|
|
|
else:
|
|
|
|
protocol = 'ldap'
|
2013-01-31 05:19:02 -06:00
|
|
|
|
|
|
|
if protocol == 'ldaps':
|
2016-11-01 08:52:33 -05:00
|
|
|
return 'ldaps://%s' % format_netloc(host, port)
|
2013-01-31 05:19:02 -06:00
|
|
|
elif protocol == 'ldapi':
|
|
|
|
return 'ldapi://%%2fvar%%2frun%%2fslapd-%s.socket' % (
|
2016-11-01 08:52:33 -05:00
|
|
|
"-".join(realm.split(".")))
|
2013-01-31 05:19:02 -06:00
|
|
|
elif protocol == 'ldap':
|
2016-11-01 08:52:33 -05:00
|
|
|
return 'ldap://%s' % format_netloc(host, port)
|
2013-01-31 05:19:02 -06:00
|
|
|
else:
|
|
|
|
raise ValueError('Protocol %r not supported' % protocol)
|