Python ldap.INVALID_CREDENTIALS Examples

The following are 30 code examples of ldap.INVALID_CREDENTIALS(). 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: connect_python_ldap.py    From Learning-Python-Networking-Second-Edition with MIT License 6 votes vote down vote up
def main():
	try:
		# Open a connection
		ldap_client = ldap.initialize(LDAP_SERVER)
		# Set LDAPv3 option
		ldap_client.set_option(ldap.OPT_PROTOCOL_VERSION,3)
		# Bind/authenticate with a user with appropriate rights
		ldap_client.simple_bind("admin",'Secret123')
		# Get user attributes defined in LDAP_ATTRS
		result = ldap_client.search_s(LDAP_BASE_DN,ldap.SCOPE_SUBTREE,LDAP_FILTER, LDAP_ATTRS)
		print(result)
	except ldap.INVALID_CREDENTIALS as exception:
		ldap_client.unbind()
		print('Wrong username or password. '+exception)
	except ldap.SERVER_DOWN as exception:
		print('LDAP server not available. '+exception) 
Example #2
Source File: user_management.py    From fame with GNU General Public License v3.0 6 votes vote down vote up
def ldap_authenticate(email, password):
    con = _ldap_get_con()
    if not con:
        raise LdapSettingsNotPresentException

    ldap_user = _find_user_by_email(con, email)

    if ldap_user:
        try:
            con.simple_bind_s(ldap_user['principal'], password)
            return ldap_user
        except ldap.INVALID_CREDENTIALS:
            # forward exception to view
            raise
        finally:
            con.unbind_s() 
Example #3
Source File: ldap_user.py    From MCVirt with GNU General Public License v2.0 6 votes vote down vote up
def _check_password(self, password):
        """Check the given password against the stored password for the user."""
        # If either username or password are empty strings or None, reject user.
        if not self.get_username() or not password:
            return False

        try:
            self.po__get_registered_object('ldap_factory').get_connection(bind_dn=self._get_dn(),
                                                                       password=password)
            return True
        except ldap.INVALID_CREDENTIALS:
            pass
        except MCVirtException:
            raise
        except Exception:
            raise LdapConnectionFailedException('An error occurred whilst connecting to LDAP')
        return False 
Example #4
Source File: users.py    From core with GNU General Public License v3.0 6 votes vote down vote up
def verify_passwd(self, passwd):
        """
        Validate the provided password against the hash stored in LDAP.

        :param str passwd: password to check
        """
        try:
            c = ldap.initialize("ldap://localhost")
            c.simple_bind_s(self.ldap_id, passwd)
            data = c.search_s("cn=admins,ou=groups," + self.rootdn,
                              ldap.SCOPE_SUBTREE, "(objectClass=*)",
                              ["member"])[0][1]["member"]
            if b(self.ldap_id) not in data:
                return False
            return True
        except ldap.INVALID_CREDENTIALS:
            return False 
Example #5
Source File: backendAD.py    From ldapcherry with MIT License 6 votes vote down vote up
def auth(self, username, password):

        binddn = username + '@' + self.domain
        if binddn is not None:
            ldap_client = self._connect()
            try:
                ldap_client.simple_bind_s(
                    self._byte_p2(binddn),
                    self._byte_p2(password)
                )
            except ldap.INVALID_CREDENTIALS:
                ldap_client.unbind_s()
                return False
            ldap_client.unbind_s()
            return True
        else:
            return False 
Example #6
Source File: backendLdap.py    From ldapcherry with MIT License 6 votes vote down vote up
def auth(self, username, password):
        """Authentication of a user"""

        binddn = self._get_user(self._byte_p2(username), NO_ATTR)
        if binddn is not None:
            ldap_client = self._connect()
            try:
                ldap_client.simple_bind_s(
                        self._byte_p2(binddn),
                        self._byte_p2(password)
                        )
            except ldap.INVALID_CREDENTIALS:
                ldap_client.unbind_s()
                return False
            ldap_client.unbind_s()
            return True
        else:
            return False 
Example #7
Source File: _helpers.py    From ckanext-ldap with GNU General Public License v3.0 6 votes vote down vote up
def check_ldap_password(cn, password):
    '''Checks that the given cn/password credentials work on the given CN.

    :param cn: Common name to log on
    :param password: Password for cn
    :returns: True on success, False on failure

    '''
    cnx = ldap.initialize(toolkit.config[u'ckanext.ldap.uri'], bytes_mode=False,
                          trace_level=toolkit.config[u'ckanext.ldap.trace_level'])
    try:
        cnx.bind_s(cn, password)
    except ldap.SERVER_DOWN:
        log.error(u'LDAP server is not reachable')
        return False
    except ldap.INVALID_CREDENTIALS:
        log.debug(u'Invalid LDAP credentials')
        return False
    # Fail on empty password
    if password == u'':
        log.debug(u'Invalid LDAP credentials')
        return False
    cnx.unbind_s()
    return True 
Example #8
Source File: forms.py    From flask-ldap-login with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def validate_ldap(self):
        'Validate the username/password data against ldap directory'
        ldap_mgr = current_app.ldap_login_manager
        username = self.username.data
        password = self.password.data
        try:
            userdata = ldap_mgr.ldap_login(username, password)
        except ldap.INVALID_CREDENTIALS:
            flash("Invalid LDAP credentials", 'danger')
            return False
        except ldap.LDAPError as err:
            if isinstance(err.message, dict):
                message = err.message.get('desc', str(err))
            else:
                message = str(err.message)
            flash(message, 'danger')
            return False

        if userdata is None:
            flash("Invalid LDAP credentials", 'danger')
            return False

        self.user = ldap_mgr._save_user(username, userdata)
        return True 
Example #9
Source File: plugin.py    From allura with Apache License 2.0 6 votes vote down vote up
def set_password(self, user, old_password, new_password):
        dn = ldap_user_dn(user.username)
        if old_password:
            ldap_ident = dn
            ldap_pass = old_password.encode('utf-8')
        else:
            ldap_ident = ldap_pass = None
        try:
            con = ldap_conn(ldap_ident, ldap_pass)
            new_password = self._encode_password(new_password)
            con.modify_s(
                dn, [(ldap.MOD_REPLACE, b'userPassword', new_password)])
            con.unbind_s()
            user.last_password_updated = datetime.utcnow()
            session(user).flush(user)
        except ldap.INVALID_CREDENTIALS:
            raise exc.HTTPUnauthorized() 
Example #10
Source File: data_backend_api.py    From n6 with GNU Affero General Public License v3.0 6 votes vote down vote up
def login(self, request, auth_api):
        post_data = request.POST
        try:
            user_id = post_data.getone('user_id')
            org_id = post_data.getone('org_id')
            password = post_data.getone('password')
        except KeyError as e:
            LOGGER.debug('User has not filled all credential fields for authentication. %s.',
                         e.message)
            raise HTTPForbidden
        if user_id and org_id and password:
            try:
                auth_api.authenticate_with_password(org_id, user_id, password)
            except INVALID_CREDENTIALS:
                LOGGER.warning('User tried to authenticate with invalid credentials. '
                               'User id: %r, organization id: %r.', user_id, org_id)
                raise HTTPForbidden
            credentials = self._join_org_id_user_id(org_id, user_id)
            headers = remember(request, credentials)
            self._add_content_type_header(headers)
            return Response(headerlist=headers) 
Example #11
Source File: ldap_auth.py    From kansha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check_password(self, uid, password):
        """Check if the specified couple user/password is correct

        In:
           - ``uid`` -- the user id
           - ``password`` -- the user password
        Return:
            - True if password is checked
        """
        c = self.connect()
        # Try to authenticate
        try:
            c.simple_bind_s(uid, password)
            return True
        except ldap.INVALID_CREDENTIALS:
            log.info("Bad credentials for uid %r" % uid)
        except ldap.SERVER_DOWN:
            log.critical("LDAP server down")
        finally:
            c.unbind() 
Example #12
Source File: ldap_auth.py    From kansha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check_password(self, uid, password):
        """Check if the specified couple user/password is correct

        In:
           - ``uid`` -- the user id
           - ``password`` -- the user password
        Return:
            - True if password is checked
        """
        c = self.connect()
        dn = self.get_user_dn(uid)
        # Try to authenticate
        try:
            c.simple_bind_s(dn, password.encode('UTF-8'))
            return True
        except ldap.INVALID_CREDENTIALS:
            log.info("Bad credentials for DN %r" % dn)
        except ldap.SERVER_DOWN:
            log.critical("LDAP server down")
        finally:
            c.unbind() 
Example #13
Source File: acl.py    From cmdb with GNU General Public License v2.0 6 votes vote down vote up
def authenticate_with_ldap(self, username, password):
        ldap_conn = ldap.initialize(current_app.config.get('LDAP_SERVER'))
        ldap_conn.protocol_version = 3
        ldap_conn.set_option(ldap.OPT_REFERRALS, 0)
        if '@' in username:
            who = '{0}@{1}'.format(username.split('@')[0], current_app.config.get('LDAP_DOMAIN'))
        else:
            who = '{0}@{1}'.format(username, current_app.config.get('LDAP_DOMAIN'))

        username = username.split('@')[0]
        user = self.get_by_username(username)
        try:

            if not password:
                raise ldap.INVALID_CREDENTIALS

            ldap_conn.simple_bind_s(who, password)

            if not user:
                from api.lib.perm.acl.user import UserCRUD
                user = UserCRUD.add(username=username, email=who)

            return user, True
        except ldap.INVALID_CREDENTIALS:
            return user, False 
Example #14
Source File: user.py    From daf-recipes with GNU General Public License v3.0 6 votes vote down vote up
def _check_ldap_password(cn, password):
    """Checks that the given cn/password credentials work on the given CN.

    @param cn: Common name to log on
    @param password: Password for cn
    @return: True on success, False on failure
    """
    cnx = ldap.initialize(config['ckanext.ldap.uri'])
    try:
        cnx.bind_s(cn, password)
    except ldap.SERVER_DOWN:
        log.error('LDAP server is not reachable')
        return False
    except ldap.INVALID_CREDENTIALS:
        log.debug('Invalid LDAP credentials')
        return False
    # Fail on empty password
    if password == '':
        log.debug('Invalid LDAP credentials')
        return False
    cnx.unbind_s()
    return True 
Example #15
Source File: __init__.py    From flask-ldap-login with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def direct_bind(self, username, password):
        """
        Bind to username/password directly
        """
        log.debug("Performing direct bind")

        ctx = {'username':username, 'password':password}
        scope = self.config.get('SCOPE', ldap.SCOPE_SUBTREE)
        user = self.config['BIND_DN'] % ctx

        try:
            log.debug("Binding with the BIND_DN %s" % user)
            self.conn.simple_bind_s(user, password)
        except ldap.INVALID_CREDENTIALS:
            if self._raise_errors:
                raise ldap.INVALID_CREDENTIALS("Unable to do a direct bind with BIND_DN %s" % user)
            return None
        results = self.conn.search_s(user, scope, attrlist=self.attrlist)
        self.conn.unbind_s()
        return self.format_results(results) 
Example #16
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 #17
Source File: views.py    From fame with GNU General Public License v3.0 6 votes vote down vote up
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        try:
            user = authenticate(request.form.get('email'), request.form.get('password'))
        except SERVER_DOWN:
            flash("LDAP Server down.", "danger")
            return render_template('login.html')
        except INVALID_CREDENTIALS:
            flash("Invalid credentials.", "danger")
            return render_template('login.html')
        except LdapSettingsNotPresentException:
            flash("LDAP Settings not present. Check server logs.", "danger")
            return render_template('login.html')

        if not user or not user_has_groups_and_sharing(user):
            flash("Access not allowed.", "danger")
            return render_template('login.html')

        redir = request.args.get('next', '/')
        return redirect(redir) 
Example #18
Source File: externalldap.py    From quay with Apache License 2.0 5 votes vote down vote up
def ping(self):
        try:
            with self._ldap.get_connection():
                pass
        except ldap.INVALID_CREDENTIALS:
            return (False, "LDAP Admin dn or password is invalid")
        except ldap.LDAPError as lde:
            logger.exception("Exception when trying to health check LDAP")
            return (False, str(lde))

        return (True, None) 
Example #19
Source File: externalldap.py    From quay with Apache License 2.0 5 votes vote down vote up
def at_least_one_user_exists(self):
        logger.debug("Checking if any users exist in LDAP")
        try:
            with self._ldap.get_connection():
                pass
        except ldap.INVALID_CREDENTIALS:
            return (None, "LDAP Admin dn or password is invalid")

        has_pagination = not self._force_no_pagination
        with self._ldap.get_connection() as conn:
            for user_search_dn in self._user_dns:
                search_flt = "(objectClass=*)"
                search_flt = self._add_user_filter(search_flt)

                lc = ldap.controls.libldap.SimplePagedResultsControl(
                    criticality=True, size=1, cookie=""
                )
                try:
                    if has_pagination:
                        msgid = conn.search_ext(
                            user_search_dn, ldap.SCOPE_SUBTREE, search_flt, serverctrls=[lc]
                        )
                        _, rdata, _, serverctrls = conn.result3(msgid)
                    else:
                        msgid = conn.search(user_search_dn, ldap.SCOPE_SUBTREE, search_flt)
                        _, rdata = conn.result(msgid)

                    for entry in rdata:  # Handles both lists and iterators.
                        return (True, None)

                except ldap.LDAPError as lde:
                    return (False, str(lde) or "Could not find DN %s" % user_search_dn)

        return (False, None) 
Example #20
Source File: ldap.py    From iris with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def ldap_auth(self, username, password):
        if self.cert_path:
            ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, self.cert_path)
        connection = ldap.initialize(self.ldap_url)
        connection.set_option(ldap.OPT_REFERRALS, 0)

        if not password:
            return False

        auth_user = username + self.user_suffix
        try:
            if self.bind_user:
                # use search filter to find DN of username
                connection.simple_bind_s(self.bind_user, self.bind_password)
                sfilter = self.search_filter % username
                result = connection.search_s(self.base_dn, ldap.SCOPE_SUBTREE, sfilter, ['dn'])
                if len(result) < 1:
                    return False
                auth_user = result[0][0]

            connection.simple_bind_s(auth_user, password)

        except ldap.INVALID_CREDENTIALS:
            return False
        except (ldap.SERVER_DOWN, ldap.INVALID_DN_SYNTAX) as err:
            logger.warning("%s", err)
            return None
        return True 
Example #21
Source File: externalldap.py    From quay with Apache License 2.0 5 votes vote down vote up
def _ldap_user_search(self, username_or_email, limit=20, suffix=""):
        if not username_or_email:
            return (None, "Empty username/email")

        # Verify the admin connection works first. We do this here to avoid wrapping
        # the entire block in the INVALID CREDENTIALS check.
        try:
            with self._ldap.get_connection():
                pass
        except ldap.INVALID_CREDENTIALS:
            return (None, "LDAP Admin dn or password is invalid")

        with self._ldap.get_connection() as conn:
            logger.debug("Incoming username or email param: %s", username_or_email.__repr__())

            for user_search_dn in self._user_dns:
                (pairs, err_msg) = self._ldap_user_search_with_rdn(
                    conn, username_or_email, user_search_dn, suffix=suffix
                )
                if pairs is not None and len(pairs) > 0:
                    break

            if err_msg is not None:
                return (None, err_msg)

            logger.debug("Found matching pairs: %s", pairs)
            results = [LDAPUsers._LDAPResult(*pair) for pair in take(limit, pairs)]

            # Filter out pairs without DNs. Some LDAP impls will return such pairs.
            with_dns = [result for result in results if result.dn]
            return (with_dns, None) 
Example #22
Source File: backend.py    From django-auth-ldap-ad with GNU General Public License v2.0 5 votes vote down vote up
def authenticate(self, username=None, password=None):
        if not hasattr(self, "ldap_settings"):
            self.ldap_settings = LDAPSettings()

        if isinstance(self.ldap_settings.SERVER_URI, six.string_types):
            servers_urls = [self.ldap_settings.SERVER_URI]
        else:
            servers_urls = self.ldap_settings.SERVER_URI

        # For all configured servers try to connect
        for server in servers_urls:
            # Use self.ldap_connection object if such is given for testing with
            # mockldap.
            if not hasattr(self, "ldap_connection"):
                try:
                    ldap_connection = self.ldap_open_connection(
                        server, username, password)
                except ldap.SERVER_DOWN:
                    continue
                except ldap.INVALID_CREDENTIALS:
                    return None
            else:  # end up here with mock
                ldap_connection = self.ldap_connection

            for key, value in self.ldap_settings.CONNECTION_OPTIONS.items():
                ldap_connection.set_option(key, value)

            # Do search
            try:
                ldap_user_info = self.ldap_search_user(
                    ldap_connection, username, password)
            except LDAPBackendException:
                return None

            return self.get_local_user(username, ldap_user_info)
        return None 
Example #23
Source File: externalldap.py    From quay with Apache License 2.0 5 votes vote down vote up
def verify_credentials(self, username_or_email, password):
        """
        Verify the credentials with LDAP.
        """
        # Make sure that even if the server supports anonymous binds, we don't allow it
        if not password:
            return (None, "Anonymous binding not allowed")

        (found_user, err_msg) = self._ldap_single_user_search(username_or_email)
        if found_user is None:
            return (None, err_msg)

        found_dn, found_response = found_user
        logger.debug("Found user for LDAP username %s; validating password", username_or_email)
        logger.debug("DN %s found: %s", found_dn, found_response)

        # First validate the password by binding as the user
        try:
            with LDAPConnection(self._ldap_uri, found_dn, password, self._allow_tls_fallback):
                pass
        except ldap.REFERRAL as re:
            referral_dn = self._get_ldap_referral_dn(re)
            if not referral_dn:
                return (None, "Invalid username")

            try:
                with LDAPConnection(
                    self._ldap_uri, referral_dn, password, self._allow_tls_fallback
                ):
                    pass
            except ldap.INVALID_CREDENTIALS:
                logger.debug("Invalid LDAP credentials")
                return (None, "Invalid password")

        except ldap.INVALID_CREDENTIALS:
            logger.debug("Invalid LDAP credentials")
            return (None, "Invalid password")

        return self._build_user_information(found_response) 
Example #24
Source File: externalldap.py    From quay with Apache License 2.0 5 votes vote down vote up
def iterate_group_members(self, group_lookup_args, page_size=None, disable_pagination=False):
        try:
            with self._ldap.get_connection():
                pass
        except ldap.INVALID_CREDENTIALS:
            return (None, "LDAP Admin dn or password is invalid")

        group_dn = group_lookup_args["group_dn"]
        page_size = page_size or _DEFAULT_PAGE_SIZE
        return (self._iterate_members(group_dn, page_size, disable_pagination), None) 
Example #25
Source File: fixture.py    From flask-ldap-login with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def simple_bind_s(username, password):
    if (username, password) not in MOCK_LDAP_USERS:
        raise ldap.INVALID_CREDENTIALS
    return True 
Example #26
Source File: ldap_example.py    From oncall with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def ldap_auth(self, username, password):
        if self.cert_path:
            ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, self.cert_path)

        connection = ldap.initialize(self.ldap_url)
        connection.set_option(ldap.OPT_REFERRALS, 0)

        if not password:
            return False

        auth_user = username + self.user_suffix
        try:
            if self.bind_user:
                # use search filter to find DN of username
                connection.simple_bind_s(self.bind_user, self.bind_password)
                sfilter = self.search_filter % username
                result = connection.search_s(self.base_dn, ldap.SCOPE_SUBTREE, sfilter, ['dn'])
                if len(result) < 1:
                    return False
                auth_user = result[0][0]

            connection.simple_bind_s(auth_user, password)

        except ldap.INVALID_CREDENTIALS:
            return False
        except (ldap.SERVER_DOWN, ldap.INVALID_DN_SYNTAX) as err:
            logger.warn("%s", err)
            return None
        return True 
Example #27
Source File: connections.py    From core with GNU General Public License v3.0 5 votes vote down vote up
def ldap_connect(
        uri="", rootdn="", dn="cn=admin", config=None, passwd="",
        conn_type=""):
    """
    Initialize a connection to arkOS LDAP.

    :param str uri: LDAP host URI
    :param str rootdn: Root DN
    :param str dn: User DN
    :param Config config: arkOS config to use for default values
    :param str passwd: Password to use to validate credentials
    :returns: LDAP connection object
    """
    if not all([uri, rootdn, dn]) and not config:
        raise errors.InvalidConfigError("No LDAP values passed")
    uri = uri or config.get("general", "ldap_uri")
    rootdn = rootdn or config.get("general", "ldap_rootdn")
    conn_type = conn_type or config.get("general", "ldap_conntype")

    if conn_type == "dynamic":
        c = ldap.ldapobject.ReconnectLDAPObject(
            uri, retry_max=3, retry_delay=5.0)
    else:
        c = ldap.initialize(uri)

    try:
        c.simple_bind_s("{0},{1}".format(dn, rootdn), passwd)
    except ldap.INVALID_CREDENTIALS:
        raise errors.ConnectionError("LDAP", "Invalid username/password")
    except Exception as e:
        raise errors.ConnectionError("LDAP") from e
    if dn != "cn=admin":
        data = c.search_s("cn=admins,ou=groups,{0}".format(rootdn),
                          ldap.SCOPE_SUBTREE, "(objectClass=*)",
                          ["member"])[0][1]["member"]
        if "{0},{1}".format(dn, rootdn) not in data:
            raise errors.ConnectionError("LDAP", "Not an administrator")
    return c 
Example #28
Source File: search.py    From ckanext-ldap with GNU General Public License v3.0 5 votes vote down vote up
def find_ldap_user(login):
    '''Find the LDAP user identified by 'login' in the configured ldap database

    :param login: The login to find in the LDAP database
    :returns: None if no user is found, a dictionary defining 'cn', 'username',
              'fullname' and 'email otherwise.

    '''
    cnx = ldap.initialize(toolkit.config[u'ckanext.ldap.uri'], bytes_mode=False,
                          trace_level=toolkit.config[u'ckanext.ldap.trace_level'])
    cnx.set_option(ldap.OPT_NETWORK_TIMEOUT, 10)
    if toolkit.config.get(u'ckanext.ldap.auth.dn'):
        try:
            if toolkit.config[u'ckanext.ldap.auth.method'] == u'SIMPLE':
                cnx.bind_s(toolkit.config[u'ckanext.ldap.auth.dn'],
                           toolkit.config[u'ckanext.ldap.auth.password'])
            elif toolkit.config[u'ckanext.ldap.auth.method'] == u'SASL':
                if toolkit.config[u'ckanext.ldap.auth.mechanism'] == u'DIGEST-MD5':
                    auth_tokens = ldap.sasl.digest_md5(toolkit.config[u'ckanext.ldap.auth.dn'],
                                                       toolkit.config[
                                                           u'ckanext.ldap.auth.password'])
                    cnx.sasl_interactive_bind_s(u'', auth_tokens)
                else:
                    log.error(u'SASL mechanism not supported: {0}'.format(
                        toolkit.config[u'ckanext.ldap.auth.mechanism']))
                    return None
            else:
                log.error(u'LDAP authentication method is not supported: {0}'.format(
                    toolkit.config[u'ckanext.ldap.auth.method']))
                return None
        except ldap.SERVER_DOWN:
            log.error(u'LDAP server is not reachable')
            return None
        except ldap.INVALID_CREDENTIALS:
            log.error(
                u'LDAP server credentials (ckanext.ldap.auth.dn and ckanext.ldap.auth.password) '
                u'invalid')
            return None
        except ldap.LDAPError, e:
            log.error(u'Fatal LDAP Error: {0}'.format(e))
            return None 
Example #29
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 #30
Source File: ldap.py    From kqueen with MIT License 5 votes vote down vote up
def _bind(self, dn, password):

        try:
            self.connection = ldap.initialize(self.uri)
            bind = self.connection.simple_bind_s(dn, password)

            if bind:
                msg = 'User {} successfully bind connection LDAP'.format(dn)
                logger.debug(msg)
                return True
        except ldap.INVALID_CREDENTIALS:

            msg = "Invalid LDAP credentials for {}".format(dn)
            logger.exception(msg)
            return False

        except ldap.INVALID_DN_SYNTAX:

            msg = 'Invalid DN syntax in configuration: {}'.format(dn)
            logger.exception(msg)
            return False

        except ldap.LDAPError:

            msg = 'Failed to bind LDAP server'
            logger.exception(msg)
            return False

        except Exception:

            msg = 'Unknown error occurred during LDAP server bind'
            logger.exception(msg)
            return False

        finally:
            self.connection.unbind()

        msg = 'All LDAP authentication methods failed'
        logger.error(msg)
        return False