Python ldap.OPT_REFERRALS Examples

The following are 18 code examples of ldap.OPT_REFERRALS(). 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: ldap_backend.py    From st2-auth-backend-ldap with Apache License 2.0 6 votes vote down vote up
def _ldap_connect(self):
        """
        Prepare ldap object for binding phase.
        """
        try:
            connection = ldap.initialize(self._ldap_uri)
            connection.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
            connection.set_option(ldap.OPT_REFERRALS,
                                  int(self._chase_referrals))

            if self._ldap_uri.startswith('ldaps://'):
                # Require server certificate but ignore it's validity. (allow self-signed)
                ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

            if self._use_tls:
                # Require TLS connection.
                ldap.set_option(ldap.OPT_X_TLS, ldap.OPT_X_TLS_DEMAND)
                # Require server certificate but ignore it's validity. (allow self-signed)
                ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
                connection.start_tls_s()
                LOG.debug('Connection now using TLS')
            return connection
        except ldap.LDAPError as e:
            LOG.debug('(_ldap_connect) LDAP Error: %s : Type %s' % (str(e), type(e)))
            return False 
Example #2
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 #3
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 #4
Source File: __init__.py    From flask-ldap-login with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def init_app(self, app):
        '''
        Configures an application. This registers an `after_request` call, and
        attaches this `LoginManager` to it as `app.ldap_login_manager`.
        '''

        self._config = app.config.get('LDAP', {})
        app.ldap_login_manager = self

        self.config.setdefault('BIND_DN', '')
        self.config.setdefault('BIND_AUTH', '')
        self.config.setdefault('URI', 'ldap://127.0.0.1')
        self.config.setdefault('OPTIONS', {})
        # Referrals are disabled by default
        self.config['OPTIONS'].setdefault(ldap.OPT_REFERRALS, ldap.OPT_OFF)

        if self.config.get('USER_SEARCH') and not isinstance(self.config['USER_SEARCH'], list):
            self.config['USER_SEARCH'] = [self.config['USER_SEARCH']] 
Example #5
Source File: externalldap.py    From quay with Apache License 2.0 6 votes vote down vote up
def __enter__(self):
        trace_level = 2 if os.environ.get("USERS_DEBUG") == "1" else 0

        self._conn = ldap.initialize(self._ldap_uri, trace_level=trace_level)
        self._conn.set_option(ldap.OPT_REFERRALS, 1)
        self._conn.set_option(
            ldap.OPT_NETWORK_TIMEOUT, self._network_timeout or _DEFAULT_NETWORK_TIMEOUT
        )
        self._conn.set_option(ldap.OPT_TIMEOUT, self._timeout or _DEFAULT_TIMEOUT)

        if self._allow_tls_fallback:
            logger.debug("TLS Fallback enabled in LDAP")
            self._conn.set_option(ldap.OPT_X_TLS_TRY, 1)

        self._conn.simple_bind_s(self._user_dn, self._user_pw)
        return self._conn 
Example #6
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 #7
Source File: ldapconn.py    From zabbix-ldap-sync with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def connect(self):
        """
        Establish a connection to the LDAP server.

        Raises:
            SystemExit

        """
        self.conn = ldap.initialize(self.uri)
        self.conn.set_option(ldap.OPT_REFERRALS, ldap.OPT_OFF)

        try:
            self.conn.simple_bind_s(self.ldap_user, self.ldap_pass)
        except ldap.SERVER_DOWN as e:
            raise SystemExit('Cannot connect to LDAP server: %s' % e) 
Example #8
Source File: user.py    From PowerDNS-Admin with MIT License 5 votes vote down vote up
def ldap_init_conn(self):
        ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
        conn = ldap.initialize(Setting().get('ldap_uri'))
        conn.set_option(ldap.OPT_REFERRALS, ldap.OPT_OFF)
        conn.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
        conn.set_option(ldap.OPT_X_TLS, ldap.OPT_X_TLS_DEMAND)
        conn.set_option(ldap.OPT_X_TLS_DEMAND, True)
        conn.set_option(ldap.OPT_DEBUG_LEVEL, 255)
        conn.protocol_version = ldap.VERSION3
        return conn 
Example #9
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 #10
Source File: user.py    From certidude with MIT License 5 votes vote down vote up
def __enter__(self):
        import ldap
        import ldap.sasl

        # TODO: Implement simple bind
        if not os.path.exists(config.LDAP_GSSAPI_CRED_CACHE):
            raise ValueError("Ticket cache at %s not initialized, unable to "
                "authenticate with computer account against LDAP server!" % config.LDAP_GSSAPI_CRED_CACHE)
        os.environ["KRB5CCNAME"] = config.LDAP_GSSAPI_CRED_CACHE
        self.conn = ldap.initialize(config.LDAP_ACCOUNTS_URI, bytes_mode=False)
        self.conn.set_option(ldap.OPT_REFERRALS, 0)
        click.echo("Connecing to %s using Kerberos ticket cache from %s" %
            (config.LDAP_ACCOUNTS_URI, config.LDAP_GSSAPI_CRED_CACHE))
        self.conn.sasl_interactive_bind_s('', ldap.sasl.gssapi())
        return self.conn 
Example #11
Source File: windapsearch.py    From windapsearch with GNU General Public License v3.0 5 votes vote down vote up
def initializeConnection(self):
        if not self.dc_ip:
            self.get_set_DC_IP(self.domain)

        con = ldap.initialize('ldap://{}'.format(self.dc_ip))
        con.set_option(ldap.OPT_REFERRALS, 0)
        return con 
Example #12
Source File: windapsearch_py2.py    From windapsearch with GNU General Public License v3.0 5 votes vote down vote up
def initializeConnection(self):
		if not self.dc_ip:
			self.dc_ip = self.getDC_IP(self.domain)

		con = ldap.initialize('ldap://{}'.format(self.dc_ip))
		con.set_option(ldap.OPT_REFERRALS, 0)
		return con 
Example #13
Source File: ldap.py    From ldap2pg with PostgreSQL License 5 votes vote down vote up
def connect(**kw):
    # Sources order, see ldap.conf(3)
    #   variable     $LDAPNOINIT, and if that is not set:
    #   system file  /etc/ldap/ldap.conf,
    #   user files   $HOME/ldaprc,  $HOME/.ldaprc,  ./ldaprc,
    #   system file  $LDAPCONF,
    #   user files   $HOME/$LDAPRC, $HOME/.$LDAPRC, ./$LDAPRC,
    #   user files   <ldap2pg.yml>...
    #   variables    $LDAP<uppercase option name>.
    #
    # Extra variable LDAPPASSWORD is supported.

    options = gather_options(**kw)
    logger.debug("Connecting to LDAP server %s.", options['URI'])
    conn = ldap.initialize(options['URI'])
    if PY2:  # pragma: nocover_py3
        conn = UnicodeModeLDAPObject(conn)

    conn = LDAPLogger(conn)
    # Don't follow referrals by default. This is the behaviour of ldapsearch
    # and friends. Following referrals leads to strange errors with Active
    # directory. REFERRALS can still be activated through ldaprc, env var and
    # even YAML. See https://github.com/dalibo/ldap2pg/issues/228 .
    conn.set_option(ldap.OPT_REFERRALS, options.get('REFERRALS', False))

    if not options.get('SASL_MECH'):
        logger.debug("Trying simple bind.")
        conn.simple_bind_s(options['BINDDN'], options['PASSWORD'])
    else:
        logger.debug("Trying SASL %s auth.", options['SASL_MECH'])
        mech = options['SASL_MECH']
        if 'DIGEST-MD5' == mech:
            auth = sasl.sasl({
                sasl.CB_AUTHNAME: options['USER'],
                sasl.CB_PASS: options['PASSWORD'],
            }, mech)
        elif 'GSSAPI' == mech:
            auth = sasl.gssapi(options.get('SASL_AUTHZID'))
        else:
            raise UserError("Unmanaged SASL mech %s.", mech)

        conn.sasl_interactive_bind_s("", auth)

    return conn 
Example #14
Source File: account_ldap.py    From InfraBox with Apache License 2.0 5 votes vote down vote up
def ldap_conn(ldap_server):
    connect = ldap.initialize(ldap_server)
    connect.set_option(ldap.OPT_REFERRALS, 0)

    return connect 
Example #15
Source File: user_management.py    From fame with GNU General Public License v3.0 5 votes vote down vote up
def _ldap_get_con():
    if not _check_ldap_settings_present():
        return None

    con = ldap.initialize(fame_config.ldap_uri)
    con.protocol_version = ldap.VERSION3
    con.set_option(ldap.OPT_REFERRALS, 0)
    return con 
Example #16
Source File: ldap_auth.py    From kansha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def connect(self):
        conn = super(ADLDAPAuth, self).connect()
        conn.set_option(ldap.OPT_REFERRALS, 0)
        conn.protocol_version = 3
        return conn 
Example #17
Source File: tests.py    From django-auth-ldap with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_options(self):
        self._init_settings(
            USER_DN_TEMPLATE="uid=%(user)s,ou=people,o=test",
            CONNECTION_OPTIONS={ldap.OPT_REFERRALS: 0},
        )
        user = authenticate(username="alice", password="password")

        self.assertEqual(user.ldap_user.connection.get_option(ldap.OPT_REFERRALS), 0) 
Example #18
Source File: ldap_import.py    From oncall with BSD 2-Clause "Simplified" License 4 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)
        attrs = ['dn'] + list(self.attrs.values())
        ldap_contacts = {}

        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, attrs)
                if len(result) < 1:
                    return False
                auth_user = result[0][0]
                ldap_attrs = result[0][1]
                for key, val in self.attrs.items():
                    if ldap_attrs.get(val):
                        if type(ldap_attrs.get(val)) == list:
                            ldap_contacts[key] = ldap_attrs.get(val)[0]
                        else:
                            ldap_contacts[key] = ldap_attrs.get(val)
                    else:
                        ldap_contacts[key] = val

            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

        if self.import_user:
            connection = db.connect()
            cursor = connection.cursor(db.DictCursor)
            if user_exists(username, cursor):
                logger.info("user %s already exists, updating from ldap", username)
                update_user(username, ldap_contacts, cursor)
            else:
                logger.info("user %s does not exists. importing.", username)
                import_user(username, ldap_contacts, cursor)
            connection.commit()
            cursor.close()
            connection.close()

        return True