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> # # 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
# Group Member types
# SASL authentication mechanism
# OID 1.3.6.1.4.1.1466.115.121.1.7 (Boolean) syntax encoding
return tuple(encode_bool_value(v) for v in value) else:
# set own Bool parameter encoder
''' This is a thin layer over SimpleLDAPObject which allows us to utilize IPA specific types with the python-ldap API without the IPA caller needing to perform the type translation, consider this a convenience layer for the IPA programmer.
This subclass performs the following translations:
* DN objects may be passed into any ldap function expecting a dn. The DN object will be converted to a string before being passed to the python-ldap function. This allows us to maintain DN objects as DN objects in the rest of the code (useful for DN manipulation and DN information) and not have to worry about conversion to a string prior to passing it ldap.
'''
return SimpleLDAPObject.add_ext_s(self, str(dn), modlist, serverctrls, clientctrls)
return SimpleLDAPObject.compare(self, str(dn), attr, value)
return SimpleLDAPObject.compare_ext(self, str(dn), attr, value, serverctrls, clientctrls)
return SimpleLDAPObject.compare_ext_s(self, str(dn), attr, value, serverctrls, clientctrls)
return SimpleLDAPObject.compare_s(self, str(dn), attr, value)
return SimpleLDAPObject.delete(self, str(dn))
return SimpleLDAPObject.modify_ext_s(self, str(dn), modlist, serverctrls, clientctrls)
return SimpleLDAPObject.modrdn(self, str(dn), str(newrdn), delold)
return SimpleLDAPObject.modrdn_s(self, str(dn), str(newrdn), delold)
return SimpleLDAPObject.read_subschemasubentry_s(self, str(subschemasubentry_dn), attrs)
return SimpleLDAPObject.rename(self, str(dn), str(newrdn), newsuperior, delold, serverctrls, clientctrls)
return SimpleLDAPObject.rename_s(self, str(dn), str(newrdn), newsuperior, delold, serverctrls, clientctrls)
serverctrls=None, clientctrls=None, timeout=-1, sizelimit=0): serverctrls, clientctrls, timeout, sizelimit)
serverctrls=None, clientctrls=None, timeout=-1, sizelimit=0): return SimpleLDAPObject.search_ext_s(self, str(base), scope, filterstr, attrlist, attrsonly, serverctrls, clientctrls, timeout, sizelimit)
return SimpleLDAPObject.search_s(self, str(base), scope, filterstr, attrlist, attrsonly)
return SimpleLDAPObject.search_st(self, str(base), scope, filterstr, attrlist, attrsonly, timeout)
return SimpleLDAPObject.search_subschemasubentry_s(self, str(dn))
# universal LDAPError handler """ Centralize error handling in one place.
e is the error to be raised **kw is an exception-specific list of options """ else: desc = '' info = ''
# re-raise the error so we can handle it # args = kw.get('args', '') # raise errors.NotFound(msg=notfound(args)) # This error gets thrown by the uniqueness plugin 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")
""" Perform global initialization when the module is loaded.
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. """
and conn is None): # The schema is only needed on the server side return None
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) 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)))
conn = IPASimpleLDAPObject(url) if url.startswith('ldapi://'): conn.set_option(_ldap.OPT_HOST_NAME, api.env.host) conn.sasl_interactive_bind_s('', SASL_AUTH)
'cn=schema', _ldap.SCOPE_BASE, attrlist=['attributetypes', 'objectclasses'] )[0] conn.unbind_s() except _ldap.SERVER_DOWN: return None except _ldap.LDAPError, e: desc = e.args[0]['desc'].strip() info = e.args[0].get('info', '').strip() raise StandardError('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)
# Global schema
""" LDAP Backend Take 2. """ # attribute syntax to python type mapping, 'SYNTAX OID': type # everything not in this dict is considered human readable unicode '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 }
# 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): global _schema except AttributeError: self.ldap_uri = 'ldap://example.com' else: except AttributeError: self.base_dn = ''
if self.isconnected(): self.disconnect()
return self.ldap_uri
else:
if not self.schema: self.get_schema() 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))]
""" 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 """ self.get_schema()
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. """ global _schema _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.
Note: You don't have to normalize DN's before passing them to ldap2 methods. It's done internally for you. """
"""Get relative distinguished name of cotainer.""" env_container = 'container_%s' % name if env_container in self.api.env: return self.api.env[env_container] return ''
"""Make relative distinguished name from attribute."""
""" Make distinguished name from relative distinguished name.
Keyword arguments: parent_dn -- DN of the parent entry (default '') """
""" Make distinguished name from attribute.
Keyword arguments: parent_dn -- DN of the parent entry (default '') """
""" 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 '') """
"""Create a new entry.""" # remove all None values, python-ldap hates'em (k, v) for (k, v) in entry_attrs.iteritems() if 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) """
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) else: continue
base_dn=''): """ 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 either a reference to current schema or its deep copy""" global _schema raise errors.DatabaseError(desc='Unable to retrieve LDAP schema', info='Unable to proceed with request') # explicitly use setattr here so the schema can be set after # the object is finalized.
return copy.deepcopy(self.schema) else:
"""Returns True/False whether User-Private Groups are enabled. This is determined based on whether the UPG Template exists. """
upg_dn, _ldap.SCOPE_BASE, attrlist=['*'] )[0] else: return False except _ldap.NO_SUCH_OBJECT, e: return False
def get_effective_rights(self, dn, entry_attrs): """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
def can_write(self, dn, attr): """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
def can_read(self, dn, attr): """Returns True/False if the currently bound user has read permissions on the attribute. This only operates on a single attribute at a time. """ (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 #
def can_delete(self, dn): """Returns True/False if the currently bound user has delete permissions on the entry. """ (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
def can_add(self, dn): """Returns True/False if the currently bound user has add permissions on the entry. """ (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 # get_entry returns a decoded entry, encode it back # we could call search_s directly, but this saves a lot of code at # the expense of a little bit of performace # 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 = _ldap.initialize(self.ldap_uri) conn.simple_bind_s(dn, old_pass) conn.unbind() except _ldap.LDAPError, e: _handle_errors(e, **{})
except _ldap.LDAPError, e: _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 dn.endswith(DN(api.env.container_host, api.env.basedn)): attr_list, member, 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) real_members = [real_members] real_members = []
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: root_logger.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: _handle_errors(e)
# CrudBackend methods
(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'] 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', '') 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)
|