Python ldap3.Server() Examples
The following are 30
code examples of ldap3.Server().
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
ldap3
, or try the search function
.
Example #1
Source File: Active_Directory_Query.py From content with MIT License | 6 votes |
def initialize_server(host, port, secure_connection, unsecure): """ uses the instance configuration to initialize the LDAP server :param host: host or ip :type host: string :param port: port or None :type port: number :param secure_connection: SSL or None :type secure_connection: string :param unsecure: trust any cert :type unsecure: boolean :return: ldap3 Server :rtype: Server """ if secure_connection == "SSL": # intialize server with ssl # port is configured by default as 389 or as 636 for LDAPS if not specified in configuration demisto.debug("initializing sever with ssl (unsecure: {}). port: {}". format(unsecure, port or 'default(636)')) if not unsecure: demisto.debug("will require server certificate.") tls = Tls(validate=ssl.CERT_REQUIRED, ca_certs_file=os.environ.get('SSL_CERT_FILE')) if port: return Server(host, port=port, use_ssl=True, tls=tls) return Server(host, use_ssl=True, tls=tls) if port: return Server(host, port=port, use_ssl=True) return Server(host, use_ssl=True) demisto.debug("initializing server without secure connection. port: {}". format(port or 'default(389)')) if port: return Server(host, port=port) return Server(host)
Example #2
Source File: auth_ldap3.py From bbotte.github.io with Apache License 2.0 | 6 votes |
def ldap_authenticate(request,username,password,groups_allowed=True): #change these values to what is appropriate for your environment id_name="uid" ldap_host="192.168.0.2" ldap_port="389" bind_dn="cn=Manager,dc=bbotte,dc=com" bind_pass="123456" user_base="ou=People,dc=bbotte,dc=com" #bind with service account s = Server(ldap_host, port=int(ldap_port), get_info=ALL) c = Connection( s, authentication=SIMPLE, user=bind_dn, password=bind_pass, check_names=True, lazy=False, client_strategy=SYNC, raise_exceptions=False) c.open() c.bind() if c.bound: #once bound, check username provided and get cn, memberOf list and mail # get cn_name c.search(user_base,'(%s=%s)'%(id_name,username),attributes=['cn','mail']) c.unbind try: cn_name=c.entries[0].cn except: print("user cn cannot be found") auth_logger.error("user cn cannot be found") session['username']=username return True else: auth_logger.debug('ldap bind failed') c.unbind() return False
Example #3
Source File: ldaprelayclient.py From Exchange2domain with MIT License | 6 votes |
def sendAuth(self, authenticateMessageBlob, serverChallenge=None): if unpack('B', str(authenticateMessageBlob)[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP: respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob) token = respToken2['ResponseToken'] else: token = authenticateMessageBlob with self.session.connection_lock: self.authenticateMessageBlob = token request = bind.bind_operation(self.session.version, 'SICILY_RESPONSE_NTLM', self, None) response = self.session.post_send_single_response(self.session.send('bindRequest', request, None)) result = response[0] self.session.sasl_in_progress = False if result['result'] == RESULT_SUCCESS: self.session.bound = True self.session.refresh_server_info() return None, STATUS_SUCCESS else: if result['result'] == RESULT_STRONGER_AUTH_REQUIRED and self.PLUGIN_NAME != 'LDAPS': raise LDAPRelayClientException('Server rejected authentication because LDAP signing is enabled. Try connecting with TLS enabled (specify target as ldaps://hostname )') return None, STATUS_ACCESS_DENIED #This is a fake function for ldap3 which wants an NTLM client with specific methods
Example #4
Source File: __init__.py From flask-ldap3-login with MIT License | 6 votes |
def add_server(self, hostname, port, use_ssl, tls_ctx=None, app=None): """ Add an additional server to the server pool and return the freshly created server. Args: hostname (str): Hostname of the server port (int): Port of the server use_ssl (bool): True if SSL is to be used when connecting. tls_ctx (ldap3.Tls): An optional TLS context object to use when connecting. app (flask.Flask): The app on which to add the server. If not given, ``flask.current_app`` is used. Returns: ldap3.Server: The freshly created server object. """ if app is None: app = current_app._get_current_object() if not use_ssl and tls_ctx: raise ValueError("Cannot specify a TLS context and not use SSL!") server = ldap3.Server(hostname, port=port, use_ssl=use_ssl, tls=tls_ctx) app.ldap3_login_manager_server_pool.add(server) return server
Example #5
Source File: _servers.py From treadmill with Apache License 2.0 | 6 votes |
def create_ldap_connection(domain_controller): """Create ldap connection object. """ # Disable W0212: Access to a protected member _is_ipv6 of a # client class # # This is needed because twisted monkey patches socket._is_ipv6 # and ldap3 code is wrong. # pylint: disable=W0212 ldap3.Server._is_ipv6 = lambda x, y: False server = ldap3.Server(domain_controller, mode=ldap3.IP_V4_ONLY) return ldap3.Connection( server, authentication=ldap3.SASL, sasl_mechanism='GSSAPI', sasl_credentials=(True,), client_strategy=ldap3.RESTARTABLE, auto_bind=True, auto_range=True, return_empty_attributes=False )
Example #6
Source File: user.py From passhport with GNU Affero General Public License v3.0 | 6 votes |
def try_ldap_login(login, password): """ Connect to a LDAP directory to verify user login/passwords""" result = "Wrong login/password" s = Server(config.LDAPURI, port=config.LDAPPORT, use_ssl=False, get_info=ALL) # 1. connection with service account to find the user uid uid = useruid(s, login) if uid: # 2. Try to bind the user to the LDAP c = Connection(s, user = uid , password = password, auto_bind = True) c.open() c.bind() result = c.result["description"] # "success" if bind is ok c.unbind() return result
Example #7
Source File: LDAPIdResolver.py From privacyidea with GNU Affero General Public License v3.0 | 6 votes |
def _bind(self): if not self.i_am_bound: if not self.serverpool: self.serverpool = self.get_serverpool_instance(self.get_info) self.l = self.create_connection(authtype=self.authtype, server=self.serverpool, user=self.binddn, password=self.bindpw, receive_timeout=self.timeout, auto_referrals=not self.noreferrals, start_tls=self.start_tls) #log.error("LDAP Server Pool States: %s" % server_pool.pool_states) if not self.l.bind(): raise Exception("Wrong credentials") self.i_am_bound = True
Example #8
Source File: search.py From coldfront with GNU General Public License v3.0 | 6 votes |
def __init__(self, user_search_string, search_by): super().__init__(user_search_string, search_by) self.FREEIPA_SERVER = import_from_settings('FREEIPA_SERVER') self.FREEIPA_USER_SEARCH_BASE = import_from_settings('FREEIPA_USER_SEARCH_BASE', 'cn=users,cn=accounts') self.FREEIPA_KTNAME = import_from_settings('FREEIPA_KTNAME', '') self.server = Server('ldap://{}'.format(self.FREEIPA_SERVER), use_ssl=True, connect_timeout=1) if len(self.FREEIPA_KTNAME) > 0: logger.info('Kerberos bind enabled: %s', self.FREEIPA_KTNAME) # kerberos SASL/GSSAPI bind os.environ["KRB5_CLIENT_KTNAME"] = self.FREEIPA_KTNAME self.conn = Connection(self.server, authentication=SASL, sasl_mechanism=KERBEROS, auto_bind=True) else: # anonomous bind self.conn = Connection(self.server, auto_bind=True) if not self.conn.bind(): raise ImproperlyConfigured('Failed to bind to LDAP server: {}'.format(self.conn.result)) else: logger.info('LDAP bind successful: %s', self.conn.extend.standard.who_am_i())
Example #9
Source File: 20_8_read_ldap_server.py From Python-Network-Programming with MIT License | 5 votes |
def main(): server = Server('ipa.demo1.freeipa.org', get_info=ALL) conn = Connection(server, 'uid=admin,cn=users,cn=accounts,dc=demo1,dc=freeipa,dc=org', 'Secret123', auto_bind=True) person = ObjectDef('person', conn) r = Reader(conn, person, 'ou=ldap3-tutorial,dc=demo1,dc=freeipa,dc=org') print(r) print('************') person+='uid' print(r)
Example #10
Source File: 11_8_read_ldap_server.py From Python-Network-Programming-Cookbook-Second-Edition with MIT License | 5 votes |
def main(): server = Server('ipa.demo1.freeipa.org', get_info=ALL) conn = Connection(server, 'uid=admin,cn=users,cn=accounts,dc=demo1,dc=freeipa,dc=org', 'Secret123', auto_bind=True) person = ObjectDef('person', conn) r = Reader(conn, person, 'ou=ldap3-tutorial,dc=demo1,dc=freeipa,dc=org') print(r) print('************') person+='uid' print(r)
Example #11
Source File: 20_6_connect_ldap_server.py From Python-Network-Programming with MIT License | 5 votes |
def main(address): # Create the Server object with the given address. # Get ALL information. server = Server(address, get_info=ALL) #Create a connection object, and bind with auto bind set to true. conn = Connection(server, auto_bind=True) # Print the LDAP Server Information. print('******************Server Info**************') print(server.info) # Print the LDAP Server Detailed Schema. print('******************Server Schema**************') print(server.schema)
Example #12
Source File: client_ldap3.py From code with MIT License | 5 votes |
def __init__(self, url, require_tls=True): Core.debug("creating ldap3 connection to %r", url) serv = ldap3.Server(url, tls=ldap3.Tls(validate=ssl.CERT_REQUIRED), get_info=ldap3.DSA) self.conn = ldap3.Connection(serv, #authentication=ldap3.SASL, #sasl_mechanism=ldap3.GSSAPI, raise_exceptions=True) self.conn.open() if require_tls and not url.startswith(("ldaps://", "ldapi://")): self.conn.start_tls() self._controls = {c[0] for c in self.conn.server.info.supported_controls} self._features = {c[0] for c in self.conn.server.info.supported_features}
Example #13
Source File: restore.py From CVE-2019-1040 with MIT License | 5 votes |
def establish_connection(self, user): domain = self.config['domain'] # First check if the server was specified explicitly if self.config['server']: server = self.config['server'] else: server = self.config['domain'] # if self.args.server: # server = self.args.server # # If not, check if the server was specified in the restore data # elif self.config['server']: # server = self.config['server'] # # Else, assume DNS is set up properly and we can connect to the domain # else: # server = self.config['domain'] #password = getpass.getpass(self.ntlm.encode('utf-8')) password = self.ntlm self.passdata[user] = password #Todo: get password from command line args # try: # password = self.passdata[user] # except KeyError: # prompt = 'Please supply the password or LM:NTLM hashes for the account %s: ' % user # password = getpass.getpass(prompt.encode('utf-8')) # # Store for further reference # self.passdata[user] = password if domain is None: domain = get_domain(user) if '@' in user or '.' in user: binduser = get_sam_name(user) else: binduser = user ldapserver = ldap3.Server(server, get_info=ldap3.DSA) connection = ldap3.Connection(ldapserver, user='%s\\%s' % (domain, binduser), password=password, authentication=ldap3.NTLM) if not connection.bind(): raise RestoreException('Failed to connect to the LDAP server as %s\\%s: %s' % (domain, binduser, str(connection.result))) return connection, user
Example #14
Source File: 20_7_query_ldap_server.py From Python-Network-Programming with MIT License | 5 votes |
def main(address, dn, password): # Create the Server object with the given address. server = Server(address, get_info=ALL) #Create a connection object, and bind with the given DN and password. try: conn = Connection(server, dn, password, auto_bind=True) print('LDAP Bind Successful.') print(conn) except core.exceptions.LDAPBindError as e: # If the LDAP bind failed for reasons such as authentication failure. print('LDAP Bind Failed: ', e)
Example #15
Source File: 20_7_query_ldap_server_b.py From Python-Network-Programming with MIT License | 5 votes |
def main(address, dn, password): # Create the Server object with the given address. server = Server(address, get_info=ALL) #Create a connection object, and bind with the given DN and password. try: conn = Connection(server, dn, password, auto_bind=True) print('LDAP Bind Successful.') # Perform a search for a pre-defined criteria. # Mention the search filter / filter type and attributes. conn.search('dc=example,dc=com', '(&(uid=euler))' , attributes=['sn']) # Print the resulting entries. print(conn.entries[0]) except core.exceptions.LDAPBindError as e: # If the LDAP bind failed for reasons such as authentication failure. print('LDAP Bind Failed: ', e)
Example #16
Source File: helper.py From resilient-community-apps with MIT License | 5 votes |
def get_ldap_connection(self): try: server = Server(self.LDAP_SERVER, port=self.LDAP_PORT, get_info=ALL, use_ssl=self.LDAP_USE_SSL, connect_timeout=self.LDAP_CONNECT_TIMEOUT) if self.LDAP_AUTH_TYPE == "NTLM": connection = Connection( server=server, user=self.LDAP_USER_NTLM, password=self.LDAP_PASSWORD, authentication=NTLM, return_empty_attributes=True, raise_exceptions=True) else: connection = Connection( server=server, user=self.LDAP_USER_DN, password=self.LDAP_PASSWORD, authentication=self.LDAP_AUTH_TYPE, return_empty_attributes=True, raise_exceptions=True) return connection except Exception as err: raise ValueError("Cannot connect to LDAP Server. Ensure credentials are correct\n Error: {0}".format(err))
Example #17
Source File: helper.py From resilient-community-apps with MIT License | 5 votes |
def __init__(self, app_configs): SUPPORTED_LDAP_AUTH_TYPE_TYPES = ["ANONYMOUS", "SIMPLE", "NTLM"] self.LDAP_SERVER = self.__get_config_option(app_configs=app_configs, option_name="ldap_server", optional=False, placeholder="xxx.xxx.xxx.xxx") self.LDAP_PORT = int(self.__get_config_option(app_configs=app_configs, option_name="ldap_port", optional=False)) self.LDAP_USE_SSL = self.str_to_bool(self.__get_config_option(app_configs=app_configs, option_name="ldap_use_ssl", optional=False)) self.LDAP_AUTH_TYPE = self.__get_config_option(app_configs=app_configs, option_name="ldap_auth", optional=False).upper() self.LDAP_USER_DN = self.__get_config_option(app_configs=app_configs, option_name="ldap_user_dn", optional=True) self.LDAP_USER_NTLM = self.__get_config_option(app_configs=app_configs, option_name="ldap_user_ntlm", optional=True) self.LDAP_PASSWORD = self.__get_config_option(app_configs=app_configs, option_name="ldap_password", optional=True) self.LDAP_IS_ACTIVE_DIRECTORY = self.str_to_bool(self.__get_config_option(app_configs=app_configs, option_name="ldap_is_active_directory", optional=False)) self.LDAP_CONNECT_TIMEOUT = int(self.__get_config_option(app_configs=app_configs, option_name="ldap_connect_timeout", optional=False)) if self.LDAP_AUTH_TYPE not in SUPPORTED_LDAP_AUTH_TYPE_TYPES: raise ValueError("Invalid value for 'ldap_auth'. '{0}' is not a supported authentication method. Support methods are: {1}".format(self.LDAP_AUTH_TYPE, SUPPORTED_LDAP_AUTH_TYPE_TYPES)) if self.LDAP_AUTH_TYPE == "SIMPLE": if not self.LDAP_USER_DN or not self.LDAP_PASSWORD: raise ValueError("'ldap_user_dn' and 'ldap_password' must be defined in the app.config file if using SIMPLE authentication to your LDAP Server") elif self.LDAP_AUTH_TYPE == "NTLM": if not self.LDAP_USER_NTLM or not self.LDAP_PASSWORD: raise ValueError("'ldap_user_ntlm' and 'ldap_password' must be defined in the app.config file if using NTLM authentication to your LDAP Server") elif self.LDAP_AUTH_TYPE == "ANONYMOUS": if self.LDAP_USER_DN or self.LDAP_USER_NTLM or self.LDAP_PASSWORD: raise ValueError("'ldap_user_dn', 'ldap_user_ntlm' and 'ldap_password' must be left blank in the app.config file if using ANONYMOUS authentication to your LDAP Server")
Example #18
Source File: __init__.py From anima with MIT License | 5 votes |
def ldap_authenticate(login, password, ldap_server_address=None, ldap_base_dn=None): """Authenticates with data from Stalker and creates a proper local session """ # check the LDAP server for login information success = False from anima import defaults if not ldap_server_address: ldap_server_address = defaults.ldap_server_address if not ldap_base_dn: ldap_base_dn = defaults.ldap_base_dn from ldap3 import Server, Connection if ldap_server_address and ldap_base_dn: ldap_server = Server(ldap_server_address) ldap_connection = Connection(server=ldap_server, user=login, password=password) success = ldap_connection.bind() logger.debug("ldap_connection.bind(): %s" % success) logger.debug("ldap_connection.extend.standard.who_am_i(): %s" % ldap_connection.extend.standard.who_am_i()) if success: result = ldap_connection.extend.standard.who_am_i() if result: create_user_with_ldap_info(ldap_connection, ldap_base_dn, login, password) ldap_connection.unbind() return success
Example #19
Source File: 11_7_query_ldap_server.py From Python-Network-Programming-Cookbook-Second-Edition with MIT License | 5 votes |
def main(address, dn, password): # Create the Server object with the given address. server = Server(address, get_info=ALL) #Create a connection object, and bind with the given DN and password. try: conn = Connection(server, dn, password, auto_bind=True) print('LDAP Bind Successful.') print(conn) except core.exceptions.LDAPBindError as e: # If the LDAP bind failed for reasons such as authentication failure. print('LDAP Bind Failed: ', e)
Example #20
Source File: 11_7_query_ldap_server_b.py From Python-Network-Programming-Cookbook-Second-Edition with MIT License | 5 votes |
def main(address, dn, password): # Create the Server object with the given address. server = Server(address, get_info=ALL) #Create a connection object, and bind with the given DN and password. try: conn = Connection(server, dn, password, auto_bind=True) print('LDAP Bind Successful.') # Perform a search for a pre-defined criteria. # Mention the search filter / filter type and attributes. conn.search('dc=example,dc=com', '(&(uid=euler))' , attributes=['sn']) # Print the resulting entries. print(conn.entries[0]) except core.exceptions.LDAPBindError as e: # If the LDAP bind failed for reasons such as authentication failure. print('LDAP Bind Failed: ', e)
Example #21
Source File: 11_6_connect_ldap_server.py From Python-Network-Programming-Cookbook-Second-Edition with MIT License | 5 votes |
def main(address): # Create the Server object with the given address. # Get ALL information. server = Server(address, get_info=ALL) #Create a connection object, and bind with auto bind set to true. conn = Connection(server, auto_bind=True) # Print the LDAP Server Information. print('******************Server Info**************') print(server.info) # Print the LDAP Server Detailed Schema. print('******************Server Schema**************') print(server.schema)
Example #22
Source File: api.py From diting with GNU General Public License v2.0 | 5 votes |
def post(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): host = serializer.validated_data["AUTH_LDAP_SERVER_URI"] bind_dn = serializer.validated_data["AUTH_LDAP_BIND_DN"] password = serializer.validated_data["AUTH_LDAP_BIND_PASSWORD"] use_ssl = serializer.validated_data.get("AUTH_LDAP_START_TLS", False) search_ou = serializer.validated_data["AUTH_LDAP_SEARCH_OU"] search_filter = serializer.validated_data["AUTH_LDAP_SEARCH_FILTER"] attr_map = serializer.validated_data["AUTH_LDAP_USER_ATTR_MAP"] try: attr_map = json.loads(attr_map) except json.JSONDecodeError: return Response({"error": "AUTH_LDAP_USER_ATTR_MAP not valid"}, status=401) server = Server(host, use_ssl=use_ssl) conn = Connection(server, bind_dn, password) try: conn.bind() except Exception as e: return Response({"error": str(e)}, status=401) ok = conn.search(search_ou, search_filter % ({"user": "*"}), attributes=list(attr_map.values())) if not ok: return Response({"error": "Search no entry matched"}, status=401) users = [] for entry in conn.entries: user = {} for attr, mapping in attr_map.items(): if hasattr(entry, mapping): user[attr] = getattr(entry, mapping) users.append(user) if len(users) > 0: return Response({"msg": _("Match {} s users").format(len(users))}) else: return Response({"error": "Have user but attr mapping error"}, status=401) else: return Response({"error": str(serializer.errors)}, status=401)
Example #23
Source File: api.py From diting with GNU General Public License v2.0 | 5 votes |
def get(self, request): host = settings.AUTH_LDAP_SERVER_URI bind_dn = settings.AUTH_LDAP_BIND_DN password = settings.AUTH_LDAP_BIND_PASSWORD use_ssl = settings.AUTH_LDAP_START_TLS search_ou = settings.AUTH_LDAP_SEARCH_OU search_filter = settings.AUTH_LDAP_SEARCH_FILTER attr_map = settings.AUTH_LDAP_USER_ATTR_MAP server = Server(host, use_ssl=use_ssl) conn = Connection(server, bind_dn, password) try: conn.bind() except Exception as e: return Response({"error": str(e)}, status=401) ok = conn.search(search_ou, search_filter % ({"user": "*"}), attributes=list(attr_map.values())) if not ok: return Response({"error": "Search no entry matched"}, status=401) users = [] for entry in conn.entries: # user = entry.entry_to_json(include_empty=True) # user_dict = json.loads(user) user = {} for attr, mapping in attr_map.items(): if hasattr(entry, mapping): user[attr] = getattr(entry, mapping).value #判断当前是否导入 local_user = User.objects.filter(username=user['username']) user['id'] = user['username'] if local_user: user['isImported'] = True # print("该用户已导入:%s" % local_user[0].username) else: user['isImported'] = False # print("没有导入ldap_local:%s"%local_user) users.append(user) return Response(data=users, status=200)
Example #24
Source File: gldap.py From adminset with GNU General Public License v2.0 | 5 votes |
def connect(self): server = Server(self.server) c = Connection(server, user=self.manager, password=self.passwd) c.bind() return c
Example #25
Source File: ldaprelayclient.py From Slackor with GNU General Public License v3.0 | 5 votes |
def initConnection(self): self.server = Server("ldaps://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL) self.session = Connection(self.server, user="a", password="b", authentication=NTLM) self.session.open(False) return True
Example #26
Source File: ldaprelayclient.py From Slackor with GNU General Public License v3.0 | 5 votes |
def initConnection(self): self.server = Server("ldap://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL) self.session = Connection(self.server, user="a", password="b", authentication=NTLM) self.session.open(False) return True
Example #27
Source File: ldap.py From knowledge-repo with Apache License 2.0 | 5 votes |
def init(self): if not self.app.config.get('LDAP_SERVER'): raise RuntimeError( "Use of LDAP authentication requires specification of the LDAP_SERVER configuration variable.") self.server = Server(self.app.config['LDAP_SERVER'], get_info=ALL)
Example #28
Source File: ldaprelayclient.py From krbrelayx with MIT License | 5 votes |
def initConnection(self, authdata, kdc=None): if not kdc: kdc = authdata['domain'] self.server = Server("ldaps://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL) self.session = Connection(self.server, user="a", password="b", authentication=SASL, sasl_mechanism=KERBEROS) ldap_kerberos(authdata['domain'], kdc, authdata['tgt'], authdata['username'], self.session, self.targetHost)
Example #29
Source File: ldaprelayclient.py From krbrelayx with MIT License | 5 votes |
def initConnection(self, authdata, kdc=None): if not kdc: kdc = authdata['domain'] self.server = Server("ldap://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL) self.session = Connection(self.server, user="a", password="b", authentication=SASL, sasl_mechanism=KERBEROS) ldap_kerberos(authdata['domain'], kdc, authdata['tgt'], authdata['username'], self.session, self.targetHost)
Example #30
Source File: models.py From realms-wiki with GNU General Public License v2.0 | 5 votes |
def __init__(self, config, userid, password): self.config = config self.tls = None self.setup_tls_options() self.server = ldap3.Server(self.config['URI'], tls=self.tls) self.userid = userid self.password = password self.version = int(self.config['LDAP_PROTO_VERSION']) self.conn = None