def connect_tls(self): kerberos = True try: if kerberos: tls_configuration = ldap3.Tls(validate=ssl.CERT_NONE, version=ssl.PROTOCOL_TLSv1_2) else: tls_configuration = Tls(local_private_key_file=self.key, local_certificate_file=self.cacert, validate=ssl.CERT_REQUIRED, version=ssl.PROTOCOL_TLSv1, ca_certs_file=self.cacert) except: tls_configuration = Tls(validate=ssl.CERT_REQUIRED, version=ssl.PROTOCOL_TLSv1_2) server = Server(self.uri, port=self.port, tls=tls_configuration, get_info=ALL) #, use_ssl=True, self.connection = Connection( server, user=self.binddn, password=self.password, # auto_bind=AUTO_BIND_NONE, version=3, authentication=SIMPLE, raise_exceptions=True) read_server_info = True self.connection.start_tls(read_server_info) try: self.connection.open() return self.connection.bind() except Exception as e: print("LDAP conenction error %s " % e) return False
def _ldap_bind(self, action_result=None): """ returns phantom.APP_SUCCESS if connection succeeded, else phantom.APP_ERROR. If an action_result is passed in, method will appropriately use it. Otherwise just return APP_SUCCESS/APP_ERROR """ if self._ldap_connection and \ self._ldap_connection.bound and \ not self._ldap_connection.closed: return True elif self._ldap_connection is not None: self._ldap_connection.unbind() try: if self._validate_ssl_cert: tls = Tls(validate=ssl.CERT_REQUIRED) else: tls = Tls(validate=ssl.CERT_NONE) server_param = { "use_ssl": self._ssl, "port": self._ssl_port, "host": self._server, "get_info": ldap3.ALL, "tls": tls } self._ldap_server = ldap3.Server(**server_param) self.save_progress("configured server {}...".format(self._server)) self._ldap_connection = ldap3.Connection(self._ldap_server, user=self._username, password=self._password, raise_exceptions=True) self.save_progress("binding to directory...") if not self._ldap_connection.bind(): if action_result: return action_result.set_status( phantom.APP_ERROR, self._ldap_connection.result['description']) else: return phantom.APP_ERROR if action_result: return action_result.set_status(phantom.APP_SUCCESS) else: return phantom.APP_SUCCESS except Exception as e: self.debug_print("[DEBUG] ldap_bind, e = {}".format(e)) if action_result: return action_result.set_status(phantom.APP_ERROR, status_message=e, exception=e) else: return phantom.APP_ERROR
def connect(domain_controller, base_dn, user, password, use_ldaps=False, certificate_data=None): logging.info("Connecting to LDAP endpoint of '%s' as '%s'" % (domain_controller, user)) if use_ldaps: logging.info("Using LDAP over SSL/TLS") tls_configuration = Tls(ssl.create_default_context( ssl.Purpose.SERVER_AUTH), validate=ssl.CERT_REQUIRED) if certificate_data is not None: logging.debug("Using CA certificate data from Secret Manager") tls_configuration.ca_certs_data = certificate_data server = ldap3.Server(domain_controller, port=636, connect_timeout=5, use_ssl=True, tls=tls_configuration) else: server = ldap3.Server(domain_controller, port=389, connect_timeout=5, use_ssl=False) connection = ldap3.Connection(server, user=user, password=password, authentication=ldap3.NTLM, raise_exceptions=True) try: if connection.bind(): return ActiveDirectoryConnection(domain_controller, connection, base_dn) except LDAPStrongerAuthRequiredResult: logging.exception( "Failed to connect to LDAP endpoint: Active Directory requires LDAPS for NTLM binds" ) except LDAPException as e: logging.warn("Failed to connect to LDAP endpoint: %s" % e) # LDAP connection could not be established, raise exception raise LdapException( "Connecting to LDAP endpoint of '%s' as '%s' failed" % (domain_controller, user))
def modify_ad_password(self, AD_SERVER, BIND_USENAME, BIND_PASSWORD, USER_DN, NEW_PASSWORD): tls_config = Tls(validate=ssl.CERT_NONE) server = Server(AD_SERVER, port=636, use_ssl=True, tls=tls_config, get_info=ALL) # print(AD_SERVER, BIND_USENAME, # BIND_PASSWORD, USER_DN, NEW_PASSWORD) try: conn = Connection(server, BIND_USENAME, BIND_PASSWORD) conn.start_tls() if not conn.bind(): return 'Bind ERROR {}'.format(conn.result) conn.extend.microsoft.modify_password(USER_DN, NEW_PASSWORD) rs_mod = conn.result except Exception as e: return 'ERROR from modify_ad_password()--->{}'.format(e) conn.unbind() # return 'Operation Modify Password Result : {}'.format(rs_mod) return (rs_mod)
def create_group(self, AD_SERVER, OU_BASE, DOMAIN, BIND_USERNAME, BIND_PASSWORD, NEW_GROUP, DESCRIPTION): tlsconfig = Tls(validate=ssl.CERT_NONE) server = Server(AD_SERVER, port=636, use_ssl=True, tls=tlsconfig, get_info=ALL) print(AD_SERVER, OU_BASE, DOMAIN, BIND_USERNAME, BIND_PASSWORD, NEW_GROUP, DESCRIPTION) try: conn = Connection(server, BIND_USERNAME, BIND_PASSWORD) conn.start_tls() if not conn.bind(): return 'Bind ERROR {}'.format(conn.result) temp_group_dn = 'cn=' + NEW_GROUP + ',' + OU_BASE print(temp_group_dn) conn.add(temp_group_dn, 'group', {'description': DESCRIPTION}) if conn.result['result'] != 0: conn.unbind() return conn.result print(conn.result) except Exception as e: return 'Create Group Error : {}'.format(e) conn.unbind() return conn.result
def get_ldap_connection(dn=None, password=None): try: cacert = configuration.conf.get("ldap", "cacert") except AirflowConfigException: pass try: ignore_malformed_schema = configuration.conf.get( "ldap", "ignore_malformed_schema") except AirflowConfigException: pass if ignore_malformed_schema: set_config_parameter('IGNORE_MALFORMED_SCHEMA', ignore_malformed_schema) tls_configuration = Tls(validate=ssl.CERT_REQUIRED, ca_certs_file=cacert) server = Server(configuration.conf.get("ldap", "uri"), use_ssl=True, tls=tls_configuration) conn = Connection(server, dn, password) if not conn.bind(): log.error("Cannot bind to ldap server: %s ", conn.last_error) raise AuthenticationError("Cannot bind to ldap server") return conn
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) 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)
def authenticate(self, request, username=None, password=None): """ 独自バックエンドに必須のメソッド Active Directoryへusernameとpasswordでbindして認証を実施 該usernameがDjangoに存在しない場合は、新規作成する必要がある """ if not (username and password): return None tls = Tls(validate=CERT_NONE, version=PROTOCOL_SSLv23) server = Server(host=settings.LDAP_HOST, port=settings.LDAP_PORT, use_ssl=True, tls=tls) connection = Connection(server, user='******'.format(settings.LDAP_DOMAIN, username), password=password) if not connection.bind(): return None try: user = User.objects.get(username=username) except User.DoesNotExist: user = User(username=username) user.is_staff = True user.is_superuser = True user.save() return user
def authenticate(self, request, username=None, password=None, **keyword_arguments): if not username or not password: return None # The user must exist in the database try: user = User.objects.get(username=username) except User.DoesNotExist: logger.warning(f"Username {username} attempted to authenticate with LDAP, but that username does not exist in the NEMO database. The user was denied access.") return None # The user must be marked active. if not user.is_active: logger.warning(f"User {username} successfully authenticated with LDAP, but that user is marked inactive in the NEMO database. The user was denied access.") return None for server in settings.LDAP_SERVERS: try: t = Tls(validate=CERT_REQUIRED, version=PROTOCOL_TLSv1_2, ca_certs_file=server['certificate']) s = Server(server['url'], port=636, use_ssl=True, tls=t) c = Connection(s, user='******'.format(server['domain'], username), password=password, auto_bind=AUTO_BIND_TLS_BEFORE_BIND, authentication=SIMPLE) c.unbind() # At this point the user successfully authenticated to at least one LDAP server. return user except LDAPBindError as e: logger.warning(f"User {username} attempted to authenticate with LDAP, but entered an incorrect password. The user was denied access.") pass # When this error is caught it means the username and password were invalid against the LDAP server. except LDAPExceptionError as e: exception(e) # The user did not successfully authenticate to any of the LDAP servers. return None
def update_cert(email, auth_user, auth_pw, cert_path=""): der_cert = open(cert_path, "rb").read() # email to: cn, dc, dc emailSplit1 = email.split('@') username = emailSplit1[0] emailSplit2 = emailSplit1[1].split('.') dc0 = emailSplit2[0] dc1 = emailSplit2[1] # Open connection tls = Tls(validate=ssl.CERT_NONE) server = Server(LDAP_SERVER_TLS, get_info=ALL, use_ssl=True, tls=tls) conn = Connection(server, user=auth_user, password=auth_pw) conn.bind() # check if certificate exists at server if get_cert(email) != None: print("cert found") rc = conn.modify( "uid=" + email + ",ou=certificates," + LDAP_SEARCH_BASE, {"userCertificate;binary": [(MODIFY_REPLACE, der_cert)]}) print(conn.result) else: print("cert not found") rc = conn.modify( "uid=" + email + ",ou=certificates," + LDAP_SEARCH_BASE, {"userCertificate;binary": [(MODIFY_ADD, der_cert)]}) print(conn.result)
def authenticate(self, request, username=None, password=None, **keyword_arguments): if not username or not password: return None # The user must exist in the database try: user = User.objects.get(username=username) except User.DoesNotExist: auth_logger.warning( f"Username {username} attempted to authenticate with LDAP, but that username does not exist in the NEMO database. The user was denied access." ) return None # The user must be marked active. if not user.is_active: auth_logger.warning( f"User {username} successfully authenticated with LDAP, but that user is marked inactive in the NEMO database. The user was denied access." ) return None is_authenticated_with_ldap = False errors = [] for server in settings.LDAP_SERVERS: try: t = Tls(validate=CERT_REQUIRED, version=PROTOCOL_TLSv1_2, ca_certs_file=server.get('certificate')) s = Server(server['url'], port=636, use_ssl=True, tls=t) c = Connection(s, user='******'.format(server['domain'], username), password=password, auto_bind=AUTO_BIND_TLS_BEFORE_BIND, authentication=SIMPLE) c.unbind() # At this point the user successfully authenticated to at least one LDAP server. is_authenticated_with_ldap = True auth_logger.debug( f"User {username} was successfully authenticated with LDAP ({server['url']})" ) break except LDAPBindError as e: errors.append( f"User {username} attempted to authenticate with LDAP ({server['url']}), but entered an incorrect password. The user was denied access: {str(e)}" ) except LDAPExceptionError as e: errors.append( f"User {username} attempted to authenticate with LDAP ({server['url']}), but an error occurred. The user was denied access: {str(e)}" ) if is_authenticated_with_ldap: return user else: for error in errors: auth_logger.warning(error) return None
def loadConfig(self, config): """ Load the config from conf. :param config: The configuration from the Config Table :type config: dict '#ldap_uri': 'LDAPURI', '#ldap_basedn': 'LDAPBASE', '#ldap_binddn': 'BINDDN', '#ldap_password': '******', '#ldap_timeout': 'TIMEOUT', '#ldap_sizelimit': 'SIZELIMIT', '#ldap_loginattr': 'LOGINNAMEATTRIBUTE', '#ldap_searchfilter': 'LDAPSEARCHFILTER', '#ldap_mapping': 'USERINFO', '#ldap_uidtype': 'UIDTYPE', '#ldap_noreferrals' : 'NOREFERRALS', '#ldap_editable' : 'EDITABLE', '#ldap_certificate': 'CACERTIFICATE', """ self.uri = config.get("LDAPURI") self.basedn = config.get("LDAPBASE") self.binddn = config.get("BINDDN") # object_classes is a comma separated list like # ["top", "person", "organizationalPerson", "user", "inetOrgPerson"] self.object_classes = [ cl.strip() for cl in config.get("OBJECT_CLASSES", "").split(",") ] self.dn_template = config.get("DN_TEMPLATE", "") self.bindpw = config.get("BINDPW") self.timeout = float(config.get("TIMEOUT", 5)) self.cache_timeout = int(config.get("CACHE_TIMEOUT", 120)) self.sizelimit = int(config.get("SIZELIMIT", 500)) self.loginname_attribute = config.get("LOGINNAMEATTRIBUTE") self.searchfilter = config.get("LDAPSEARCHFILTER") userinfo = config.get("USERINFO", "{}") self.userinfo = yaml.safe_load(userinfo) self.userinfo["username"] = self.loginname_attribute self.map = yaml.safe_load(userinfo) self.uidtype = config.get("UIDTYPE", "DN") self.noreferrals = is_true(config.get("NOREFERRALS", False)) self.start_tls = is_true(config.get("START_TLS", False)) self._editable = config.get("EDITABLE", False) self.scope = config.get("SCOPE") or ldap3.SUBTREE self.resolverId = self.uri self.authtype = config.get("AUTHTYPE", AUTHTYPE.SIMPLE) self.tls_verify = is_true(config.get("TLS_VERIFY", False)) self.tls_ca_file = config.get("TLS_CA_FILE") or DEFAULT_CA_FILE if self.tls_verify and (self.uri.lower().startswith("ldaps") or self.start_tls): self.tls_context = Tls(validate=ssl.CERT_REQUIRED, version=ssl.PROTOCOL_TLSv1, ca_certs_file=self.tls_ca_file) else: self.tls_context = None return self
def test_ldap_authentication(): """ Opens an encrypted connection (using only TLS 1.2) to an LDAP directory (such as Active Directory) and tests authentication """ name = input("DNS name or IP address = ") domain = input("Domain = ") username = input("Username = "******"Password = "******"Path to public key certificate = ") try: t = Tls(validate=CERT_REQUIRED, version=PROTOCOL_TLSv1_2, ca_certs_file=certificate) s = Server(name, port=636, use_ssl=True, tls=t) c = Connection(s, user='******'.format(domain, username), password=password, auto_bind=AUTO_BIND_TLS_BEFORE_BIND, authentication=SIMPLE) c.unbind() # At this point the user successfully authenticated to at least one LDAP server. print("Authentication successful!") except LDAPBindError: pass # When this error is caught it means the username and password were invalid against the LDAP server. except LDAPExceptionError as error: print("A problem was encountered during authentication:\n") print(error)
def _ldap_server_connect(): """ Connect to an LDAP server :param ldap_server: LDAP Server Hostname / IP Address :param ldap_port: Port to use on LDAP server :param ldap_use_tls: Use a secure connection to the LDAP server :param ldap_cert_path: Certificate for Secure connection to LDAP :param ldap_sa_bind_dn: LDAP Bind Distinguished Name for Service Account :param ldap_sa_password: LDAP Service Account password :return: LDAP Context """ ldap_server = current_app.config['LDAP_SERVER'] ldap_port = int(current_app.config['LDAP_PORT']) ldap_use_tls = current_app.config['LDAP_USE_TLS'] ldap_key_path = current_app.config['LDAP_KEY_PATH'] ldap_sa_bind_dn = current_app.config['LDAP_SA_BIND_DN'] ldap_sa_password = current_app.config['LDAP_SA_PASSWORD'] tls = Tls(validate=ssl.CERT_NONE, local_private_key_file=ldap_key_path) if ldap_use_tls: server = Server(ldap_server, ldap_port, tls=tls, use_ssl=True) else: server = Server(ldap_server, ldap_port) conn = Connection(server, ldap_sa_bind_dn, ldap_sa_password, auto_bind=True) return conn
def connect(self): # check configuration if not (hasattr(settings, 'LDAP_SERVERS') and hasattr(settings, 'LDAP_BIND_ADMIN') and hasattr(settings, 'LDAP_BIND_ADMIN_PASS') and hasattr(settings, 'LDAP_AD_DOMAIN') and hasattr(settings, 'LDAP_CERT_FILE')): raise ImproperlyConfigured() # first: build server pool from settings tls = Tls(validate=ssl.CERT_OPTIONAL, version=ssl.PROTOCOL_TLSv1, ca_certs_file=settings.LDAP_CERT_FILE) if self.pool is None: self.pool = ServerPool(None, pool_strategy=FIRST, active=True) for srv in settings.LDAP_SERVERS: # Only add servers that supports SSL, impossible to make changes without if srv['use_ssl']: server = Server(srv['host'], srv['port'], srv['use_ssl'], tls=tls) self.pool.add(server) # then, try to connect with user/pass from settings self.con = Connection(self.pool, auto_bind=True, authentication=SIMPLE, user=settings.LDAP_BIND_ADMIN, password=settings.LDAP_BIND_ADMIN_PASS)
def init_app(self, app): # Default config app.config.setdefault('LDAP_SERVER', 'localhost') app.config.setdefault('LDAP_PORT', 389) app.config.setdefault('LDAP_BINDDN', None) app.config.setdefault('LDAP_SECRET', None) app.config.setdefault('LDAP_TIMEOUT', 10) app.config.setdefault('LDAP_USE_SSL', False) app.config.setdefault('LDAP_USE_TLS', True) app.config.setdefault('LDAP_TLS_VERSION', PROTOCOL_TLSv1) app.config.setdefault('LDAP_REQUIRE_CERT', CERT_REQUIRED) app.config.setdefault('LDAP_CERT_PATH', None) app.config.setdefault('LDAP_CLIENT_PRIVATE_KEY', None) app.config.setdefault('LDAP_CLIENT_CERT', None) app.config.setdefault('LDAP_READ_ONLY', False) self.tls = Tls( local_private_key_file=app.config['LDAP_CLIENT_PRIVATE_KEY'], local_certificate_file=app.config['LDAP_CLIENT_CERT'], validate=app.config['LDAP_REQUIRE_CERT'], version=app.config['LDAP_TLS_VERSION'], ca_certs_file=app.config['LDAP_CERT_PATH']) self.ldap_server = Server(host=app.config['LDAP_SERVER'], port=app.config['LDAP_PORT'], use_ssl=app.config['LDAP_USE_SSL'], tls=self.tls, get_info=GET_ALL_INFO) # Store ldap_conn object to extensions app.extensions['ldap_conn'] = self # Teardown appcontext app.teardown_appcontext(self.teardown)
def create_server(self) -> Server: # PyCharm wants this here to not complain about the return statement. transport_layer_security = None if self.secure: certificate_chain = join( dirname(realpath(__file__)), 'certificate_chain.pem', ) try: transport_layer_security = Tls( validate=CERT_REQUIRED, ca_certs_file=certificate_chain, version=PROTOCOL_TLSv1_2, ) except LDAPSSLConfigurationError as exception: print('LDAPSSLConfigurationError: ' + str(exception)) print('certificate_chain: ' + certificate_chain) print('server_name: ' + self.server_name) exit(4) return Server( host=self.server_name, port=389, # TODO: Why no get_info? # get_info=False, get_info=ALL, tls=transport_layer_security, )
def authenticate(domain, username, password): """ Verifies credentials for username and password. Returns True on success or False on failure """ tls_configuration = Tls(validate=ssl.CERT_NONE, version=ssl.PROTOCOL_TLSv1_2) # define the server and the connection s = Server(domain, port=636, use_ssl=True, tls=tls_configuration) conn = Connection(s, domain + "\\" + username, password, authentication=NTLM) conn.start_tls() conn.bind() # print(conn.usage) # perform the Bind operation try: if not conn.bind(): print("Not Connected") conn.unbind() return False else: print("Connected") conn.unbind() return True finally: pass
def ldap_auth(auth_username, auth_pass): key = hashlib.pbkdf2_hmac('sha256', auth_pass.encode('utf-8'), expiring_salt(), 10) # check if the key is already in the cache. If so return true as if the authentication response was valid. Otherwise continue to authenticate and cache the actual response r = redis.StrictRedis(host=redis_host, port=redis_port, password=redis_password, decode_responses=True) cached = r.get(key) if cached: return True else: tls_ctx = Tls(validate=ssl.CERT_REQUIRED, ca_certs_file='/app/cacerts/cafile', version=ssl.PROTOCOL_TLSv1_2) server = Server('ldaps://' + ldap_host, use_ssl=True, tls=tls_ctx, port=636) conn = Connection(server, user='******' + auth_username + ',ou=Users,o=AUTH', password=auth_pass, auto_bind=True) result = conn.bind() if result: r.set(key, 1, ex=10) # cached key will expire after 10 sec return True else: return False
def _ldap_server_connect(): """ Connect to an LDAP server :return: LDAP Context """ ldap_server = current_app.config['LDAP_SERVER'] ldap_port = int(current_app.config['LDAP_PORT']) ldap_use_tls = current_app.config['LDAP_USE_TLS'] ldap_key_path = current_app.config['LDAP_KEY_PATH'] ldap_sa_bind_dn = current_app.config['LDAP_SA_BIND_DN'] ldap_sa_password = current_app.config['LDAP_SA_PASSWORD'] tls = Tls(validate=ssl.CERT_NONE, local_private_key_file=ldap_key_path) if ldap_use_tls: server = Server(ldap_server, ldap_port, tls=tls, use_ssl=True) else: server = Server(ldap_server, ldap_port) conn = Connection(server, ldap_sa_bind_dn, ldap_sa_password, auto_bind=True) return conn
def tls(): t = Tls(local_private_key_file=settings.LOCAL_PRIVATE_KEY_FILE, local_certificate_file=settings.LOCAL_CERTIFICATE_KEY_FILE, validate=ssl.CERT_REQUIRED, version=ssl.PROTOCOL_TLSv1, ca_certs_file=settings.CA_CERTS_FILE) return t
def test_start_tls_extension(self): if not self.connection.strategy.no_real_dsa: connection = get_connection(use_ssl=False) connection.server.tls = Tls() result = connection.start_tls() self.assertTrue(result) connection.unbind()
def get_ad_users_group_dn(self, AD_SERVER, SEARCH_BASE, BIND_USERNAME, BIND_PASSWORD, SERCH_TYPE, SEARCH_OBJ): FILTERS = '(&(objectclass=' + SERCH_TYPE + ')(cn=' + SEARCH_OBJ + '))' tlsconfig = Tls(validate=ssl.CERT_NONE) server = Server(AD_SERVER, port=636, use_ssl=True, tls=tlsconfig, get_info=ALL) # print(AD_SERVER, BIND_USENAME, BIND_PASSWORD, SEARCH_OBJ) if str(SEARCH_OBJ).find('*') != -1: return 'NO Allows ******* Input' else: try: conn = Connection(server, BIND_USERNAME, BIND_PASSWORD) conn.start_tls() if not conn.bind(): return 'Bind ERROR {}'.format(conn.result) conn.search(SEARCH_BASE, FILTERS) entry = conn.entries[0].entry_to_json() except Exception as e: return 'SEARCH_ERROR : {}'.format(e) conn.unbind() group_dn = json.loads(entry) return group_dn['dn']
def add_member_to_group(self, AD_SERVER, SEARCH_BASE, BIND_USERNAME, BIND_PASSWORD, MEMBER_NAME, GROUP_NAME): tlsconfig = Tls(validate=ssl.CERT_NONE) server = Server(AD_SERVER, port=636, use_ssl=True, tls=tlsconfig, get_info=ALL) # print(AD_SERVER, BIND_USENAME, BIND_PASSWORD, SEARCH_OBJ) try: conn = Connection(server, BIND_USERNAME, BIND_PASSWORD) conn.start_tls() if not conn.bind(): return 'Bind ERROR {}'.format(conn.result) group_dn = self.get_ad_users_group_dn(AD_SERVER, SEARCH_BASE, BIND_USERNAME, BIND_PASSWORD, 'group', GROUP_NAME) user_dn = self.get_ad_users_group_dn(AD_SERVER, SEARCH_BASE, BIND_USERNAME, BIND_PASSWORD, 'person', MEMBER_NAME) rs = addUsersInGroups(conn, user_dn, group_dn) print(rs, group_dn, user_dn) except Exception as e: return 'SEARCH_ERROR : {}'.format(e) conn.unbind() return 'ADD USER : '******' --- to --- > GROUP : ' + group_dn + " Completed"
def modify_ad_attributes(self, AD_SERVER, BIND_USENAME, BIND_PASSWORD, USER_DN, ATTRIBUTE_NAME, NEW_VALUE): tls_config = Tls(validate=ssl.CERT_NONE) server = Server(AD_SERVER, port=636, use_ssl=True, tls=tls_config, get_info=ALL) # print(AD_SERVER, BIND_USENAME, BIND_PASSWORD, # USER_DN, ATTRIBUTE_NAME, NEW_VALUE) try: conn = Connection(server, BIND_USENAME, BIND_PASSWORD) conn.start_tls() if not conn.bind(): return 'Bind ERROR {}'.format(conn.result) conn.modify(USER_DN, {ATTRIBUTE_NAME: [(MODIFY_REPLACE, [NEW_VALUE])]}) rs_mod = conn.result except Exception as e: return 'ERROR from modify_ad_attributes()--->{}'.format(e) conn.unbind() return 'Operation Modify Attributes Result : {}'.format(rs_mod)
def main(): #conn1 = Connection(server1, 'uid=administrator, dc=samba, dc=redos', password='******') tls = Tls(validate=ssl.CERT_NONE, version=ssl.PROTOCOL_TLSv1_2) server1 = Server('185.61.26.170:54732', get_info=ALL, tls=tls) print(server1) c = Connection(server1, authentication=SASL, sasl_mechanism=KERBEROS) c.bind() print(c.extend.standard.who_am_i()) # conn1.bind() # print(conn1) # f = conn1.extend.standard.who_am_i() #print(f) server = Server('ipa.demo1.freeipa.org', use_ssl=True, get_info=ALL) print(server) conn = Connection( server, 'uid=admin, cn=users, cn=accounts, dc=demo1, dc=freeipa,dc=org', 'Secret123', auto_bind=True) f = conn.extend.standard.who_am_i() print(conn.extend.standard.who_am_i()) return f
def get_ldap_connection(dn=None, password=None): ldap_uri = conf.get("ldap", "uri") isSslEnable = False try: isSslEnable = conf.get("ldap", "isssl") except AirflowConfigException: pass if isSslEnable : log.info('Connect LDAP with SSL') tls_config = Tls(validate=ssl.CERT_NONE) server = Server(ldap_uri, use_ssl=True, tls=tls_config) conn = Connection(server, dn, password) else : log.info('Connect LDAP without SSL') server = Server(ldap_uri) conn = Connection(server, dn, password) if not conn.bind(): log.error("Cannot bind to ldap server: %s ", conn.last_error) raise AuthenticationError("Cannot bind to ldap server") return conn
def test_bind_ssl_cert_none(self): if test_strategy not in [MOCK_SYNC, MOCK_ASYNC]: tls = Tls(validate=ssl.CERT_NONE) if isinstance(test_server, (list, tuple)): server = ServerPool(pool_strategy=test_pooling_strategy, active=test_pooling_active, exhaust=test_pooling_exhaust) for host in test_server: server.add( Server(host=host, port=test_port, allowed_referral_hosts=('*', True), get_info=test_get_info, mode=test_server_mode)) else: server = Server(host=test_server, port=test_port_ssl, use_ssl=True, tls=tls) connection = Connection(server, auto_bind=False, client_strategy=test_strategy, user=test_user, password=test_password, authentication=test_authentication) connection.open() connection.bind() self.assertTrue(connection.bound) connection.unbind() if connection.strategy.pooled: connection.strategy.terminate() self.assertFalse(connection.bound)
def test_open_with_tls_before_bind(self): if test_strategy not in [MOCK_SYNC, MOCK_ASYNC]: if isinstance(test_server, (list, tuple)): server = ServerPool(pool_strategy=test_pooling_strategy, active=test_pooling_active, exhaust=test_pooling_exhaust) for host in test_server: server.add( Server(host=host, port=test_port, allowed_referral_hosts=('*', True), get_info=test_get_info, mode=test_server_mode)) else: server = Server(host=test_server, port=test_port, tls=Tls()) connection = Connection(server, auto_bind=False, version=3, client_strategy=test_strategy, user=test_user, password=test_password, authentication=test_authentication, lazy=test_lazy_connection, pool_name='pool1') connection.open() connection.start_tls() connection.bind() self.assertTrue(connection.bound) connection.unbind() if connection.strategy.pooled: connection.strategy.terminate() self.assertFalse(connection.bound)
def __init__(self, conf=None): self.conf = if_not(conf, def_conf) self.tls_config = Tls(validate=ssl.CERT_NONE, version=ssl.PROTOCOL_TLSv1) self.server = Server(self.conf.LDAP_DOMAIN, get_info=ALL, use_ssl=conf.LDAP_USE_SSL, tls=self.tls_config)