Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# Authors: # Pavel Zuna <pzuna@redhat.com> # John Dennis <jdennis@redhat.com> # # Copyright (C) 2009 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/>. Backend plugin for LDAP. """
# Entries are represented as (dn, entry_attrs), where entry_attrs is a dict # mapping attribute names to values. Values can be a single value or list/tuple # of virtually any type. Each method passing these values to the python-ldap # binding encodes them into the appropriate representation. This applies to # everything except the CrudBackend methods, where dn is part of the entry dict.
except ImportError: """ python-ldap 2.4.x introduced a new API for effective rights control, which needs to be used or otherwise bind dn is not passed correctly. The following class is created for backward compatibility with python-ldap 2.3.x. Relevant BZ: https://bugzilla.redhat.com/show_bug.cgi?id=802675 """ from ldap.controls import LDAPControl class GetEffectiveRightsControl(LDAPControl): def __init__(self, criticality, authzId=None): LDAPControl.__init__(self, '1.3.6.1.4.1.42.2.27.9.5.2', criticality, authzId) # for backward compatibility
# Make python-ldap tuple style result compatible with Entry and Entity # objects by allowing access to the dn (tuple index 0) via the 'dn' # attribute name and the attr dict (tuple index 1) via the 'data' # attribute name. Thus: # r = result[0] # r[0] == r.dn # r[1] == r.data
# Group Member types
# SASL authentication mechanism
''' val is a UTF-8 encoded string, return a unicode object. '''
''' Coerce the val parameter to a UTF-8 encoded string representation of the val. '''
# If val is not a string we need to convert it to a string # (specifically a unicode string). Naively we might think we need to # call str(val) to convert to a string. This is incorrect because if # val is already a unicode object then str() will call # encode(default_encoding) returning a str object encoded with # default_encoding. But we don't want to apply the default_encoding! # Rather we want to guarantee the val object has been converted to a # unicode string because from a unicode string we want to explicitly # encode to a str using our desired encoding (utf-8 in this case). # # Note: calling unicode on a unicode object simply returns the exact # same object (with it's ref count incremented). This means calling # unicode on a unicode object is effectively a no-op, thus it's not # inefficient.
''' Properties of a schema retrieved from an LDAP server. '''
''' Cache the schema's from individual LDAP servers. '''
''' 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. '''
self.flush(url)
self.debug('flushing %s from SchemaCache', url) try: del self.servers[url] except KeyError: pass
""" 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. """
# FIXME: is this really what we want to do? # This seems like this logic is in the wrong place and may conflict with other state. try: # Create a new credentials cache for this Apache process tmpdir = tempfile.mkdtemp(prefix = "tmp-") ccache_file = 'FILE:%s/ccache' % tmpdir krbcontext = krbV.default_context() principal = str('HTTP/%s@%s' % (api.env.host, api.env.realm)) keytab = krbV.Keytab(name='/etc/httpd/conf/ipa.keytab', context=krbcontext) principal = krbV.Principal(name=principal, context=krbcontext) prev_ccache = os.environ.get('KRB5CCNAME') os.environ['KRB5CCNAME'] = ccache_file ccache = krbV.CCache(name=ccache_file, context=krbcontext, primary_principal=principal) ccache.init(principal) ccache.init_creds_keytab(keytab=keytab, principal=principal) except krbV.Krb5Error, e: raise StandardError('Unable to retrieve LDAP schema. Error initializing principal %s in %s: %s' % (principal.name, '/etc/httpd/conf/ipa.keytab', str(e))) finally: if prev_ccache is not None: os.environ['KRB5CCNAME'] = prev_ccache
conn = IPASimpleLDAPObject(url) if url.startswith('ldapi://'): conn.set_option(_ldap.OPT_HOST_NAME, api.env.host) conn.sasl_interactive_bind_s(None, SASL_AUTH)
attrlist=['attributetypes', 'objectclasses'])[0] conn.unbind_s() except _ldap.SERVER_DOWN: raise NetworkError(uri=url, error=u'LDAP Server Down, unable to retrieve LDAP schema') except _ldap.LDAPError, e: desc = e.args[0]['desc'].strip() info = e.args[0].get('info', '').strip() raise DatabaseError(desc = u'uri=%s' % url, info = u'Unable to retrieve LDAP schema: %s: %s' % (desc, info)) except IndexError: # 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 raise finally: shutil.rmtree(tmpdir)
''' 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.
IPA code should never call python-ldap directly, it should only call python-ldap methods in this class. '''
# Note: the oid for dn syntax is: 1.3.6.1.4.1.1466.115.121.1.12
'1.3.6.1.4.1.1466.115.121.1.1' : str, # ACI item '1.3.6.1.4.1.1466.115.121.1.4' : str, # Audio '1.3.6.1.4.1.1466.115.121.1.5' : str, # Binary '1.3.6.1.4.1.1466.115.121.1.8' : str, # Certificate '1.3.6.1.4.1.1466.115.121.1.9' : str, # Certificate List '1.3.6.1.4.1.1466.115.121.1.10' : str, # Certificate Pair '1.3.6.1.4.1.1466.115.121.1.23' : str, # Fax '1.3.6.1.4.1.1466.115.121.1.28' : str, # JPEG '1.3.6.1.4.1.1466.115.121.1.40' : str, # OctetString (same as Binary) '1.3.6.1.4.1.1466.115.121.1.49' : str, # Supported Algorithm '1.3.6.1.4.1.1466.115.121.1.51' : str, # Teletext Terminal Identifier
DN_SYNTAX_OID : DN, # DN, member, memberof '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 :-(
'managedtemplate': DN_SYNTAX_OID, # DN 'managedbase': DN_SYNTAX_OID, # DN 'originscope': DN_SYNTAX_OID, # DN })
# The schema may be updated during install or during # updates, make sure we have a current version of the # schema, not an out of date cached version.
''' 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.
# Is this a special case attribute?
# Try to lookup the syntax in the schema returned by the server else:
""" Check the schema to see if the attribute uses DN syntax.
Returns True/False """
''' ''' # 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. else: dct = dict((self.encode(k), self.encode(v)) for k, v in val.iteritems()) return dct else: raise TypeError("attempt to pass unsupported type to ldap, value=%s type=%s" %(val, type(val)))
''' '''
else: except Exception, e: msg = 'unable to convert the attribute "%s" value "%s" to type %s' % (attr, original_value, target_type) self.error(msg) raise ValueError(msg)
''' 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 dn to a DN object.
We convert every value associated with an attribute according to it's syntax into the desired Python type.
returns a IPA result tuple of the same form as a python-ldap result tuple except everything inside of the result tuple has been converted to it's preferred IPA python type. '''
self.debug('ldap.result: %s', ipa_result)
#---------- python-ldap emulations ----------
assert isinstance(dn, DN) dn = str(dn) modlist = self.encode(modlist) return self.conn.add(dn, modlist)
assert isinstance(dn, DN) dn = str(dn) modlist = self.encode(modlist) return self.conn.add_ext(dn, modlist, serverctrls, clientctrls)
assert isinstance(dn, DN) dn = str(dn) modlist = self.encode(modlist) return self.conn.add_ext_s(dn, modlist, serverctrls, clientctrls)
self.flush_cached_schema() if who is None: who = DN() assert isinstance(who, DN) who = str(who) cred = self.encode(cred) return self.conn.bind(who, cred, method)
assert isinstance(dn, DN) dn = str(dn) return self.conn.delete(dn)
assert isinstance(dn, DN) dn = str(dn) assert isinstance(newrdn, (DN, RDN)) newrdn = str(newrdn) return self.conn.modrdn_s(dn, newrdn, delold)
self.debug("ldap.search_ext: dn: %s\nfilter: %s\nattrs_list: %s", base, filterstr, attrlist)
assert isinstance(base, DN) base = str(base) filterstr = self.encode(filterstr) attrlist = self.encode(attrlist) ldap_result = self.conn.search_ext_s(base, scope, filterstr, attrlist, attrsonly, serverctrls, clientctrls, timeout, sizelimit) ipa_result = self.convert_result(ldap_result) return ipa_result
assert isinstance(base, DN) base = str(base) filterstr = self.encode(filterstr) attrlist = self.encode(attrlist) ldap_result = self.conn.search_st(base, scope, filterstr, attrlist, attrsonly, timeout) ipa_result = self.convert_result(ldap_result) return ipa_result
who = DN()
return self.conn.start_tls_s()
""" LDAP Backend Take 2. """ # attributes in this list cannot be deleted by update_entry # only MOD_REPLACE operations are generated for them
# rules for generating filters from entries
# search scope for find_entries()
schema=None): except AttributeError: self.ldap_uri = 'ldap://example.com' else: except AttributeError: self.base_dn = DN()
self.disconnect()
return self.ldap_uri
# universal LDAPError handler """ Centralize error handling in one place.
e is the error to be raised """ else: desc = '' info = ''
# re-raise the error so we can handle it # This error gets thrown by the uniqueness plugin if info.startswith('Another entry with the same attribute value already exists'): raise errors.DuplicateEntry() else: raise errors.DatabaseError(desc=desc, info=info) raise errors.ACIError(info=info) raise errors.ACIError(info="%s %s" % (info, desc)) # 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() raise errors.InvalidSyntax(attr=info) raise errors.LimitsExceeded() raise errors.LimitsExceeded() raise errors.LimitsExceeded() raise errors.BadSearchFilter(info=info) pass raise errors.ACIError(info="KDC returned NOT_ALLOWED_TO_DELEGATE")
if self.schema is None: return None obj = self.schema.get_obj(_ldap.schema.AttributeType, attr) if obj is not None: return obj.syntax else: return None
return None elif raise_on_unknown: raise errors.NotFound(reason=_('objectclass %s not found') % oc)
""" 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 """ return None
tls_cacertfile=None, tls_certfile=None, tls_keyfile=None, debug_level=0, autobind=False): """ Connect to LDAP server.
Keyword arguments: ldapuri -- the LDAP server to connect to ccache -- Kerberos V5 ccache name bind_dn -- dn used to bind to the server bind_pw -- password used to bind to the server debug_level -- LDAP debug level option tls_cacertfile -- TLS CA certificate filename tls_certfile -- TLS certificate filename tls_keyfile - TLS bind key filename autobind - autobind as the current user
Extends backend.Connectible.create_connection. """ _ldap.set_option(_ldap.OPT_X_TLS_CACERTFILE, tls_cacertfile) _ldap.set_option(_ldap.OPT_X_TLS_CERTFILE, tls_certfile) _ldap.set_option(_ldap.OPT_X_TLS_KEYFILE, tls_keyfile)
_ldap.set_option(_ldap.OPT_DEBUG_LEVEL, debug_level)
conn.set_option(_ldap.OPT_HOST_NAME, api.env.host) # Always connect with at least an SSF of 56, confidentiality # This also protects us from a broken ldap.conf conn.set_option(_ldap.OPT_X_SASL_SSF_MAX, minssf) context=krbV.default_context()).principal().name else: # no kerberos ccache, use simple bind or external sasl else:
"""Disconnect from LDAP server.""" except _ldap.LDAPError: # ignore when trying to unbind multiple times pass
""" Normalize distinguished name by assuring it ends with the base_dn.
Note: You don't have to normalize DN's before passing them to ldap2 methods. It's done internally for you. """
# DN's are mutable, don't use in-place addtion (+=) which would # modify the dn passed in with unintended side-effects. Addition # returns a new DN object which is the concatenation of the two.
""" Make distinguished name from attribute.
Keyword arguments: parent_dn -- DN of the parent entry (default '') """ parent_dn = DN()
""" 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 '') """
parent_dn = DN()
"""Create a new entry."""
# remove all None or [] values, python-ldap hates'em # FIXME, shouldn't these values be an error? (k, v) for (k, v) in entry_attrs.iteritems() if v is not None and v != [] )
# 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)
""" Combine filters into one for ldap2.find_entries.
Keyword arguments: rules -- see ldap2.make_filter """
self.combine_filters(filters, self.MATCH_ANY))
else: f = '(%s)' % f
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 """ leading_wildcard=leading_wildcard, trailing_wildcard=trailing_wildcard) for v in value ] return '(!(%s=%s))' % (attr, value)
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 """ self.make_filter_from_attr(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( self.make_filter_from_attr(a, value, make_filter_rules, exact, leading_wildcard, trailing_wildcard) )
scope=_ldap.SCOPE_SUBTREE, time_limit=None, size_limit=None, normalize=True, search_refs=False): """ 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: 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 '') scope -- search scope, see LDAP docs (default ldap2.SCOPE_SUBTREE) time_limit -- time limit in seconds (default use IPA config values) size_limit -- size (number of entries returned) limit (default use IPA config values) normalize -- normalize the DN (default True) search_refs -- allow search references to be returned (default skips these entries) """ base_dn = DN()
time_limit = -1
# pass arguments to python-ldap base_dn, scope, filter, attrs_list, timeout=time_limit, sizelimit=size_limit ) (search_refs and objtype == _ldap.RES_SEARCH_REFERENCE): _ldap.SIZELIMIT_EXCEEDED), e:
else: time_limit=time_limit, size_limit=size_limit, normalize=normalize) memberof = r[1]['memberOf'] del r[1]['memberOf'] else: continue size_limit=size_limit, normalize=normalize)
""" 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 '') """
else: raise errors.LimitsExceeded() else:
size_limit=None, normalize=True): """ Get entry (dn, entry_attrs) by dn.
Keyword arguments: attrs_list - list of attributes to return, all if None (default None) """
None, attrs_list, dn, self.SCOPE_BASE, time_limit=time_limit, size_limit=size_limit, normalize=normalize )
raise errors.LimitsExceeded()
"""Returns the IPA configuration entry (dn, entry_attrs)."""
# Not in our context yet None, attrs_list, base_dn=cdn, scope=self.SCOPE_BASE, time_limit=2, size_limit=10 ) raise errors.LimitsExceeded() except errors.NotFound: config_entry = {} config_entry[a] = self.config_defaults[a]
"""Returns True/False whether User-Private Groups are enabled. This is determined based on whether the UPG Template exists. """
('cn', 'etc'), api.env.basedn)
attrlist=['*'])[0] else: return False except _ldap.NO_SUCH_OBJECT, e: return False
"""Returns the rights the currently bound user has for the given DN.
Returns 2 attributes, the attributeLevelRights for the given list of attributes and the entryLevelRights for the entry itself. """
# remove the control so subsequent operations don't include GER
"""Returns True/False if the currently bound user has write permissions on the attribute. This only operates on a single attribute at a time. """
return False
"""Returns True/False if the currently bound user has read permissions on the attribute. This only operates on a single attribute at a time. """ assert isinstance(dn, DN)
(dn, attrs) = self.get_effective_rights(dn, [attr]) if 'attributelevelrights' in attrs: attr_rights = attrs.get('attributelevelrights')[0].decode('UTF-8') (attr, rights) = attr_rights.split(':') if 'r' in rights: return True
return False
# # Entry-level effective rights # # a - Add # d - Delete # n - Rename the DN # v - View the entry #
"""Returns True/False if the currently bound user has delete permissions on the entry. """
assert isinstance(dn, DN)
(dn, attrs) = self.get_effective_rights(dn, ["*"]) if 'entrylevelrights' in attrs: entry_rights = attrs['entrylevelrights'][0].decode('UTF-8') if 'd' in entry_rights: return True
return False
"""Returns True/False if the currently bound user has add permissions on the entry. """ assert isinstance(dn, DN) (dn, attrs) = self.get_effective_rights(dn, ["*"]) if 'entrylevelrights' in attrs: entry_rights = attrs['entrylevelrights'][0].decode('UTF-8') if 'a' in entry_rights: return True
return False
""" Update entry's relative distinguished name.
Keyword arguments: del_old -- delete old RDN value (default True) """
# get original entry
# generate modlist # for multi value attributes: no MOD_REPLACE to handle simultaneous # updates better # for single value attribute: always MOD_REPLACE else:
raise errors.OnlyOneValueAllowed(attr=k)
else:
""" Update entry's attributes.
An attribute value set to None deletes all current values. """
# generate modlist
# pass arguments to python-ldap
"""Delete entry."""
"""Set user password."""
# The python-ldap passwd command doesn't verify the old password # so we'll do a simple bind to validate it. try: conn = IPASimpleLDAPObject(self.ldap_uri) conn.simple_bind_s(dn, old_pass) conn.unbind() except _ldap.LDAPError, e: self.handle_errors(e)
except _ldap.LDAPError, e: self.handle_errors(e)
""" Add entry designaed by dn to group group_dn in the member attribute member_attr.
Adding a group as a member of itself is not allowed unless allow_same is True. """
# check if the entry exists
# get group entry
# check if we're not trying to add group into itself raise errors.SameGroupError()
# add dn to group entry's `member_attr` attribute
# update group entry
"""Remove entry from group."""
# get group entry
# remove dn from group entry's `member_attr` attribute
# update group entry
"""Do a memberOf search of groupdn and return the attributes in attr_list (an empty list returns all attributes).
membertype = MEMBERS_ALL all members returned membertype = MEMBERS_DIRECT only direct members are returned membertype = MEMBERS_INDIRECT only inherited members are returned
Members may be included in a group as a result of being a member of a group that is a member of the group being queried.
Returns a list of DNs. """
return None
# Verify group membership
# No need to check entry types that are not nested for # additional members member_dn.endswith(host_container_dn): attr_list, member_dn, time_limit=time_limit, size_limit=size_limit, scope=_ldap.SCOPE_BASE, normalize=normalize) raise errors.LimitsExceeded() # This member may contain other members, add it to our # candidate list
entries = [] for e in results: entries.append(e[0])
return entries
size_limit=size_limit, time_limit=time_limit)
else: entries.append(e[0])
""" Examine the objects that an entry is a member of and determine if they are a direct or indirect member of that group.
entry_dn: dn of the entry we want the direct/indirect members of memberof: the memberOf attribute for entry_dn
Returns two memberof lists: (direct, indirect) """
return ([], []) return ([], [])
search_entry_dn, search_entry_dn, search_entry_dn)
# Search only the groups for which the object is a member to # determine if it is directly or indirectly associated.
group, time_limit=time_limit,size_limit=size_limit, scope=_ldap.SCOPE_BASE, normalize=normalize)
# If there is an exception here, it is likely due to a failure in # referential integrity. All members should have corresponding # memberOf entries. except ValueError, e: self.info('Failed to remove indirect entry %s from %s' % r[0], entry_dn) raise e
"""Mark entry active/inactive."""
# get the entry in question
# check nsAccountLock attribute raise errors.AlreadyActive() else: raise errors.AlreadyInactive()
# LDAP expects string instead of Bool but it also requires it to be TRUE or FALSE, # not True or False as Python stringification does. Thus, we uppercase it.
"""Mark entry active."""
"""Mark entry inactive."""
"""Remove a kerberos principal key."""
# We need to do this directly using the LDAP library because we # don't have read access to krbprincipalkey so we need to delete # it in the blind. (_ldap.MOD_REPLACE, 'krblastpwdchange', None)]
except _ldap.LDAPError, e: self.handle_errors(e)
# CrudBackend methods
assert isinstance(dn, DN)
(dn, entry_attrs) = self.get_entry(dn, attrs_list) entry_attrs['dn'] = dn return entry_attrs
""" Create a new entry and return it as one dict (DN included).
Extends CrudBackend.create. """ assert 'dn' in kw dn = kw['dn'] assert isinstance(dn, DN) del kw['dn'] self.add_entry(dn, kw) return self._get_normalized_entry_for_crud(dn)
""" Get entry by primary_key (DN) as one dict (DN included).
Extends CrudBackend.retrieve. """ return self._get_normalized_entry_for_crud(primary_key, attributes)
""" Update entry's attributes and return it as one dict (DN included).
Extends CrudBackend.update. """ self.update_entry(primary_key, kw) return self._get_normalized_entry_for_crud(primary_key)
""" Delete entry by primary_key (DN).
Extends CrudBackend.delete. """ self.delete_entry(primary_key)
""" Return a list of entries (each entry is one dict, DN included) matching the specified criteria.
Keyword arguments: filter -- search filter (default: '') 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 '') scope -- search scope, see LDAP docs (default ldap2.SCOPE_SUBTREE)
Extends CrudBackend.search. """ # get keyword arguments filter = kw.pop('filter', None) attrs_list = kw.pop('attrs_list', None) base_dn = kw.pop('base_dn', DN()) assert isinstance(base_dn, DN) scope = kw.pop('scope', self.SCOPE_SUBTREE)
# generate filter filter_tmp = self.make_filter(kw) if filter: filter = self.combine_filters((filter, filter_tmp), self.MATCH_ALL) else: filter = filter_tmp if not filter: filter = '(objectClass=*)'
# find entries and normalize the output for CRUD output = [] (entries, truncated) = self.find_entries( filter, attrs_list, base_dn, scope ) for (dn, entry_attrs) in entries: entry_attrs['dn'] = [dn] output.append(entry_attrs)
if truncated: return (-1, output) return (len(output), output)
|