Python ldap.NO_SUCH_OBJECT Examples

The following are 15 code examples of ldap.NO_SUCH_OBJECT(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ldap , or try the search function .
Example #1
Source File: users.py    From core with GNU General Public License v3.0 6 votes vote down vote up
def update_adminsudo(self):
        """Update the user's admin and sudo group settings in LDAP."""
        ldif = conns.LDAP.search_s(
            "cn=admins,ou=groups,{0}".format(self.rootdn),
            ldap.SCOPE_SUBTREE, "(objectClass=*)", None)[0][1]
        memlist = ldif["member"]
        ldif_vals = [(1, "member", None), (0, "member", memlist)]

        if self.admin and b(self.ldap_id) not in memlist:
            memlist += [b(self.ldap_id)]
            conns.LDAP.modify_s(
                "cn=admins,ou=groups,{0}".format(self.rootdn), ldif_vals)
        elif not self.admin and self.ldap_id in memlist:
            memlist.remove(self.ldap_id)
            conns.LDAP.modify_s(
                "cn=admins,ou=groups,{0}".format(self.rootdn), ldif_vals)

        try:
            conns.LDAP.search_s(
                "cn={0},ou=sudo,{1}".format(
                    self.name, self.rootdn),
                ldap.SCOPE_SUBTREE, "(objectClass=*)", None)
            is_sudo = True
        except ldap.NO_SUCH_OBJECT:
            is_sudo = False

        if self.sudo and not is_sudo:
            nldif = {
                "objectClass": [b"sudoRole", b"top"],
                "cn": [b(self.name)],
                "sudoHost": b"ALL",
                "sudoCommand": b"ALL",
                "sudoUser": [b(self.name)],
                "sudoOption": b"authenticate"
            }
            nldif = ldap.modlist.addModlist(nldif)
            conns.LDAP.add_s(
                "cn=" + self.name + ",ou=sudo," + self.rootdn, nldif)
        elif not self.sudo and is_sudo:
            conns.LDAP.delete_s(
                "cn=" + self.name + ",ou=sudo," + self.rootdn) 
Example #2
Source File: groups.py    From core with GNU General Public License v3.0 6 votes vote down vote up
def add(self):
        """Add the group to LDAP."""
        try:
            ldif = conns.LDAP.search_s(self.ldap_id, ldap.SCOPE_SUBTREE,
                                       "(objectClass=*)", None)
            emsg = "A group with this name already exists"
            raise errors.InvalidConfigError(emsg)
        except ldap.NO_SUCH_OBJECT:
            pass
        ldif = {
            "objectClass": [b"posixGroup", b"top"],
            "cn": [b(self.name)],
            "gidNumber": [b(str(self.gid))]
        }
        if self.users:
            ldif["memberUid"] = [b(u) for u in self.users]
        ldif = ldap.modlist.addModlist(ldif)
        signals.emit("groups", "pre_add", self)
        conns.LDAP.add_s(self.ldap_id, ldif)
        signals.emit("groups", "post_add", self) 
Example #3
Source File: freeipaserver.py    From checkipaconsistency with GNU General Public License v3.0 6 votes vote down vote up
def _get_conn(self):
        self._log.debug('Setting up LDAP connection')
        ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

        try:
            conn = ldap.initialize(self._url)
            conn.set_option(ldap.OPT_NETWORK_TIMEOUT, 3)
            conn.set_option(ldap.OPT_REFERRALS, ldap.OPT_OFF)
            conn.simple_bind_s(self._binddn, self._bindpw)
        except (
            ldap.SERVER_DOWN,
            ldap.NO_SUCH_OBJECT,
            ldap.INVALID_CREDENTIALS
        ) as e:
            if hasattr(e, 'message') and 'desc' in e.message:
                msg = e.message['desc']
            else:
                msg = e.args[0]['desc']
            self._log.debug('%s (%s)' % (msg, self._url))
            return False

        self._log.debug('LDAP connection established')
        return conn 
Example #4
Source File: tools.py    From cassh with Apache License 2.0 5 votes vote down vote up
def get_memberof(realname, server_options, reuse=None):
    """
    Returns the list of memberOf groups
    """
    if not server_options['ldap']:
        return list(), None
    if reuse:
        ldap_conn = reuse
    else:
        ldap_conn, err_msg = get_ldap_conn(
            server_options['ldap_host'],
            server_options['ldap_username'],
            server_options['ldap_password'])
        if err_msg:
            return list(), 'Error: wrong cassh ldap credentials'
    try:
        output = ldap_conn.search_s(
            server_options['ldap_bind_dn'],
            SCOPE_SUBTREE,
            filterstr='(&({}={}))'.format(
                server_options['ldap_filter_realname_key'],
                realname))
    except NO_SUCH_OBJECT:
        return list(), 'Error: admin LDAP filter is incorrect (no such object).'
    if not isinstance(output, list) or not output:
        return list(), None
    if len(output) != 1:
        return list(), 'Error: admin LDAP filter is incorrect (multiple user).'
    ldap_infos = output[0]
    if not isinstance(output, list) or not output:
        return list(), None
    for i in ldap_infos:
        if isinstance(i, dict) and server_options['ldap_filter_memberof_key'] in i:
            if isinstance(i[server_options['ldap_filter_memberof_key']], list):
                return i[server_options['ldap_filter_memberof_key']], None
            return list(), 'Error: admin LDAP output is incorrect.'
    return list(), 'Error: admin LDAP filter is incorrect.' 
Example #5
Source File: sync_ldap_groups_to_svn_authz.py    From sync-ldap-groups-to-svn-authz with MIT License 5 votes vote down vote up
def get_groups(ldapobject):
  """This function will search the LDAP directory for the specificied group DNs."""

  groups = []
  for group_dn in group_dns:
    try:
      result_set = get_ldap_search_resultset(group_dn, group_query, ldapobject, ldap.SCOPE_BASE)
      for i in range(len(result_set)):
        for entry in result_set[i]:
          groups.append(entry)
    except ldap.NO_SUCH_OBJECT, e:
      if not silent:
        sys.stderr.write("Couldn't find a group with DN %s.\n" % group_dn)
      raise e 
Example #6
Source File: users.py    From core with GNU General Public License v3.0 5 votes vote down vote up
def update(self, newpasswd=""):
        """
        Update a user's object in LDAP. Change params on the object first.

        To change password, do so via the ``newpasswd`` param here.

        :param str newpasswd: new password to set
        """
        try:
            ldif = conns.LDAP.search_s(self.ldap_id, ldap.SCOPE_SUBTREE,
                                       "(objectClass=*)", None)
        except ldap.NO_SUCH_OBJECT:
            raise errors.InvalidConfigError(
                "Users", "This user does not exist")

        self.mail = list(set(self.mail))

        for i, x in enumerate(self.mail):
            if not x.endswith(self.domain):
                self.mail[i] = x.split("@")[0] + "@" + self.domain

        ldif = ldif[0][1]
        attrs = {
            "givenName": [b(self.first_name)],
            "sn": [b(self.last_name)] if self.last_name else [b"NONE"],
            "displayName": [b(self.full_name)],
            "cn": [b(self.full_name)],
            "mail": [b(x) for x in self.mail]
        }
        if newpasswd:
            attrs["userPassword"] = [b(ldap_sha512_crypt.encrypt(newpasswd))]
        signals.emit("users", "pre_update", self)
        nldif = ldap.modlist.modifyModlist(ldif, attrs, ignore_oldexistent=1)
        conns.LDAP.modify_s(self.ldap_id, nldif)

        self.update_adminsudo()
        self.update_samba(newpasswd)

        signals.emit(
            "users", "post_update", {"user": self, "passwd": newpasswd}
        ) 
Example #7
Source File: domains.py    From core with GNU General Public License v3.0 5 votes vote down vote up
def add(self):
        """Add the domain to LDAP."""
        try:
            ldif = conns.LDAP.search_s(self.ldap_id, ldap.SCOPE_SUBTREE,
                                       "(objectClass=*)", None)
            emsg = "This domain is already present here"
            raise errors.InvalidConfigError(emsg)
        except ldap.NO_SUCH_OBJECT:
            pass
        ldif = {"virtualdomain": [b(self.name)],
                "objectClass": [b"mailDomain", b"top"]}
        signals.emit("domains", "pre_add", self)
        conns.LDAP.add_s(self.ldap_id, ldap.modlist.addModlist(ldif))
        signals.emit("domains", "post_add", self) 
Example #8
Source File: plugin.py    From allura with Apache License 2.0 5 votes vote down vote up
def _validate_password(self, username, password):
        '''by username'''
        password = h.really_unicode(password).encode('utf-8')
        try:
            ldap_user = ldap_user_dn(username)
        except ValueError:
            return False
        try:
            con = ldap_conn(ldap_user, password)
            con.unbind_s()
            return True
        except (ldap.INVALID_CREDENTIALS, ldap.UNWILLING_TO_PERFORM, ldap.NO_SUCH_OBJECT):
            log.debug('LdapAuth: could not authenticate {}'.format(username), exc_info=True)
        return False 
Example #9
Source File: plugin.py    From allura with Apache License 2.0 5 votes vote down vote up
def _get_pref(self, username, pref_name):
        con = ldap_conn()
        try:
            rs = con.search_s(ldap_user_dn(username), ldap.SCOPE_BASE)
        except ldap.NO_SUCH_OBJECT:
            rs = []
        else:
            con.unbind_s()
        if not rs:
            log.warning('LdapUserPref: No user record found for: {}'.format(username))
            return ''
        user_dn, user_attrs = rs[0]
        ldap_attr = self.fields[pref_name]
        # assume single-valued list
        return user_attrs[ldap_attr][0].decode('utf-8') 
Example #10
Source File: freeipaserver.py    From checkipaconsistency with GNU General Public License v3.0 5 votes vote down vote up
def _search(self, base, fltr, attrs=None, scope=ldap.SCOPE_SUBTREE):
        self._log.debug('Search base: %s, filter: %s, attributes: %s, scope: %s' % (base, fltr, attrs, scope))
        try:
            results = self._conn.search_s(base, scope, fltr, attrs)
        except (ldap.NO_SUCH_OBJECT, ldap.SERVER_DOWN) as e:
            self._log.debug(self._get_ldap_msg(e))
            results = False
        except ldap.REFERRAL as e:
            self._log.critical("Replica %s is temporarily unavailable." % self._fqdn)
            self._log.debug("Replica redirected")
            self._log.debug(e.message['info'])
            exit(1)
        return results 
Example #11
Source File: user.py    From daf-recipes with GNU General Public License v3.0 4 votes vote down vote up
def _ldap_search(cnx, filter_str, attributes, non_unique='raise'):
    """Helper function to perform the actual LDAP search

    @param cnx: The LDAP connection object
    @param filter_str: The LDAP filter string
    @param attributes: The LDAP attributes to fetch. This *must* include self.ldap_username
    @param non_unique: What to do when there is more than one result. Can be either 'log' (log an error
                       and return None - used to indicate that this is a configuration problem that needs
                       to be address by the site admin, not by the current user) or 'raise' (raise an
                       exception with a message that will be displayed to the current user - such
                       as 'please use your unique id instead'). Other values will silently ignore the error.
    @return: A dictionary defining 'cn', self.ldap_username and any other attributes that were defined
             in attributes; or None if no user was found.
    """
    try:
        res = cnx.search_s(config['ckanext.ldap.base_dn'], ldap.SCOPE_SUBTREE, filterstr=filter_str, attrlist=attributes)
    except ldap.SERVER_DOWN:
        log.error('LDAP server is not reachable')
        return None
    except ldap.OPERATIONS_ERROR as e:
        log.error('LDAP query failed. Maybe you need auth credentials for performing searches? Error returned by the server: ' + e.info)
        return None
    except (ldap.NO_SUCH_OBJECT, ldap.REFERRAL) as e:
        log.error('LDAP distinguished name (ckanext.ldap.base_dn) is malformed or does not exist.')
        return None
    except ldap.FILTER_ERROR:
        log.error('LDAP filter (ckanext.ldap.search) is malformed')
        return None
    if len(res) > 1:
        if non_unique == 'log':
            log.error('LDAP search.filter search returned more than one entry, ignoring. Fix the search to return only 1 or 0 results.')
        elif non_unique == 'raise':
            raise MultipleMatchError(config['ckanext.ldap.search.alt_msg'])
        return None
    elif len(res) == 1:
        cn = res[0][0]
        attr = res[0][1]
        ret = {
            'cn': cn,
        }

        # Check required fields
        for i in ['username', 'email']:
            cname = 'ckanext.ldap.' + i
            if config[cname] not in attr or not attr[config[cname]]:
                log.error('LDAP search did not return a {}.'.format(i))
                return None
        # Set return dict
        for i in ['username', 'fullname', 'email', 'about']:
            cname = 'ckanext.ldap.' + i
            if cname in config and config[cname] in attr:
                v = attr[config[cname]]
                if v:
                    ret[i] = v[0]
        return ret
    else:
        return None 
Example #12
Source File: users.py    From core with GNU General Public License v3.0 4 votes vote down vote up
def add(self, passwd):
        """
        Add the user to LDAP.

        :param str passwd: user password to set
        """
        try:
            ldif = conns.LDAP.search_s(
                self.ldap_id, ldap.SCOPE_BASE, "(objectClass=*)", None)
            msg = "A user named {0} already exists".format(self.name)
            raise errors.InvalidConfigError(msg)
        except ldap.NO_SUCH_OBJECT:
            pass

        # Create LDAP user with proper metadata
        ldif = {
            "objectClass": [b"mailAccount", b"inetOrgPerson", b"posixAccount"],
            "givenName": [b(self.first_name)],
            "sn": [b(self.last_name)] if self.last_name else [b"NONE"],
            "displayName": [b(self.full_name)],
            "cn": [b(self.full_name)],
            "uid": [b(self.name)],
            "mail": [b(self.name + "@" + self.domain)],
            "maildrop": [b(self.name)],
            "userPassword": [b(ldap_sha512_crypt.encrypt(passwd))],
            "gidNumber": [b"100"],
            "uidNumber": [b(str(self.uid))],
            "homeDirectory": [b("/home/" + self.name)],
            "loginShell": [b"/usr/bin/bash"]
            }
        ldif = ldap.modlist.addModlist(ldif)
        signals.emit("users", "pre_add", self)
        logger.debug("Roles", "Adding user: {0}".format(self.ldap_id))
        conns.LDAP.add_s(self.ldap_id, ldif)
        modes = ["admin" if self.admin else "", "sudo" if self.sudo else ""]
        msg = "Setting user modes: {0}".format(", ".join(modes))
        logger.debug("Roles", msg)

        self.update_adminsudo()
        self.update_samba(passwd)

        signals.emit("users", "post_add", {"user": self, "passwd": passwd}) 
Example #13
Source File: users.py    From core with GNU General Public License v3.0 4 votes vote down vote up
def get(uid=None, name=None):
    """
    Get all LDAP users.

    :param str id: ID of single user to fetch
    :param str name: username of single user to fetch
    :returns: User(s)
    :rtype: User or list thereof
    """
    r = []
    rootdn = config.get("general", "ldap_rootdn")
    ldap_users = conns.LDAP.search_s("ou=users," + rootdn, ldap.SCOPE_SUBTREE,
                                     "(objectClass=inetOrgPerson)", None)
    for x in ldap_users:
        for y in x[1]:
            if y == "mail":
                continue
            if type(x[1][y]) == list and len(x[1][y]) == 1:
                x[1][y] = x[1][y][0]
        u = User(x[1]["uid"].decode(), x[1]["givenName"].decode(),
                 x[1]["sn"].decode() if x[1]["sn"] != b"NONE" else None,
                 int(x[1]["uidNumber"]),
                 x[1]["mail"][0].split(b"@")[1].decode(),
                 x[0].split("ou=users,")[1],
                 [z.decode() for z in x[1]["mail"]])

        # Check if the user is a member of the admin or sudo groups
        try:
            conns.LDAP.search_s("cn={0},ou=sudo,{1}".format(u.name, u.rootdn),
                                ldap.SCOPE_SUBTREE, "(objectClass=*)", None)
            u.sudo = True
        except ldap.NO_SUCH_OBJECT:
            u.sudo = False
        memlist = conns.LDAP.search_s("cn=admins,ou=groups,{0}"
                                      .format(u.rootdn), ldap.SCOPE_SUBTREE,
                                      "(objectClass=*)", None)[0][1]["member"]
        if b("uid={0},ou=users,{1}".format(u.name, u.rootdn)) in memlist:
            u.admin = True
        else:
            u.admin = False

        if u.uid == uid:
            return u
        elif name and u.name == name:
            return u
        r.append(u)
    return r if uid is None and name is None else None 
Example #14
Source File: backendLdap.py    From ldapcherry with MIT License 4 votes vote down vote up
def add_to_groups(self, username, groups):
        ldap_client = self._bind()
        # recover dn of the user and his attributes
        tmp = self._get_user(self._byte_p2(username), ALL_ATTRS)
        dn = tmp[0]
        attrs = tmp[1]
        attrs['dn'] = dn
        self._normalize_group_attrs(attrs)
        dn = self._byte_p2(tmp[0])
        # add user to all groups
        for group in groups:
            group = self._byte_p2(group)
            # iterate on group membership attributes
            for attr in self.group_attrs:
                # fill the content template
                content = self._byte_p2(self.group_attrs[attr] % attrs)
                self._logger(
                    severity=logging.DEBUG,
                    msg="%(backend)s: adding user '%(user)s'"
                        " with dn '%(dn)s' to group '%(group)s' by"
                        " setting '%(attr)s' to '%(content)s'" % {
                            'user': username,
                            'dn': self._uni(dn),
                            'group': self._uni(group),
                            'attr': attr,
                            'content': self._uni(content),
                            'backend': self.backend_name
                            }
                )
                ldif = modlist.modifyModlist(
                        {},
                        {attr: self._modlist(self._byte_p3(content))}
                       )
                try:
                    ldap_client.modify_s(group, ldif)
                # if already member, not a big deal, just log it and continue
                except (ldap.TYPE_OR_VALUE_EXISTS, ldap.ALREADY_EXISTS) as e:
                    self._logger(
                        severity=logging.INFO,
                        msg="%(backend)s: user '%(user)s'"
                            " already member of group '%(group)s'"
                            " (attribute '%(attr)s')" % {
                                'user': username,
                                'group': self._uni(group),
                                'attr': attr,
                                'backend': self.backend_name
                                }
                    )
                except ldap.NO_SUCH_OBJECT as e:
                    raise GroupDoesntExist(group, self.backend_name)
                except Exception as e:
                    ldap_client.unbind_s()
                    self._exception_handler(e)
        ldap_client.unbind_s() 
Example #15
Source File: slapd.py    From datadog-checks with MIT License 4 votes vote down vote up
def fetch_metric(self, conn, bind, type=int):
        self.log.debug("Running bind: {1}", bind)

        try:
            res = conn.search_s(bind, ldap.SCOPE_SUBTREE, '(objectClass=*)', ['*', '+'])
            if len(res) == 0:
                self.log.warn("No results for bind: {0}", bind)
                return None
        except ldap.NO_SUCH_OBJECT:
            self.log.warn("No such object for bind: {0}", bind)
            return None
        except ldap.LDAPError as e:
            self.log.error("Unexpected error for bind {0}:", bind, e)
            return None

        # Take first result from the server
        _, attrs = res[0]

        obj_class = attrs['structuralObjectClass'][0]
        if obj_class == 'monitoredObject':
            value_field = 'monitoredInfo'
        elif obj_class == 'monitorCounterObject':
            value_field = 'monitorCounter'
        else:
            self.log.error("Unknown type of metric: {0}", obj_class)
            return None

        try:
            # Since a single result can contain multiple values, we also take
            # the first element in the list.
            value = attrs[value_field][0]
        except (KeyError, IndexError):
            self.log.error("Unable to extract value from bind: {0}", bind)
            return None

        # Try to convert by passing the value to the type of the metric.
        converted = value
        if type is not None:
            try:
                converted = type(value)
            except (ValueError, TypeError):
                self.log.warn('Unable to convert metric for bind {0}: {1} cannot be converted to {2}',
                    bind,
                    value,
                    type.__name__
                )

        self.log.debug("Finished with bind: {0}", bind)
        return converted