Python ldap.set_option() Examples
The following are 21
code examples of ldap.set_option().
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_attr.py From isam-ansible-roles with Apache License 2.0 | 7 votes |
def _connect_to_ldap(self): ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) connection = ldap.initialize(self.server_uri) if self.start_tls: try: connection.start_tls_s() except ldap.LDAPError: e = get_exception() self.module.fail_json(msg="Cannot start TLS.", details=str(e)) try: if self.bind_dn is not None: connection.simple_bind_s(self.bind_dn, self.bind_pw) else: connection.sasl_interactive_bind_s('', ldap.sasl.external()) except ldap.LDAPError: e = get_exception() self.module.fail_json( msg="Cannot bind to the server.", details=str(e)) return connection
Example #2
Source File: ldap_backend.py From st2-auth-backend-ldap with Apache License 2.0 | 6 votes |
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 #3
Source File: freeipaserver.py From checkipaconsistency with GNU General Public License v3.0 | 6 votes |
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: __init__.py From flask-simpleldap with MIT License | 6 votes |
def initialize(self): """Initialize a connection to the LDAP server. :return: LDAP connection object. """ try: conn = ldap.initialize('{0}://{1}:{2}'.format( current_app.config['LDAP_SCHEMA'], current_app.config['LDAP_HOST'], current_app.config['LDAP_PORT'])) conn.set_option(ldap.OPT_NETWORK_TIMEOUT, current_app.config['LDAP_TIMEOUT']) conn = self._set_custom_options(conn) conn.protocol_version = ldap.VERSION3 if current_app.config['LDAP_USE_TLS']: conn.start_tls_s() return conn except ldap.LDAPError as e: raise LDAPException(self.error(e.args))
Example #5
Source File: ldapconn.py From zabbix-ldap-sync with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 #6
Source File: config.py From django-auth-ldap with BSD 2-Clause "Simplified" License | 5 votes |
def get_ldap(cls, global_options=None): """ Returns the configured ldap module. """ # Apply global LDAP options once if not cls._ldap_configured and global_options is not None: for opt, value in global_options.items(): ldap.set_option(opt, value) cls._ldap_configured = True return ldap
Example #7
Source File: ldapconn.py From zabbix-ldap-sync with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__(self, config): self.uri = config.ldap_uri self.base = config.ldap_base self.ldap_user = config.ldap_user self.ldap_pass = config.ldap_passwd self.ldap_type = config.ldap_type self.group_member_attribute = config.ldap_group_member_attribute self.group_filter = config.ldap_group_filter self.uid_attribute = config.ldap_uid_attribute self.recursive = config.ldap_recursive if self.recursive: self.memberof_filter = config.ldap_memberof_filter self.skipdisabled = config.ldap_skipdisabled self.lowercase = config.ldap_lowercase self.user_filter = config.ldap_user_filter self.active_directory = config.ldap_active_directory self.verbose = config.verbose # Use logger to log information self.logger = logging.getLogger() if self.verbose: self.logger.setLevel(logging.DEBUG) else: self.logger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') # Log to stdout ch = logging.StreamHandler() if self.verbose: ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) self.logger.addHandler(ch) # Use logger to log information # Log from pyldap log = logging.getLogger('ldap') log.addHandler(ch) if self.verbose: log.setLevel(logging.DEBUG) ldap.set_option(ldap.OPT_DEBUG_LEVEL, 4095)
Example #8
Source File: __init__.py From flask-simpleldap with MIT License | 5 votes |
def _set_custom_options(conn): options = current_app.config['LDAP_CUSTOM_OPTIONS'] if options: for k, v in options.items(): conn.set_option(k, v) return conn
Example #9
Source File: ldap_auth.py From termite-visualizations with BSD 3-Clause "New" or "Revised" License | 5 votes |
def init_ldap(ldap_server=server, ldap_port=port, ldap_basedn=base_dn, ldap_mode=mode, secure=secure, cert_path=cert_path, cert_file=cert_file): """ Inicialize ldap connection """ logger.info('[%s] Initialize ldap connection' % str(ldap_server)) if secure: if not ldap_port: ldap_port = 636 con = ldap.initialize( "ldaps://" + ldap_server + ":" + str(ldap_port)) if cert_path: con.set_option(ldap.OPT_X_TLS_CACERTDIR, cert_path) if cert_file: con.set_option(ldap.OPT_X_TLS_CACERTFILE, cert_file) else: if not ldap_port: ldap_port = 389 con = ldap.initialize( "ldap://" + ldap_server + ":" + str(ldap_port)) return con
Example #10
Source File: login.py From ckanext-ldap with GNU General Public License v3.0 | 5 votes |
def initialise(): ldap.set_option(ldap.OPT_DEBUG_LEVEL, toolkit.config[u'ckanext.ldap.debug_level'])
Example #11
Source File: user.py From PowerDNS-Admin with MIT License | 5 votes |
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 #12
Source File: ldap_example.py From oncall with BSD 2-Clause "Simplified" License | 5 votes |
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 #13
Source File: ldap.py From iris with BSD 2-Clause "Simplified" License | 5 votes |
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 #14
Source File: __init__.py From zentral with Apache License 2.0 | 5 votes |
def get_ldap_connection(host): conn = ldap.initialize("ldap://{}".format(host)) conn.set_option(ldap.OPT_PROTOCOL_VERSION, ldap.VERSION3) conn.start_tls_s() return conn
Example #15
Source File: account_ldap.py From InfraBox with Apache License 2.0 | 5 votes |
def ldap_conn(ldap_server): connect = ldap.initialize(ldap_server) connect.set_option(ldap.OPT_REFERRALS, 0) return connect
Example #16
Source File: ldap_factory.py From MCVirt with GNU General Public License v2.0 | 5 votes |
def get_connection(self, bind_dn=None, password=None): """Return an LDAP object.""" if not LdapFactory.is_enabled(): raise LdapNotEnabledException('Ldap has not been configured on this node') ca_cert_exists = os.path.exists(self.ldap_ca_cert_path) ldap_config = MCVirtConfig().get_config()['ldap'] ldap.set_option( ldap.OPT_X_TLS_CACERTFILE, self.ldap_ca_cert_path if ca_cert_exists else '' ) if bind_dn is None and password is None: bind_dn = ldap_config['bind_dn'] password = ldap_config['bind_pass'] try: ldap_connection = ldap.initialize(uri=ldap_config['server_uri']) try: ldap_connection.bind_s(bind_dn, password) except AttributeError: # This is required for the mockldap server as part of the unit tests ldap_connection.simple_bind_s(bind_dn, password) except Exception: raise LdapConnectionFailedException( 'Connection attempts to the LDAP server failed.' ) return ldap_connection
Example #17
Source File: user_management.py From fame with GNU General Public License v3.0 | 5 votes |
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 #18
Source File: ldap_import.py From oncall with BSD 2-Clause "Simplified" License | 4 votes |
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
Example #19
Source File: backendLdap.py From ldapcherry with MIT License | 4 votes |
def _connect(self): """Initialize an ldap client""" ldap_client = ldap.initialize(self.uri) ldap.set_option(ldap.OPT_REFERRALS, 0) ldap.set_option(ldap.OPT_TIMEOUT, self.timeout) if self.starttls == 'on': ldap.set_option(ldap.OPT_X_TLS_DEMAND, True) else: ldap.set_option(ldap.OPT_X_TLS_DEMAND, False) # set the CA file if declared and if necessary if self.ca and self.checkcert == 'on': # check if the CA file actually exists if os.path.isfile(self.ca): ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, self.ca) else: raise CaFileDontExist(self.ca) if self.checkcert == 'off': # this is dark magic # remove any of these two lines and it doesn't work ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) ldap_client.set_option( ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER ) else: # this is even darker magic ldap_client.set_option( ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_DEMAND ) # it doesn't make sense to set it to never # (== don't check certifate) # but it only works with this option... # ... and it checks the certificat # (I've lost my sanity over this) ldap.set_option( ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER ) if self.starttls == 'on': try: ldap_client.start_tls_s() except Exception as e: self._exception_handler(e) return ldap_client
Example #20
Source File: __init__.py From flask-simpleldap with MIT License | 4 votes |
def init_app(app): """Initialize the `app` for use with this :class:`~LDAP`. This is called automatically if `app` is passed to :meth:`~LDAP.__init__`. :param flask.Flask app: the application to configure for use with this :class:`~LDAP` """ app.config.setdefault('LDAP_HOST', 'localhost') app.config.setdefault('LDAP_PORT', 389) app.config.setdefault('LDAP_SCHEMA', 'ldap') app.config.setdefault('LDAP_USERNAME', None) app.config.setdefault('LDAP_PASSWORD', None) app.config.setdefault('LDAP_TIMEOUT', 10) app.config.setdefault('LDAP_USE_SSL', False) app.config.setdefault('LDAP_USE_TLS', False) app.config.setdefault('LDAP_REQUIRE_CERT', False) app.config.setdefault('LDAP_CERT_PATH', '/path/to/cert') app.config.setdefault('LDAP_BASE_DN', None) app.config.setdefault('LDAP_OBJECTS_DN', 'distinguishedName') app.config.setdefault('LDAP_USER_FIELDS', []) app.config.setdefault('LDAP_USER_OBJECT_FILTER', '(&(objectclass=Person)(userPrincipalName=%s))') app.config.setdefault('LDAP_USER_GROUPS_FIELD', 'memberOf') app.config.setdefault('LDAP_GROUP_FIELDS', []) app.config.setdefault('LDAP_GROUP_OBJECT_FILTER', '(&(objectclass=Group)(userPrincipalName=%s))') app.config.setdefault('LDAP_GROUP_MEMBERS_FIELD', 'member') app.config.setdefault('LDAP_LOGIN_VIEW', 'login') app.config.setdefault('LDAP_REALM_NAME', 'LDAP authentication') app.config.setdefault('LDAP_OPENLDAP', False) app.config.setdefault('LDAP_GROUP_MEMBER_FILTER', '*') app.config.setdefault('LDAP_GROUP_MEMBER_FILTER_FIELD', '*') app.config.setdefault('LDAP_CUSTOM_OPTIONS', None) if app.config['LDAP_USE_SSL'] or app.config['LDAP_USE_TLS']: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) if app.config['LDAP_REQUIRE_CERT']: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_DEMAND) ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, current_app.config['LDAP_CERT_PATH']) for option in ['USERNAME', 'PASSWORD', 'BASE_DN']: if app.config['LDAP_{0}'.format(option)] is None: raise LDAPException('LDAP_{0} cannot be None!'.format(option))
Example #21
Source File: __init__.py From ssh-ldap-pubkey with MIT License | 4 votes |
def connect(self): """Connect to the LDAP server. This method must be called before any other methods of this object. Raises: ConfigError: If Base DN or LDAP URI is missing in the config. LDAPConnectionError: If can't connect to the LDAP server. ldap.LDAPError: """ conf = self.conf if not conf.uris or not conf.base: raise ConfigError('Base DN and LDAP URI(s) must be provided.', 1) if conf.tls_require_cert: if conf.tls_require_cert not in [ldap.OPT_X_TLS_DEMAND, ldap.OPT_X_TLS_HARD]: print(BAD_REQCERT_WARNING, file=sys.stderr) # this is a global option! ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, conf.tls_require_cert) if conf.cacert_dir: # this is a global option! ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, conf.cacert_dir) if not conf.referrals: # this is a global option! ldap.set_option(ldap.OPT_REFERRALS, 0) # NOTE: The uri argument is passed directly to the underlying openldap # library that allows multiple URIs separated by a space for failover. self._conn = conn = ldap.initialize(' '.join(conf.uris)) try: conn.protocol_version = conf.ldap_version conn.network_timeout = conf.bind_timeout conn.timeout = conf.search_timeout if conf.sasl == 'GSSAPI': self._bind_sasl_gssapi() return if conf.ssl == 'start_tls' and conf.ldap_version >= 3: conn.start_tls_s() if conf.bind_dn and conf.bind_pass: self._bind(conf.bind_dn, conf.bind_pass) except ldap.SERVER_DOWN: raise LDAPConnectionError('Can\'t contact LDAP server.', 3)