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, native(dn), native(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 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 build_sds_connection_tls(ldap_address: str, private_key: str, local_cert: str, ca_certs: str) -> ldap3.Connection: """ This will return a connection object for the given ip along with loading the given certification files :param ldap_address: The URL of the LDAP server to connect to. :param private_key: A string containing the client private key. :param local_cert: A string containing the client certificate. :param ca_certs: A string containing certificate authority certificates :return: Connection object using the given cert files """ certificates = certs.Certs.create_certs_files(definitions.ROOT_DIR, private_key=private_key, local_cert=local_cert, ca_certs=ca_certs) load_tls = ldap3.Tls(local_private_key_file=certificates.private_key_path, local_certificate_file=certificates.local_cert_path, validate=ssl.CERT_REQUIRED, version=ssl.PROTOCOL_TLSv1, ca_certs_file=certificates.ca_certs_path) ldap3.set_config_parameter('RESTARTABLE_TRIES', _LDAP_CONNECTION_RETRIES) server = ldap3.Server(ldap_address, use_ssl=True, tls=load_tls, connect_timeout=_LDAP_CONNECTION_TIMEOUT_IN_SECONDS) logger.info('Configuring LDAP connection using TLS') return _configure_ldap_connection(server)
def _build_sds_connection(ldap_address: str) -> ldap3.Connection: """ Given an ldap service address this will return a ldap3 connection object """ ldap3.set_config_parameter('RESTARTABLE_TRIES', _LDAP_CONNECTION_RETRIES) server = ldap3.Server(ldap_address, connect_timeout=_LDAP_CONNECTION_TIMEOUT_IN_SECONDS) logger.info('Configuring LDAP connection without TLS') return _configure_ldap_connection(server)
def connect(self): """Connects (binds) to LDAP server.""" ldap3.set_config_parameter('RESTARTABLE_TRIES', 3) server = ldap3.Server(self.uri) self.ldap = ldap3.Connection( server, authentication=ldap3.SASL, sasl_mechanism='GSSAPI', client_strategy=ldap3.STRATEGY_SYNC_RESTARTABLE, auto_bind=True)
def process(self) -> int: """ The only public method of this class, call straight after construction, returns an integer that can/should be used for the process exit value """ self._check_bind_creds() log_item("Connecting to LDAP Server", self.ldap_host_port) if self.ldap_log: logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) set_library_log_activation_level(EXTENDED) set_library_log_detail_level(EXTENDED) set_config_parameter('RESPONSE_WAITING_TIMEOUT', self.ldap_timeout) set_config_parameter('IGNORE_MALFORMED_SCHEMA', True) server = ldap3.Server(self.ldap_host, port=self.ldap_port, connect_timeout=self.ldap_timeout, get_info=ldap3.ALL, use_ssl=False, tls=None, mode=ldap3.IP_V4_ONLY) start = time.time() rc = 0 try: rc = self._process_connection(server) except LDAPBindError: log_error( f"Unable to bind using dn: {self.bind_dn} and the given password" ) rc = 3 except LDAPResponseTimeoutError: log_error("Server timed out") rc = 4 except LDAPSocketOpenError: log_error(f"Could not connect with {self.ldap_host_port}") rc = 5 except PyAsn1Error as e: log_error(f"Could not connect with {self.ldap_host_port}: {e}") rc = 6 except LDAPSocketReceiveError as e: log_error(f"LDAP Socket Receive Error: {e}") rc = 7 log_item('Seconds', time.time() - start) # activity_iri = self.prov_activity_start(xlsx_iri) # self.prov_activity_end(activity_iri) log_item("Return Code", rc) return rc
def connect(self): """Connects (binds) to LDAP server.""" ldap3.set_config_parameter('RESTARTABLE_TRIES', 3) for uri in self.uri: try: server = ldap3.Server(uri) self.ldap = ldap3.Connection( server, authentication=ldap3.SASL, sasl_mechanism='GSSAPI', client_strategy=ldap3.STRATEGY_SYNC_RESTARTABLE, auto_bind=True) except (ldap3.LDAPSocketOpenError, ldap3.LDAPBindError, ldap3.LDAPMaximumRetriesError): _LOGGER.exception('Could not connect to %s', uri) else: break # E0704: The raise statement is not inside an except clause if not self.ldap: raise # pylint: disable=E0704
def connect(self): try: set_config_parameter("RESTARTABLE_SLEEPTIME", 1) set_config_parameter("RESTARTABLE_TRIES", 2) set_config_parameter('DEFAULT_SERVER_ENCODING', 'utf-8') set_config_parameter('DEFAULT_CLIENT_ENCODING', 'utf-8') self.conn = Connection(Server(self.ldap_server_uri, get_info=NONE), self.ldap_binddn, self.ldap_bindpw, auto_bind=True, raise_exceptions=True, client_strategy='RESTARTABLE', receive_timeout=self.ldap_receive_timeout) except LDAPException as e: raise ExOTAPolicyBackendException( "An error occured while connecting to LDAP backend: " + traceback.format_exc()) from e
test_fast_decoder = True if environ['DECODER'].upper( ) == 'INTERNAL' else False test_check_names = True if environ['CHECK_NAMES'].upper( ) == 'TRUE' else False else: location += '-' + test_server_type # # force TRAVIS configuration # location = 'TRAVIS-LOCAL' # test_strategy = ASYNC # test_server_type = 'AD' # test_fast_decoder = True if 'TRAVIS' in location: # test in the cloud set_config_parameter('RESPONSE_WAITING_TIMEOUT', 30) if test_server_type == 'EDIR': test_server_context = 'o=resources' # used in Novell eDirectory extended operations test_server = 'labldap02.cloudapp.net' test_server_edir_name = 'SLES1' test_root_partition = '' test_base = 'ou=fixtures,o=test' # base context where test objects are created test_moved = 'ou=moved,o=test' # base context where objects are moved in ModifyDN operations test_name_attr = 'cn' # naming attribute for test objects test_int_attr = 'loginGraceLimit' test_multivalued_attribute = 'givenname' test_singlevalued_attribute = 'generationQualifier' test_user = '******' # the user that performs the tests test_password = '******' # user password test_secondary_user = '******' test_secondary_password = '******'
import argparse import ssl import json import csv parser = argparse.ArgumentParser() parser.add_argument("servername", type=str, help=" -> serverldap") parser.add_argument("username", type=str, help=" -> username") parser.add_argument("password", type=str, help=" -> password") parser.add_argument("dnbase", type=str, help=" -> dnbase") # Accept Self-Sign Certificates # ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) #server = Server('10.134.2.43' ,port=389, use_ssl=False, get_info=ALL_ATTRIBUTES) server = Server('10.4.1.47', port=389, use_ssl=False, get_info=ALL_ATTRIBUTES) set_config_parameter('DEFAULT_CLIENT_ENCODING', 'utf8') BaseAD = "ou=grp_sces,ou=groupes,dc=adchpg,dc=chpg,dc=mc" BaseeDir = "ou=grp_partages,O=chpg" Scope = 'SUBTREE' FilterAD = "(&(objectClass=Group)(!(objectClass=computer)))" FiltereDir = "(&(objectClass=Group))" AttrsAD = ['samAccountName', 'dn', 'member', 'cn'] AttrseDir = ['dn', 'member', 'cn'] #conn = Connection(server, 'cn=Netonline,ou=Externes,ou=Utilisateurs,dc=adchpg,dc=chpg,dc=mc', 'Netonline@26', auto_bind=True) #conn.search(search_base=BaseAD, search_filter=FilterAD, search_scope=Scope, attributes=AttrsAD ) conn = Connection(server, 'cn=netonline,ou=presta,ou=ext,o=chpg', 'Netonline@26', auto_bind=True) conn.search(search_base=BaseeDir,
import json from six import add_metaclass from copy import deepcopy from importlib import import_module from flask import current_app from ldap3 import ObjectDef, set_config_parameter import ldap3.core.exceptions from ldap3.utils.dn import safe_dn from ldap3.utils.conv import check_json_dict, format_json from .query import BaseQuery from .attribute import LDAPAttribute set_config_parameter('DEFAULT_ENCODING', 'utf-8') __all__ = ('LDAPEntry', ) class LDAPEntryMeta(type): # requiered base_dn = None entry_rdn = ['cn'] object_classes = ['top'] # optional sub_tree = True operational_attributes = False
g_milter_expect_auth = True if 'MILTER_WHITELISTED_RCPTS' in os.environ: # A blank separated list is expected whitelisted_rcpts_str = os.environ['MILTER_WHITELISTED_RCPTS'] # for whitelisted_rcpt in whitelisted_rcpts_str.split(): for whitelisted_rcpt in re.split(',|\s', whitelisted_rcpts_str): if g_re_email.match(whitelisted_rcpt) == None: logging.error( "ENV[MILTER_WHITELISTED_RCPTS]: invalid email address: " + whitelisted_rcpt) sys.exit(1) else: logging.info("ENV[MILTER_WHITELISTED_RCPTS]: " + whitelisted_rcpt) g_milter_whitelisted_rcpts[whitelisted_rcpt] = {} set_config_parameter("RESTARTABLE_SLEEPTIME", 2) set_config_parameter("RESTARTABLE_TRIES", 2) server = Server(g_ldap_server, get_info=NONE) g_ldap_conn = Connection(server, g_ldap_binddn, g_ldap_bindpw, auto_bind=True, raise_exceptions=True, client_strategy='RESTARTABLE') logging.info("Connected to LDAP-server: " + g_ldap_server) timeout = 600 # Register to have the Milter factory create instances of your class: Milter.factory = LdapAclMilter # Tell the MTA which features we use flags = Milter.ADDHDRS Milter.set_flags(flags)
import time __version__ = '1' logger = logging.getLogger('ldap') try: import ldap3 import ldap3.core.exceptions try: LDAP_AUTH_SIMPLE = ldap3.AUTH_SIMPLE except AttributeError: LDAP_AUTH_SIMPLE = ldap3.SIMPLE try: ldap3.set_config_parameter('DEFAULT_ENCODING', 'UTF-8') except AttributeError: pass except ldap3.core.exceptions.LDAPConfigurationParameterError: pass except ImportError: ldap3 = None pass class LDAPPasswordProvider(object): __version__ = '1' def __init__(self, config, account_handler): self.account_handler = account_handler
# coding=utf-8 # from ldap3 import Server, Connection, RESTARTABLE, set_config_parameter, MODIFY_REPLACE from ldap3.core.exceptions import LDAPInvalidCredentialsResult, LDAPConstraintViolationResult, \ LDAPInsufficientAccessRightsResult # https://ldap3.readthedocs.io/installation.html#global-configuration set_config_parameter('RESTARTABLE_TRIES', 1) class AD(object): def __init__(self, server, admin, admin_pwd, search_base, netbios): self.s = Server(server) self.ss = Server(server, use_ssl=True) self.admin_c = Connection(self.ss, '%s\%s' % (netbios, admin), admin_pwd, auto_bind=True, client_strategy=RESTARTABLE, raise_exceptions=True) self.search_base = search_base self.netbios = netbios def is_auth(self, user, pwd, max_recurse=1): u"""接受用户SamAccountName和密码\n返回(True or False, message)""" if max_recurse < 0: return False, u'该用户下次登陆必须修改密码,设置pwdLastSet=-1失败' try: c = Connection(self.s, '%s\%s' % (self.netbios, user),
# LDAP_CONNECTION_USER = '******' # LDAP_CONNECTION_PASSWD = 'Thatpassword' # LDAP_DB_URL = 'ldap://localhost:389/' LDAP_BASE_DOMAIN = 'testunical.it' # LDAP_PEOPLE_DN = 'dc=proxy' if 'multildap' in INSTALLED_APPS: ##################### # pyMutliLDAP related ##################### import ldap3 from multildap.client import LdapClient # GLOBALS # encoding ldap3.set_config_parameter('DEFAULT_SERVER_ENCODING', 'UTF-8') # some broken LDAP implementation may have different encoding # than those expected by RFCs # ldap3.set_config_paramenter('ADDITIONAL_ENCODINGS', ...) # timeouts ldap3.set_config_parameter('RESTARTABLE_TRIES', 3) ldap3.set_config_parameter('POOLING_LOOP_TIMEOUT', 2) ldap3.set_config_parameter('RESET_AVAILABILITY_TIMEOUT', 2) ldap3.set_config_parameter('RESTARTABLE_SLEEPTIME', 2) # _REWRITE_DN_TO = 'dc=proxy' _RS_ATTRIBUTES = [ 'cn', 'eduPersonPrincipalName', 'eduPersonEntitlement', 'schacHomeOrganizationType', 'schacHomeOrganization', 'mail', 'uid', 'givenName', 'sn', 'eduPersonScopedAffiliation',
import time __version__ = '3' logger = logging.getLogger('ldap') try: import ldap3 import ldap3.core.exceptions try: LDAP_AUTH_SIMPLE = ldap3.AUTH_SIMPLE except AttributeError: LDAP_AUTH_SIMPLE = ldap3.SIMPLE try: ldap3.set_config_parameter('DEFAULT_ENCODING', 'UTF-8') ldap3.set_config_parameter('ADDITIONAL_ENCODINGS', ['cp1251', 'koi8-r', 'latin1']) except AttributeError: pass except ldap3.core.exceptions.LDAPConfigurationParameterError: pass except ImportError: ldap3 = None pass class LDAPPasswordProvider(object): __version__ = '3' def __init__(self, config, account_handler):