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: 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/>. #
format_netloc, wait_for_open_socket, wait_for_open_ports, CIDict)
# Global variable to define SASL auth
# Group Member types
''' 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.log.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. """
'retrieving schema for SchemaCache url=%s conn=%s', url, conn)
attrlist=['attributetypes', 'objectclasses'])[0] except ldap.NO_SUCH_OBJECT: # try different location for schema # openldap has schema located in cn=subschema self.log.debug('cn=schema not found, fallback to cn=subschema') 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') except ldap.LDAPError, e: 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)) 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 })
decode_attrs=True): """An internal LDAP connection object
:param uri: The LDAP URI to connect to :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. """
return None self.uri, self.conn, force_update=self._force_schema_updates) except (errors.ExecutionError, IndexError): pass
''' 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?
return None
# 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 """ syntax = self.get_syntax(attr) return syntax == DN_SYNTAX_OID
''' ''' # 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)))
''' '''
return values
else: except Exception, e: msg = 'unable to convert the attribute "%s" value "%s" to type %s' % (attr, original_value, target_type) self.log.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.log.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)
# NOTICE: python-ldap of version 2.3.10 and lower does not support # serverctrls and clientctrls for rename_s operation. Thus, these # options are ommited from this command until really needed
clientctrls=None, sasl_flags=ldap.SASL_QUIET):
assert isinstance(base, DN) base = str(base) filterstr = self.encode(filterstr) attrlist = self.encode(attrlist) return self.conn.search(base, scope, filterstr, attrlist, attrsonly)
self.log.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()
# 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
""" 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 specified IPASimpleLDAPObject and DN and optionally initialize attributes from the specified mapping object.
Keyword arguments can be used to override values of specific attributes. """
assert _dn is None _dn = _conn _conn = _conn._conn
assert _obj is None _obj = _dn _dn = DN(_dn._dn)
else:
def conn(self):
# properties for Entry and Entity compatibility def dn(self):
def dn(self, value):
def data(self): # FIXME: for backwards compatibility only return self
def orig_data(self): # FIXME: for backwards compatibility only return self._orig
super(LDAPEntry, self).__repr__())
return LDAPEntry(self)
name, deepcopy(super(LDAPEntry, self).__getitem__(name)))
result._orig = self._orig.clone()
""" Make the current state of the entry a new reference point for change tracking. """ self._orig = self self._orig = self.clone()
raise TypeError( "attribute name must be unicode or str, got %s object %r" % ( name.__class__.__name__, name))
else:
name.encode('utf-8'))
# for python-ldap tuple compatibility
"""Return a single attribute value
Checks that the attribute really has one and only one value
If the entry is missing and default is given, return the default. If the entry is missing and default is not given, raise KeyError. """ return values raise ValueError( '%s has %s values, one expected' % (name, len(values)))
# for python-ldap tuple compatibility
# FIXME: for backwards compatibility only """Convert the attrs and values to a dict. The dict is keyed on the attribute name. The value is either single value or a list of values.""" assert isinstance(self.dn, DN) result = ipautil.CIDict(self.data) for i in result.keys(): result[i] = ipautil.utf8_encode_values(result[i]) result['dn'] = self.dn return result
"""Returns a dict of the original values of the user.
Used for updates. """ result = ipautil.CIDict(self.orig_data) result['dn'] = self.dn return result
"""LDAP backend class
This class abstracts a LDAP connection, providing methods that work with LADPEntries.
This class is not intended to be used directly; instead, use one of its subclasses, IPAdmin or the ldap2 plugin. """
# rules for generating filters from entries
# search scope for find_entries()
self.conn = None
"""Return the API if available, otherwise None
May be overridden in a subclass. """ return None
"""Context manager that handles LDAPErrors """ raise errors.DatabaseTimeout() info = "%s arguments: %s" % (info, arg_desc) # This error gets thrown by the uniqueness plugin raise errors.DuplicateEntry() else: 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) raise errors.NetworkError(uri=self.ldap_uri, error=info) raise errors.ACIError(info=info) pass raise errors.DatabaseError(desc=desc, info=info) raise errors.ACIError( info="KDC returned NOT_ALLOWED_TO_DELEGATE") 'Unhandled LDAPError: %s: %s' % (type(e).__name__, str(e)))
def schema(self): """schema associated with this LDAP server"""
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 self.conn.has_dn_syntax(attr)
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
""" 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 '') """
# 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
self, attr, value, rules='|', exact=True, 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 """ else: self.make_filter_from_attr( attr, v, exact=exact, leading_wildcard=leading_wildcard, trailing_wildcard=trailing_wildcard) for v in value ] return '(!(%s=%s))' % (attr, value)
self, entry_attrs, attrs_list=None, rules='|', exact=True, 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 """ else: 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) )
"""Return a list of matching entries.
Raises an error if the list is truncated by the server
: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)
Use the find_entries method for more options. """ entries, truncated = self.find_entries( base_dn=base_dn, scope=scope, filter=filter, attrs_list=attrs_list) if truncated: raise errors.LimitsExceeded() return entries
scope=ldap.SCOPE_SUBTREE, time_limit=None, size_limit=None, 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) 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:
'memberindirect' in attrs_list or '*' in attrs_list): else: r[0], members, membertype=MEMBERS_INDIRECT, time_limit=time_limit, size_limit=size_limit) 'memberofindirect' in attrs_list or '*' in attrs_list): memberof = r[1]['memberOf'] del r[1]['memberOf'] else: continue r[0], memberof, time_limit=time_limit, size_limit=size_limit)
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 '') """
base_dn = DN()
else: raise errors.LimitsExceeded() else:
size_limit=None): """ 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 )
raise errors.LimitsExceeded()
"""Returns the IPA configuration entry.
Overriden in the subclasses that have access to IPA configuration. """ return {}
size_limit=None): """ 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) """
"get_memberof: entry_dn=%s memberof=%s", entry_dn, memberof) 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.
searchfilter, attr_list, group, time_limit=time_limit, size_limit=size_limit, scope=ldap.SCOPE_BASE)
# 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.log.info( 'Failed to remove indirect entry %s from %s', r[0], entry_dn) raise e
"get_memberof: result direct=%s indirect=%s", direct, indirect)
membertype=MEMBERS_ALL, time_limit=None, size_limit=None): """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
"get_members: group_dn=%s members=%s membertype=%s", group_dn, members, membertype)
# Verify group membership
else: user_container_dn = host_container_dn = None
# No need to check entry types that are not nested for # additional members member_dn.endswith(user_container_dn) or member_dn.endswith(host_container_dn)): searchfilter, attr_list, member_dn, time_limit=time_limit, size_limit=size_limit, scope=ldap.SCOPE_BASE) 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
group_dn, ['member'], size_limit=size_limit, time_limit=time_limit)
else: entries.append(e[0])
"""Helper for legacy calling style for {add,update}_entry """ return entry_or_dn.dn, entry_or_dn else:
"""Create a new entry.
This should be called as add_entry(entry).
The legacy two-argument variant is: add_entry(dn, entry_attrs) """
# remove all [] values (python-ldap hates 'em) # FIXME: Once entry values are always lists, this condition can # be just "if v": if v is not None and v != [])
""" 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 modlist.append((ldap.MOD_DELETE, k, None)) else:
# FIXME: Convert all values to either unicode, DN or str # before detecting value changes (see IPASimpleLDAPObject for # supported types). # This conversion will set a common ground for the comparison. # # This fix can be removed when ticket 2265 is fixed and our # encoded entry_attrs' types will match get_entry result unicode_from_utf8(self.conn.encode(value)) if not isinstance(value, (DN, str, unicode)) else value for value in v) except Exception, e: # Rather let the value slip in modlist than let ldap2 crash self.log.error( "Cannot convert attribute '%s' for modlist " "for modlist comparison: %s", k, e)
raise errors.OnlyOneValueAllowed(attr=k)
else:
"""Update entry's attributes.
This should be called as update_entry(entry).
The legacy two-argument variant is: update_entry(dn, entry_attrs) """
# generate modlist
# pass arguments to python-ldap
"""Delete an entry given either the DN or the entry itself""" else: dn = entry_or_dn.dn
if protocol == 'ldaps': return 'ldaps://%s' % format_netloc(self.host, self.port) elif protocol == 'ldapi': return 'ldapi://%%2fvar%%2frun%%2fslapd-%s.socket' % ( "-".join(self.realm.split("."))) elif protocol == 'ldap': return 'ldap://%s' % format_netloc(self.host, self.port) else: raise ValueError('Protocol %r not supported' % protocol)
"""Return the protocol to use based on flags passed to the constructor
Only used when "protocol" is not specified explicitly.
If a CA certificate is provided then it is assumed that we are doing SSL client authentication with proxy auth.
If a CA certificate is not present then it is assumed that we are using a forwarded kerberos ticket for SASL auth. SASL provides its own encryption. """ if self.cacert is not None: return 'ldaps' elif self.ldapi: return 'ldapi' else: return 'ldap'
realm=None, protocol=None, force_schema_updates=True, start_tls=False, ldap_uri=None, no_schema=False, decode_attrs=True, sasl_nocanon=False, demand_cert=False): self.conn = None log_mgr.get_logger(self, True) if debug and debug.lower() == "on": ldap.set_option(ldap.OPT_DEBUG_LEVEL,255) if cacert is not None: ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, cacert)
self.port = port self.host = host self.cacert = cacert self.ldapi = ldapi self.realm = realm self.suffixes = {}
if not ldap_uri: ldap_uri = self.__get_ldap_uri(protocol or self.__guess_protocol())
LDAPClient.__init__(self, ldap_uri)
with self.error_handler(): self.conn = IPASimpleLDAPObject(ldap_uri, force_schema_updates=True, no_schema=no_schema, decode_attrs=decode_attrs)
if demand_cert: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, True) self.conn.set_option(ldap.OPT_X_TLS_DEMAND, True)
if sasl_nocanon: self.conn.set_option(ldap.OPT_X_SASL_NOCANON, ldap.OPT_ON)
if start_tls: self.conn.start_tls_s()
return self.host + ":" + str(self.port)
lurl = ldapurl.LDAPUrl(self.ldap_uri) if lurl.urlscheme == 'ldapi': wait_for_open_socket(lurl.hostport, timeout) else: (host,port) = lurl.hostport.split(':') wait_for_open_ports(host, int(port), timeout)
with self.error_handler(): try: bind_func(*args, **kwargs) except (ldap.CONNECT_ERROR, ldap.SERVER_DOWN), e: if not timeout or 'TLS' in e.args[0].get('info', ''): # No connection to continue on if we have a TLS failure # https://bugzilla.redhat.com/show_bug.cgi?id=784989 raise self.__wait_for_connection(timeout) bind_func(*args, **kwargs)
timeout=DEFAULT_TIMEOUT): self.__bind_with_wait(self.conn.simple_bind_s, timeout, binddn, bindpw)
self.__bind_with_wait( self.conn.sasl_interactive_bind_s, timeout, None, SASL_GSSAPI)
auth_tokens = ldap.sasl.external(user_name) self.__bind_with_wait( self.conn.sasl_interactive_bind_s, timeout, None, auth_tokens)
# FIXME: for backwards compatibility only """This wraps the mod function. It assumes that the entry is already populated with all of the desired objectclasses and attributes"""
assert isinstance(dn, DN)
modlist = self.generateModList(oldentry, newentry)
if len(modlist) == 0: raise errors.EmptyModlist
with self.error_handler(): self.modify_s(dn, modlist) return True
# FIXME: for backwards compatibility only """A mod list generator that computes more precise modification lists than the python-ldap version. For single-value attributes always use a REPLACE operation, otherwise use ADD/DEL. """
# Some attributes, like those in cn=config, need to be replaced # not deleted/added. FORCE_REPLACE_ON_UPDATE_ATTRS = ('nsslapd-ssl-check-hostname', 'nsslapd-lookthroughlimit', 'nsslapd-idlistscanlimit', 'nsslapd-anonlimitsdn', 'nsslapd-minssf-exclude-rootdse') modlist = []
old_entry = ipautil.CIDict(old_entry) new_entry = ipautil.CIDict(new_entry)
keys = set(map(string.lower, old_entry.keys())) keys.update(map(string.lower, new_entry.keys()))
for key in keys: new_values = new_entry.get(key, []) if not(isinstance(new_values,list) or isinstance(new_values,tuple)): new_values = [new_values] new_values = filter(lambda value:value!=None, new_values)
old_values = old_entry.get(key, []) if not(isinstance(old_values,list) or isinstance(old_values,tuple)): old_values = [old_values] old_values = filter(lambda value:value!=None, old_values)
# 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 = [x for x in new_values if x not in old_values] removes = [x for x in old_values if x not in new_values]
if len(adds) == 0 and len(removes) == 0: continue
is_single_value = self.get_single_value(key) force_replace = False if key in FORCE_REPLACE_ON_UPDATE_ATTRS or is_single_value: force_replace = True
# You can't remove schema online. An add will automatically # replace any existing schema. if old_entry.get('dn', DN()) == DN(('cn', 'schema')): if len(adds) > 0: modlist.append((ldap.MOD_ADD, key, adds)) else: if adds: if force_replace: modlist.append((ldap.MOD_REPLACE, key, adds)) else: modlist.append((ldap.MOD_ADD, key, adds)) if removes: if not force_replace: modlist.append((ldap.MOD_DELETE, key, removes)) elif new_values == []: # delete an empty value modlist.append((ldap.MOD_DELETE, key, removes))
return modlist
# FIXME: for backwards compatibility only return self.conn.modify_s(*args, **kwargs)
# FIXME: for backwards compatibility only return self.conn.set_option(*args, **kwargs)
# FIXME: for backwards compatibility only return self.conn.encode(*args, **kwargs)
return self.conn.unbind_s(*args, **kwargs) |