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)
Beispiel #2
0
def setupLDAPConnection(servers, bind_dn, bind_pass):
    try:
        pg_state = State()
        args = pg_state.args
    except:
        pg_state = lambda: None
        args = lambda: None
        args.verbose = 0

    if args.verbose:
        print("[*] Creating LDAPPool")
        if args.verbose > 1:
            print(
                "[**] Building LDAPServerPool Object: (servers=None, pool_strategy=ROUND_ROBIN, active=True, exhaust=True)"
            )
    LDAPPool = LDAPServerPool(servers=None,
                              pool_strategy=ROUND_ROBIN,
                              active=True,
                              exhaust=True)
    for dc in servers:
        s = LDAPServer("ldaps://" + dc + ":636", use_ssl=True, get_info=ALL)
        LDAPPool.add(s)
        if args.verbose > 1:
            print(
                "[**] Constructed LDAPServer Object: (%s, use_ssl=True, get_info=ALL) and added to pool"
                % (str("ldaps://" + dc + ":636")))
    if args.verbose > 1: print()
    if args.verbose:
        print("[*] Creating LDAPConnection")
    LDAPConn = LDAPConnection(LDAPPool, bind_dn, bind_pass, auto_bind=True)
    return LDAPConn
Beispiel #3
0
 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 search(self, base, filter, attributes=None):
        if attributes is None:
            attributes = []

        server_pool = ServerPool(None, FIRST)

        for hostname in self.hostnames:
            server = Server(hostname)
            server_pool.add(server)

        conn = Connection(server_pool, user=self.user, password=self.password)
        conn.open()

        if conn.bind() is False:
            raise Exception(f'Unable to bind user to the Perun LDAP {repr(server_pool.get_current_server(conn))}.')

        start_time = milli_time()
        conn.search(base, filter, attributes=attributes)
        end_time = milli_time()

        response = self.get_simplified_entries(conn.entries)
        response_time = end_time - start_time
        logger.debug(
            f'LdapConnector.search - search query proceeded in {response_time} ms. '
            f'Query base: {base}, filter: {filter}, response: {response}.'
        )
        conn.unbind()
        return response
Beispiel #5
0
 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)
Beispiel #6
0
 def test_open_ssl_with_defaults(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_ssl,
                             use_ssl=True)
         connection = Connection(server,
                                 user=test_user,
                                 password=test_password)
         connection.open()
         self.assertFalse(connection.closed)
         connection.unbind()
         if connection.strategy.pooled:
             connection.strategy.terminate()
Beispiel #7
0
 def build_server_pool(self, server_name: str) -> ServerPool:
     server_config = self.ldap_configs[server_name]['server_config']
     """
     Read the server pool docs: https://ldap3.readthedocs.io/en/latest/server.html
     """
     server_pool = ServerPool(None, ROUND_ROBIN, active=True, exhaust=30)
     server_pool.add(Server(self.ldap_configs[server_name]['ldap_host'], **server_config))
     return server_pool
Beispiel #8
0
def get_connection(bind=None,
                   check_names=None,
                   lazy_connection=None,
                   authentication=None,
                   sasl_mechanism=None,
                   sasl_credentials=None,
                   get_info=None):
    if bind is None:
        bind = True
    if check_names is None:
        check_names = test_check_names
    if lazy_connection is None:
        lazy_connection = test_lazy_connection
    if authentication is None:
        authentication = test_authentication
    if get_info is None:
        get_info = test_get_info

    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=get_info,
                              mode=test_server_mode))
    else:
        server = Server(host=test_server,
                        port=test_port,
                        allowed_referral_hosts=('*', True),
                        get_info=get_info,
                        mode=test_server_mode)

    if authentication == SASL:
        return Connection(server,
                          auto_bind=bind,
                          version=3,
                          client_strategy=test_strategy,
                          authentication=SASL,
                          sasl_mechanism=sasl_mechanism,
                          sasl_credentials=sasl_credentials,
                          lazy=lazy_connection,
                          pool_name='pool1',
                          check_names=check_names)
    else:
        return Connection(server,
                          auto_bind=bind,
                          version=3,
                          client_strategy=test_strategy,
                          user=test_user,
                          password=test_password,
                          authentication=authentication,
                          lazy=lazy_connection,
                          pool_name='pool1',
                          check_names=check_names)
Beispiel #9
0
 def __init__(self, prefix, base_dn, use_ssl=True, connect_timeout=5):
     self.ldap = ServerPool(None, FIRST)
     self.prefix = None
     self.bind_dn = None
     self.error_msg = None
     self._use_ssl = use_ssl
     self._connect_timeout = connect_timeout
     self.prefix = prefix
     self.base_dn = base_dn
Beispiel #10
0
class ConnectionProvider:
    def __init__(self, ldap_servers):
        self.serverPool = ServerPool(None, ROUND_ROBIN)
        for ldapServer in ldap_servers:
            self.serverPool.add(Server(ldapServer))

    def connection(self, user_dn, password):
        return Connection(self.serverPool,
                          user_dn,
                          password,
                          read_only=True,
                          lazy=False,
                          raise_exceptions=False)
Beispiel #11
0
 def test_open_ssl_with_defaults(self):
     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)
     connection = Connection(server, user=test_user, password=test_password)
     connection.open()
     self.assertFalse(connection.closed)
     connection.unbind()
     if connection.strategy.pooled:
         connection.strategy.terminate()
Beispiel #12
0
class LdapServer(object):
    def __init__(self, prefix, base_dn, use_ssl=True, connect_timeout=5):
        self.ldap = ServerPool(None, FIRST)
        self.prefix = None
        self.bind_dn = None
        self.error_msg = None
        self._use_ssl = use_ssl
        self._connect_timeout = connect_timeout
        self.prefix = prefix
        self.base_dn = base_dn

    def __repr__(self):
        return "<%s> %s" % (self.__class__.__name__, self.ldap)

    def __str__(self):
        return self.__repr__()

    def add_server(self, host, port, use_ssl=None):
        logger.info("Add server: %s:%d - %s", host, port, use_ssl)
        server = Server(
            host=host,
            port=port,
            use_ssl=self._use_ssl if use_ssl is None else use_ssl,
            connect_timeout=self._connect_timeout,
        )
        self.ldap.add(server)

    def searchfilter(self, uid):
        return f"(sAMAccountName={uid})"

    @classmethod
    def setup(cls, prefix, base_dn, servers):
        ldap_server = cls(prefix=prefix, base_dn=base_dn)
        for server in servers:
            ldap_server.add_server(**server)
        return ldap_server

    def connect(self, username, password, **kwargs):
        ldap_username = f"{self.prefix}\\{username}"
        conn = Connection(self.ldap,
                          user=ldap_username,
                          password=password,
                          raise_exceptions=False,
                          **kwargs)
        if conn.bind() and conn.result["result"] == 0:
            self.error_msg = conn.result
            conn.unbind()
            return conn
        else:
            return None
Beispiel #13
0
 def test_start_tls(self):
     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(validate=ssl.CERT_NONE), get_info=test_get_info, mode=test_server_mode)
     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()
     self.assertFalse(connection.closed)
     connection.unbind()
     if connection.strategy.pooled:
         connection.strategy.terminate()
Beispiel #14
0
 def test_sasl_with_external_certificate(self):
     tls = Tls(local_private_key_file=test_user_key_file, local_certificate_file=test_user_cert_file, validate=ssl.CERT_REQUIRED, version=ssl.PROTOCOL_TLSv1, ca_certs_file=test_ca_cert_file, valid_names=['EDIR-TEST', '2.hyperv', 'labldap02.cloudapp.net', 'WIN1.FOREST.LAB'])
     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, version=3, client_strategy=test_strategy, authentication=SASL, sasl_mechanism='EXTERNAL')
     connection.open()
     connection.bind()
     self.assertTrue(connection.bound)
     connection.unbind()
     if connection.strategy.pooled:
         connection.strategy.terminate()
     self.assertFalse(connection.bound)
Beispiel #15
0
 def test_restartable_invalid_server2(self):
     if test_strategy not in [MOCK_SYNC, MOCK_ASYNC]:
         if isinstance(test_server, (list, tuple)):
             hosts = ['a.b.c.d'] + list(test_server)
         else:
             hosts = ['a.b.c.d', test_server]
         search_results = []
         servers = [
             Server(host=host, port=389, use_ssl=False) for host in hosts
         ]
         server_pool = ServerPool(servers,
                                  ROUND_ROBIN,
                                  active=True,
                                  exhaust=True)
         connection = Connection(server_pool,
                                 user=test_user,
                                 password=test_password,
                                 client_strategy=RESTARTABLE,
                                 lazy=False)
         connection.open()
         connection.bind()
         connection.search(search_base=test_base,
                           search_filter='(' + test_base.split(',')[0] +
                           ')',
                           search_scope=BASE)
         if connection.response:
             for resp in connection.response:
                 if resp['type'] == 'searchResEntry':
                     search_results.append(resp['dn'])
         connection.unbind()
         self.assertEqual(len(search_results), 1)
Beispiel #16
0
    def init_and_get_ldap_user(self, username):
        if username is None or username == '':
            return None, None

        # add LDAP_BIND_PASSWORD as password field
        password_field = 'LDAP_BIND_PWD' if hasattr(settings, 'LDAP_BIND_PWD') else 'LDAP_BIND_PASSWORD'

        # check configuration
        if not (hasattr(settings, 'LDAP_SERVERS') and hasattr(settings, 'LDAP_BIND_USER') and
                hasattr(settings, password_field) and hasattr(settings, 'LDAP_SEARCH_BASE') and
                hasattr(settings, 'LDAP_USER_SEARCH_FILTER') and hasattr(settings, 'LDAP_ATTRIBUTES_MAP')):
            raise ImproperlyConfigured()

        # as first release of the module does not have this parameter, default is to set it true to keep the same
        # comportment after updates.
        if hasattr(settings, 'LDAP_USE_LDAP_GROUPS') and isinstance(settings.LDAP_USE_LDAP_GROUPS, bool):
            LDAP3ADBackend.use_groups = settings.LDAP_USE_LDAP_GROUPS
        else:
            LDAP3ADBackend.use_groups = True

        if LDAP3ADBackend.use_groups and not (hasattr(settings, 'LDAP_GROUPS_SEARCH_FILTER') and
                                              hasattr(settings, 'LDAP_GROUP_MEMBER_ATTRIBUTE') and
                                              hasattr(settings, 'LDAP_GROUPS_MAP')):
            raise ImproperlyConfigured()

        # LDAP_IGNORED_LOCAL_GROUPS is a list of local Django groups that must be kept.
        if (hasattr(settings, 'LDAP_IGNORED_LOCAL_GROUPS') and
                not isinstance(settings.LDAP_IGNORED_LOCAL_GROUPS, list)):
            raise ImproperlyConfigured()

        if hasattr(settings, 'LDAP_AUTHENTICATION'):
            authentication = getattr(settings, 'LDAP_AUTHENTICATION')
        else:
            authentication = SIMPLE

        if hasattr(settings, 'LDAP_SAVE_USER_PWD') and isinstance(settings.LDAP_SAVE_USER_PWD, bool):
            LDAP3ADBackend.save_user_passwords = settings.LDAP_SAVE_USER_PWD

        # first: build server pool from settings
        if LDAP3ADBackend.pool is None:
            LDAP3ADBackend.pool = ServerPool(None, pool_strategy=FIRST, active=True)
            for srv in settings.LDAP_SERVERS:
                server = Server(srv['host'], srv['port'], srv['use_ssl'])
                LDAP3ADBackend.pool.add(server)

        # then, try to connect with user/pass from settings
        con = Connection(LDAP3ADBackend.pool, auto_bind=True, client_strategy=SYNC, user=settings.LDAP_BIND_USER,
                         password=getattr(settings, password_field) or settings.LDAP_BIND_PASSWORD,
                         authentication=authentication, check_names=True)

        # search for the desired user
        user_dn = None
        user_attribs = None
        con.search(settings.LDAP_SEARCH_BASE, settings.LDAP_USER_SEARCH_FILTER.replace('%s', '{0}').format(username),
                   attributes=list(settings.LDAP_ATTRIBUTES_MAP.values()))
        if con.result['result'] == 0 and len(con.response) > 0 and 'dn' in con.response[0].keys():
            user_dn = con.response[0]['dn']
            user_attribs = con.response[0]['attributes']
        con.unbind()
        return user_dn, user_attribs
Beispiel #17
0
    def test_restartable_invalid_server(self):
        if test_strategy not in [MOCK_SYNC, MOCK_ASYNC]:
            if isinstance(test_server, (list, tuple)):
                hosts = ['a.b.c.d'] + list(test_server)
            else:
                hosts = ['a.b.c.d', test_server]
            search_results = []
            servers = [
                Server(host=host,
                       port=636,
                       use_ssl=True,
                       get_info=test_get_info,
                       mode=test_server_mode) for host in hosts
            ]
            connection = Connection(ServerPool(servers,
                                               ROUND_ROBIN,
                                               active=True,
                                               exhaust=True),
                                    user=test_user,
                                    password=test_password,
                                    client_strategy=RESTARTABLE,
                                    lazy=test_lazy_connection,
                                    pool_name='pool1')

            with connection as c:
                c.search(search_base=test_base,
                         search_filter='(' + test_base.split(',')[0] + ')',
                         search_scope=BASE,
                         attributes='*')

                for resp in connection.response:
                    if resp['type'] == 'searchResEntry':
                        search_results.append(resp['dn'])
            self.assertEqual(len(search_results), 1)
def get_ldap_connection(server=[],
                        port='',
                        ssl=False,
                        timeout=0,
                        binddn='',
                        bindpasswd=''):
    try:
        server_pool = ServerPool([
            Server(item, port, use_ssl=ssl, connect_timeout=3)
            for item in server
        ],
                                 FIRST,
                                 active=3,
                                 exhaust=60)
        conn = Connection(server_pool,
                          auto_bind=AUTO_BIND_NO_TLS,
                          read_only=True,
                          receive_timeout=timeout,
                          check_names=True,
                          user=binddn,
                          password=bindpasswd)
    except Exception as exc:
        print('ldap_csv_exporter LDAP bind error {}({})'.format(
            type(exc).__name__, exc))
        return False
    else:
        return conn
Beispiel #19
0
 def getUserInfo(username):
     userInfo = None
     try:
         ldap_server_pool = ServerPool(AdAuthenticate.LDAP_SERVER_POOL)
         conn = Connection(ldap_server_pool,
                           user=AdAuthenticate.ADMIN_DN,
                           password=AdAuthenticate.ADMIN_PASSWORD,
                           check_names=True,
                           lazy=False,
                           raise_exceptions=False)
         conn.open()
         conn.bind()
         res = conn.search(
             search_base=AdAuthenticate.SEARCH_BASE,
             search_filter='(samaccountname={})'.format(username),
             search_scope=SUBTREE,
             attributes=["displayName", "cn", "sn", "mail", "description"],
             paged_size=5)
         if res:
             entry = conn.response[0]
             attr_dict = entry['attributes']
             userInfo = {
                 'dn': entry['dn'],
                 'cn': attr_dict['cn'],
                 'sn': attr_dict['sn'],
                 'mail': attr_dict['mail'],
                 'displayName': attr_dict['displayName'],
                 'description': attr_dict['description'],
             }
     except Exception as e:
         logging.error(e)
     finally:
         if conn:
             conn.unbind()
     return userInfo
Beispiel #20
0
 def test_sasl_with_external_certificate(self):
     tls = Tls(local_private_key_file=test_user_key_file, local_certificate_file=test_user_cert_file, validate=ssl.CERT_REQUIRED, version=ssl.PROTOCOL_TLSv1, ca_certs_file=test_ca_cert_file, valid_names=test_valid_names)
     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_ssl, use_ssl=True, tls=tls, 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, version=3, client_strategy=test_strategy, authentication=SASL, sasl_mechanism='EXTERNAL')
     connection.open()
     connection.bind()
     self.assertTrue(connection.bound)
     connection.unbind()
     if connection.strategy.pooled:
         connection.strategy.terminate()
     self.assertFalse(connection.bound)
Beispiel #21
0
 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(read_server_info=False)
         connection.start_tls(read_server_info=False)
         connection.bind()
         self.assertTrue(connection.bound)
         connection.unbind()
         if connection.strategy.pooled:
             connection.strategy.terminate()
         self.assertFalse(connection.bound)
Beispiel #22
0
 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)
Beispiel #23
0
def ldap_auth(username, password):
    ldap_server_pool = ServerPool(LDAP_SERVER_POOL)
    conn = Connection(ldap_server_pool,
                      user=ADMIN_DN,
                      password=ADMIN_PASSWORD,
                      check_names=True,
                      lazy=False,
                      raise_exceptions=False)
    conn.open()
    r = conn.bind()
    print('bind:', r)

    # 默认uid,但是未必能匹配到,可尝试:sAMAccountName
    res = conn.search(
        search_base=SEARCH_BASE,
        search_filter='(sAMAccountName={})'.format(username),
        search_scope=SUBTREE,
        #attributes = ['cn', 'givenName', 'mail', 'sAMAccountName'],
        #ALL_ATTRIBUTES:获取所有属性值
        attributes=ALL_ATTRIBUTES,
        paged_size=5)
    print('res: ', res)

    if res:
        entry = conn.response[0]
        # print(entry)
        dn = entry['dn']
        attr_dict = entry['attributes']

        # check password by dn
        try:
            conn2 = Connection(ldap_server_pool,
                               user=dn,
                               password=password,
                               check_names=True,
                               lazy=False,
                               raise_exceptions=False)
            conn2.bind()
            if conn2.result["description"] == "success":
                print(attr_dict)
                #根据打印出的实际信息,可知道所需要的映射的字段名
                print((True, attr_dict["sAMAccountName"], password,
                       attr_dict["mail"], attr_dict["cn"],
                       attr_dict["department"], attr_dict["givenName"]))
                return (True, attr_dict["sAMAccountName"], password,
                        attr_dict["mail"], attr_dict["cn"],
                        attr_dict["department"], attr_dict["givenName"])
            else:
                print("auth fail")
                return (False, None, None, None)
        except Exception as e:
            print("auth fail")
            return (False, None, None, None)
    else:
        return (False, None, None, None)
    def test_start_tls_with_cipher(self):
        # ciphers = None
        # ciphers = '!aNULL:!eNULL:!LOW:!EXPORT:!SSLv2'
        ciphers = 'HIGH:!aNULL:!RC4:!DSS'

        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(validate=ssl.CERT_NONE, ciphers=ciphers), get_info=test_get_info, mode=test_server_mode)
            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()
            self.assertFalse(connection.closed)
            # self.assertEqual(connection.socket.cipher(), ciphers)
            connection.unbind()
            if connection.strategy.pooled:
                connection.strategy.terminate()
Beispiel #25
0
 def test_bind_ssl_with_certificate(self):
     tls = Tls(local_private_key_file=test_user_key_file,
               local_certificate_file=test_user_cert_file,
               validate=ssl.CERT_REQUIRED,
               version=ssl.PROTOCOL_TLSv1,
               ca_certs_file=test_ca_cert_file,
               valid_names=['EDIR-TEST', 'WIN1.FOREST.LAB', 'sles11sp3-template.hyperv', '192.168.137.101'])
     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)
Beispiel #26
0
	def connectToServer(self):
		# set environment variables for kerberos operations
		os.environ['KRB5CCNAME'] = self.cfgCredCacheFile
		os.environ['KRB5_CLIENT_KTNAME'] = self.cfgClientKeytabFile

		# connect to server with kerberos ticket
		serverArray = []
		for server in self.cfgServer:
			serverArray.append(Server(server['address'], port=server['port'], use_ssl=server['ssl'], get_info=ALL))
		self.server = ServerPool(serverArray, ROUND_ROBIN, active=True, exhaust=True)
		self.connection = Connection(self.server, authentication=SASL, sasl_mechanism=KERBEROS, auto_bind=True)
		print('Connected as: '+str(self.connection.server)+' '+self.connection.extend.standard.who_am_i()+'@'+self.cfgDomain)
Beispiel #27
0
    def __init__(self, app):
        ldap_servers = app.config['LDAP_SERVERS']
        ldap_port = app.config['LDAP_PORT']
        use_ssl = app.config['USE_SSL']

        ldap_pool = []
        for server in ldap_servers:
            ldap_pool.append(Server(server, ldap_port, use_ssl))

        self.username = app.config['LDAP_SERVICE_USER']
        self.password = app.config['LDAP_SERVICE_PASS']
        self.server_pool = ServerPool(ldap_pool, ROUND_ROBIN, active=False)
Beispiel #28
0
 def ldap_validate(username, password):
     """
     实现LDAP用户登录验证
     """
     ldap_host = app.config['LDAP_HOST']
     ldap_port = app.config['LDAP_PORT']
     manager_dn = app.config['MANAGER_DN']
     manager_password = app.config['MANAGER_PASSWORD']
     search_base = app.config['SEARCH_BASE']
     ldap_server = Server(ldap_host, port=int(ldap_port))
     ldap_server_pool = ServerPool([
         ldap_server,
     ])
     conn = Connection(ldap_server_pool,
                       user=manager_dn,
                       password=manager_password,
                       check_names=True,
                       lazy=False,
                       raise_exceptions=False,
                       receive_timeout=3)
     conn.open()
     conn.bind()
     res = conn.search(
         search_base=search_base,
         search_filter='(sAMAccountName={})'.format(username),
         search_scope=SUBTREE,
         attributes=[
             'cn', 'mail', 'sAMAccountName', 'department', 'manager'
         ],  # ALL_ATTRIBUTES,获取所有属性值
         paged_size=5)
     if res:
         entry = conn.response[0]
         dn = entry['dn']
         attr_dict = entry['attributes']
         try:
             # check password by dn
             conn2 = Connection(ldap_server_pool,
                                user=dn,
                                password=password,
                                check_names=True,
                                lazy=False,
                                raise_exceptions=False)
             conn2.bind()
             if conn2.result["description"] == "success":
                 return True, attr_dict
             else:
                 return False, attr_dict
         except Exception:
             return False, attr_dict
     else:
         app.logger.error("LDAP Error! user attributes is None.")
         return False, None
Beispiel #29
0
 def test_bind_ssl_with_certificate(self):
     if test_strategy not in [MOCK_SYNC, MOCK_ASYNC]:
         tls = Tls(local_private_key_file=test_user_key_file,
                   local_certificate_file=test_user_cert_file,
                   validate=ssl.CERT_REQUIRED,
                   version=ssl.PROTOCOL_TLSv1,
                   ca_certs_file=test_ca_cert_file,
                   valid_names=test_valid_names)
         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)
Beispiel #30
0
 def server(self) -> Server:
     """Get LDAP Server/ServerPool"""
     servers = []
     tls = Tls()
     if self.peer_certificate:
         tls = Tls(ca_certs_data=self.peer_certificate.certificate_data, validate=CERT_REQUIRED)
     kwargs = {
         "get_info": ALL,
         "connect_timeout": LDAP_TIMEOUT,
         "tls": tls,
     }
     if "," in self.server_uri:
         for server in self.server_uri.split(","):
             servers.append(Server(server, **kwargs))
     else:
         servers = [Server(self.server_uri, **kwargs)]
     return ServerPool(servers, RANDOM, active=True, exhaust=True)
Beispiel #31
0
def ldap_auth(username, password):
    ldap_server_pool = ServerPool(LDAP_SERVER_POOL)
    conn = Connection(ldap_server_pool,
                      user=ADMIN_DN,
                      password=ADMIN_PASSWORD,
                      check_names=True,
                      lazy=False,
                      raise_exceptions=False)
    conn.open()
    conn.bind()

    res = conn.search(search_base=SEARCH_BASE,
                      search_filter='(sAMAccountName={})'.format(username),
                      search_scope=SUBTREE,
                      attributes=['cn', 'givenName', 'mail', 'sAMAccountName'],
                      paged_size=5)

    if res:
        entry = conn.response[0]
        dn = entry['dn']
        attr_dict = entry['attributes']

        # check password by dn
        try:
            conn2 = Connection(ldap_server_pool,
                               user=dn,
                               password=password,
                               check_names=True,
                               lazy=False,
                               raise_exceptions=False)
            conn2.bind()
            if conn2.result["description"] == "success":
                print((True, attr_dict["mail"], attr_dict["sAMAccountName"],
                       attr_dict["givenName"]))
                return (True, attr_dict["mail"], attr_dict["sAMAccountName"],
                        attr_dict["givenName"])
            else:
                print("auth fail")
                return (False, None, None, None)
        except Exception as e:
            print("auth fail")
            return (False, None, None, None)
    else:
        return (False, None, None, None)
Beispiel #32
0
def authenticate(username=None, password=None, db=None, **kwargs):
    server_pool = ServerPool(SERVER_POOL)
    conn = Connection(server_pool,
                      user='******'.format(username),
                      password=password,
                      check_names=True,
                      lazy=False,
                      raise_exceptions=False)
    conn.open()
    if conn.bind():
        res = conn.search(search_base=SEARCH_BASE,
                          search_filter='(cn={})'.format(username),
                          search_scope=SUBTREE,
                          attributes=[
                              'cn', 'givenName', 'sn', 'mail',
                              'telephoneNumber', 'otherTelephone',
                              'displayName', 'division', 'department',
                              'employeeNumber', 'extensionAttribute13',
                              'memberOf', 'thumbnailPhoto'
                          ])
        if res:
            attr_dict = conn.response[0]['attributes']
            user = db.query(User).filter_by(username=attr_dict['cn']).first()
            if not user:
                user = User(username=attr_dict['cn'])
                db.add(user)
            user.avatar = base64.b64encode(
                attr_dict['thumbnailPhoto']
                if attr_dict['thumbnailPhoto'] else b'').decode()
            user.password = password
            for group_dn in attr_dict['memberOf']:
                r = re.match('CN=(.*?),OU', group_dn)
                if r:
                    group_name = r.group(1)
                    group = db.query(Group).filter_by(
                        group_name=group_name).first()
                    if not group:
                        group = Group(group_name=group_name)
                        db.add(group)
                    group.users.append(user)
            db.commit()
            return user
Beispiel #33
0
    def post(self, request, *args, **kwargs):
        '''
        接收ajax数据实现用户验证
        :param request:
        :param args:
        :param kwargs:
        :return: response.data
        '''
        response = BaseResponse()

        username = request.POST.get('username')
        pwd = request.POST.get('pwd').strip()
        pwd2 = parse.quote(pwd)
        usr_obj = models.SlbUser.objects.filter(name=username).all().first()
        if not usr_obj:
            response.data = '{"code":"没有权限"}'
            return HttpResponse(response.data)
        else:
            try:
                ldap_server_pool = ServerPool(["10.126.10.4", "10.126.11.150"])
                conn = Connection(ldap_server_pool,
                                  user=username + '@lly.com',
                                  password=pwd,
                                  check_names=True,
                                  lazy=False,
                                  raise_exceptions=False)
                conn.open()
                conn.bind()
                print(conn.result)
                if username is not None and conn.result[
                        "description"] == "success":
                    request.session['user_name'] = username
                    response.data = '{"code": "200"}'
                else:
                    response.data = '{"code": "认证失败"}'
            except Exception as e:
                response.data = str(e)
                pass
        return HttpResponse(response.data)
Beispiel #34
0
 def authenricate(username, password):
     bool = False
     try:
         if username and password:
             userInfo = AdAuthenticate.getUserInfo(username)
             if userInfo and userInfo.get("dn", None):
                 ldap_server_pool = ServerPool(
                     AdAuthenticate.LDAP_SERVER_POOL)
                 conn = Connection(ldap_server_pool,
                                   user=userInfo['dn'],
                                   password=password,
                                   check_names=True,
                                   lazy=False,
                                   raise_exceptions=False)
                 conn.bind()
                 if conn.result["description"] == "success":
                     bool = True
     except Exception as e:
         logging.error(e)
     finally:
         if conn:
             conn.unbind()
     return bool
Beispiel #35
0
 def bind(self, ad_username, ad_password):
     """
     Function that can be called to bind to a list of domain controllers as a pool
     """
     logger.debug("Trying to connect to domain controllers: {}".format(
         self.domain_controllers))
     server_pool_list = []
     for dc in self.domain_controllers:
         server_pool_list.append(
             Server(host=dc,
                    get_info=ALL,
                    port=636,
                    use_ssl=True,
                    connect_timeout=120))
     server_pool = ServerPool(server_pool_list,
                              FIRST,
                              active=True,
                              exhaust=120)
     try:
         self.conn = Connection(server_pool,
                                auto_bind=True,
                                user=ad_username,
                                password=ad_password,
                                raise_exceptions=True)
         self.conn.bind()
     except LDAPTimeLimitExceededResult as e:
         logger.critical(
             "Unable to establish a connection with the LDAP server, timed out after 60 seconds"
         )
         exit(1)
     except Exception as e:
         logger.critical(
             "Unable to create an LDAP connection to provision users in Active Directory. The error was: {}"
             .format(str(e)))
         raise
         exit(1)
Beispiel #36
0
def get_connection(bind=None,
                   use_ssl=None,
                   check_names=None,
                   lazy_connection=None,
                   authentication=None,
                   sasl_mechanism=None,
                   sasl_credentials=None,
                   ntlm_credentials=(None, None),
                   get_info=None,
                   usage=None,
                   fast_decoder=None,
                   simple_credentials=(None, None),
                   receive_timeout=None):
    if bind is None:
        bind = True
    if check_names is None:
        check_names = test_check_names
    if lazy_connection is None:
        lazy_connection = test_lazy_connection
    if authentication is None:
        authentication = test_authentication
    if get_info is None:
        get_info = test_get_info
    if usage is None:
        usage = test_usage
    if fast_decoder is None:
        fast_decoder = test_fast_decoder
    if receive_timeout is None:
        receive_timeout = test_receive_timeout
    if test_server_type == 'AD' and use_ssl is None:
        use_ssl = True  # Active directory forbids Add operations in cleartext

    if test_strategy not in [MOCK_SYNC, MOCK_ASYNC]:
        # define real server
        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,
                                  use_ssl=use_ssl,
                                  port=test_port_ssl if use_ssl else test_port,
                                  allowed_referral_hosts=('*', True),
                                  get_info=get_info,
                                  mode=test_server_mode))
        else:
            server = Server(host=test_server,
                            use_ssl=use_ssl,
                            port=test_port_ssl if use_ssl else test_port,
                            allowed_referral_hosts=('*', True),
                            get_info=get_info,
                            mode=test_server_mode)
    else:
        if test_server_type == 'EDIR':
            schema = SchemaInfo.from_json(edir_8_8_8_schema)
            info = DsaInfo.from_json(edir_8_8_8_dsa_info, schema)
            server = Server.from_definition('MockSyncServer', info, schema)
        elif test_server_type == 'AD':
            schema = SchemaInfo.from_json(ad_2012_r2_schema)
            info = DsaInfo.from_json(ad_2012_r2_dsa_info, schema)
            server = Server.from_definition('MockSyncServer', info, schema)
        elif test_server_type == 'SLAPD':
            schema = SchemaInfo.from_json(slapd_2_4_schema)
            info = DsaInfo.from_json(slapd_2_4_dsa_info, schema)
            server = Server.from_definition('MockSyncServer', info, schema)

    if authentication == SASL:
        connection = Connection(server,
                                auto_bind=bind,
                                version=3,
                                client_strategy=test_strategy,
                                authentication=SASL,
                                sasl_mechanism=sasl_mechanism,
                                sasl_credentials=sasl_credentials,
                                lazy=lazy_connection,
                                pool_name='pool1',
                                check_names=check_names,
                                collect_usage=usage,
                                fast_decoder=fast_decoder,
                                receive_timeout=receive_timeout)
    elif authentication == NTLM:
        connection = Connection(server,
                                auto_bind=bind,
                                version=3,
                                client_strategy=test_strategy,
                                user=ntlm_credentials[0],
                                password=ntlm_credentials[1],
                                authentication=NTLM,
                                lazy=lazy_connection,
                                pool_name='pool1',
                                check_names=check_names,
                                collect_usage=usage,
                                fast_decoder=fast_decoder,
                                receive_timeout=receive_timeout)
    elif authentication == ANONYMOUS:
        connection = Connection(server,
                                auto_bind=bind,
                                version=3,
                                client_strategy=test_strategy,
                                user=None,
                                password=None,
                                authentication=ANONYMOUS,
                                lazy=lazy_connection,
                                pool_name='pool1',
                                check_names=check_names,
                                collect_usage=usage,
                                fast_decoder=fast_decoder,
                                receive_timeout=receive_timeout)
    else:
        connection = Connection(server,
                                auto_bind=bind,
                                version=3,
                                client_strategy=test_strategy,
                                user=simple_credentials[0] or test_user,
                                password=simple_credentials[1] or test_password,
                                authentication=authentication,
                                lazy=lazy_connection,
                                pool_name='pool1',
                                check_names=check_names,
                                collect_usage=usage,
                                fast_decoder=fast_decoder,
                                receive_timeout=receive_timeout)

    if test_strategy in [MOCK_SYNC, MOCK_ASYNC]:
        # create authentication identities for testing mock strategies
        connection.strategy.add_entry(test_user, {'objectClass': 'inetOrgPerson', 'userPassword': test_password})
        connection.strategy.add_entry(test_secondary_user, {'objectClass': 'inetOrgPerson', 'userPassword': test_secondary_password})
        connection.strategy.add_entry(test_sasl_user_dn, {'objectClass': 'inetOrgPerson', 'userPassword': test_sasl_password})
        connection.strategy.add_entry(test_sasl_secondary_user_dn, {'objectClass': 'inetOrgPerson', 'userPassword': test_sasl_secondary_password})
        # connection.strategy.add_entry(test_ntlm_user, {'objectClass': 'inetOrgPerson', 'userPassword': test_ntlm_password})
        if bind:
            connection.bind()

    return connection
Beispiel #37
0
def get_connection(bind=None,
                   use_ssl=None,
                   check_names=None,
                   lazy_connection=None,
                   authentication=None,
                   sasl_mechanism=None,
                   sasl_credentials=None,
                   ntlm_credentials=(None, None),
                   get_info=None,
                   usage=None,
                   fast_decoder=None,
                   simple_credentials=(None, None),
                   receive_timeout=None):
    if bind is None:
        bind = True
    if check_names is None:
        check_names = test_check_names
    if lazy_connection is None:
        lazy_connection = test_lazy_connection
    if authentication is None:
        authentication = test_authentication
    if get_info is None:
        get_info = test_get_info
    if usage is None:
        usage = test_usage
    if fast_decoder is None:
        fast_decoder = test_fast_decoder
    if receive_timeout is None:
        receive_timeout = test_receive_timeout
    if test_server_type == 'AD' and use_ssl is None:
        use_ssl = True  # Active directory forbids Add operations in cleartext

    if test_strategy not in [MOCK_SYNC, MOCK_ASYNC]:
        # define real server
        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,
                                  use_ssl=use_ssl,
                                  port=test_port_ssl if use_ssl else test_port,
                                  allowed_referral_hosts=('*', True),
                                  get_info=get_info,
                                  mode=test_server_mode))
        else:
            server = Server(host=test_server,
                            use_ssl=use_ssl,
                            port=test_port_ssl if use_ssl else test_port,
                            allowed_referral_hosts=('*', True),
                            get_info=get_info,
                            mode=test_server_mode)
    else:
        if test_server_type == 'EDIR':
            schema = SchemaInfo.from_json(edir_8_8_8_schema)
            info = DsaInfo.from_json(edir_8_8_8_dsa_info, schema)
            server = Server.from_definition('MockSyncServer', info, schema)
        elif test_server_type == 'AD':
            schema = SchemaInfo.from_json(ad_2012_r2_schema)
            info = DsaInfo.from_json(ad_2012_r2_dsa_info, schema)
            server = Server.from_definition('MockSyncServer', info, schema)
        elif test_server_type == 'SLAPD':
            schema = SchemaInfo.from_json(slapd_2_4_schema)
            info = DsaInfo.from_json(slapd_2_4_dsa_info, schema)
            server = Server.from_definition('MockSyncServer', info, schema)

    if authentication == SASL:
        connection = Connection(server,
                                auto_bind=bind,
                                version=3,
                                client_strategy=test_strategy,
                                authentication=SASL,
                                sasl_mechanism=sasl_mechanism,
                                sasl_credentials=sasl_credentials,
                                lazy=lazy_connection,
                                pool_name='pool1',
                                check_names=check_names,
                                collect_usage=usage,
                                fast_decoder=fast_decoder,
                                receive_timeout=receive_timeout)
    elif authentication == NTLM:
        connection = Connection(server,
                                auto_bind=bind,
                                version=3,
                                client_strategy=test_strategy,
                                user=ntlm_credentials[0],
                                password=ntlm_credentials[1],
                                authentication=NTLM,
                                lazy=lazy_connection,
                                pool_name='pool1',
                                check_names=check_names,
                                collect_usage=usage,
                                fast_decoder=fast_decoder,
                                receive_timeout=receive_timeout)
    elif authentication == ANONYMOUS:
        connection = Connection(server,
                                auto_bind=bind,
                                version=3,
                                client_strategy=test_strategy,
                                user=None,
                                password=None,
                                authentication=ANONYMOUS,
                                lazy=lazy_connection,
                                pool_name='pool1',
                                check_names=check_names,
                                collect_usage=usage,
                                fast_decoder=fast_decoder,
                                receive_timeout=receive_timeout)
    else:
        connection = Connection(server,
                                auto_bind=bind,
                                version=3,
                                client_strategy=test_strategy,
                                user=simple_credentials[0] or test_user,
                                password=simple_credentials[1] or test_password,
                                authentication=authentication,
                                lazy=lazy_connection,
                                pool_name='pool1',
                                check_names=check_names,
                                collect_usage=usage,
                                fast_decoder=fast_decoder,
                                receive_timeout=receive_timeout)

    if test_strategy in [MOCK_SYNC, MOCK_ASYNC]:
        # create authentication identities for testing mock strategies
        connection.strategy.add_entry(test_user, {'objectClass': 'inetOrgPerson', 'userPassword': test_password})
        connection.strategy.add_entry(test_secondary_user, {'objectClass': 'inetOrgPerson', 'userPassword': test_secondary_password})
        connection.strategy.add_entry(test_sasl_user_dn, {'objectClass': 'inetOrgPerson', 'userPassword': test_sasl_password})
        connection.strategy.add_entry(test_sasl_secondary_user_dn, {'objectClass': 'inetOrgPerson', 'userPassword': test_sasl_secondary_password})
        # connection.strategy.add_entry(test_ntlm_user, {'objectClass': 'inetOrgPerson', 'userPassword': test_ntlm_password})
        if bind:
            connection.bind()

    return connection
Beispiel #38
0
def get_connection(bind=None,
                   check_names=None,
                   lazy_connection=None,
                   authentication=None,
                   sasl_mechanism=None,
                   sasl_credentials=None,
                   ntlm_credentials=None,
                   get_info=None,
                   usage=None):
    if bind is None:
        if test_server_type == 'AD':
            bind = AUTO_BIND_TLS_BEFORE_BIND
        else:
            bind = True
    if check_names is None:
        check_names = test_check_names
    if lazy_connection is None:
        lazy_connection = test_lazy_connection
    if authentication is None:
        authentication = test_authentication
    if get_info is None:
        get_info = test_get_info
    if usage is None:
        usage = test_usage

    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=get_info,
                              mode=test_server_mode))
    else:
        server = Server(host=test_server,
                        port=test_port,
                        allowed_referral_hosts=('*', True),
                        get_info=get_info,
                        mode=test_server_mode)

    if authentication == SASL:
        return Connection(server,
                          auto_bind=bind,
                          version=3,
                          client_strategy=test_strategy,
                          authentication=SASL,
                          sasl_mechanism=sasl_mechanism,
                          sasl_credentials=sasl_credentials,
                          lazy=lazy_connection,
                          pool_name='pool1',
                          check_names=check_names,
                          collect_usage=usage)
    elif authentication == NTLM:
        return Connection(server,
                          auto_bind=bind,
                          version=3,
                          client_strategy=test_strategy,
                          user=ntlm_credentials[0],
                          password=ntlm_credentials[1],
                          authentication=NTLM,
                          lazy=lazy_connection,
                          pool_name='pool1',
                          check_names=check_names,
                          collect_usage=usage)
    else:
        return Connection(server,
                          auto_bind=bind,
                          version=3,
                          client_strategy=test_strategy,
                          user=test_user,
                          password=test_password,
                          authentication=authentication,
                          lazy=lazy_connection,
                          pool_name='pool1',
                          check_names=check_names,
                          collect_usage=usage)
Beispiel #39
0
def get_connection(bind=None,
                   use_ssl=None,
                   check_names=None,
                   lazy_connection=None,
                   authentication=None,
                   sasl_mechanism=None,
                   sasl_credentials=None,
                   ntlm_credentials=(None, None),
                   get_info=None,
                   usage=None,
                   fast_decoder=None,
                   simple_credentials=(None, None),
                   receive_timeout=None):
    if bind is None:
        bind = True
    if check_names is None:
        check_names = test_check_names
    if lazy_connection is None:
        lazy_connection = test_lazy_connection
    if authentication is None:
        authentication = test_authentication
    if get_info is None:
        get_info = test_get_info
    if usage is None:
        usage = test_usage
    if fast_decoder is None:
        fast_decoder = test_fast_decoder
    if receive_timeout is None:
        receive_timeout = test_receive_timeout
    if test_server_type == 'AD' and use_ssl is None:
        use_ssl = True  # Active directory forbids Add operations in cleartext
    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,
                              use_ssl=use_ssl,
                              port=test_port_ssl if use_ssl else test_port,
                              allowed_referral_hosts=('*', True),
                              get_info=get_info,
                              mode=test_server_mode))
    else:
        server = Server(host=test_server,
                        use_ssl=use_ssl,
                        port=test_port_ssl if use_ssl else test_port,
                        allowed_referral_hosts=('*', True),
                        get_info=get_info,
                        mode=test_server_mode)

    if authentication == SASL:
        return Connection(server,
                          auto_bind=bind,
                          version=3,
                          client_strategy=test_strategy,
                          authentication=SASL,
                          sasl_mechanism=sasl_mechanism,
                          sasl_credentials=sasl_credentials,
                          lazy=lazy_connection,
                          pool_name='pool1',
                          check_names=check_names,
                          collect_usage=usage,
                          fast_decoder=fast_decoder,
                          receive_timeout=receive_timeout)
    elif authentication == NTLM:
        return Connection(server,
                          auto_bind=bind,
                          version=3,
                          client_strategy=test_strategy,
                          user=ntlm_credentials[0],
                          password=ntlm_credentials[1],
                          authentication=NTLM,
                          lazy=lazy_connection,
                          pool_name='pool1',
                          check_names=check_names,
                          collect_usage=usage,
                          fast_decoder=fast_decoder,
                          receive_timeout=receive_timeout)
    elif authentication == ANONYMOUS:
        return Connection(server,
                          auto_bind=bind,
                          version=3,
                          client_strategy=test_strategy,
                          user=None,
                          password=None,
                          authentication=ANONYMOUS,
                          lazy=lazy_connection,
                          pool_name='pool1',
                          check_names=check_names,
                          collect_usage=usage,
                          fast_decoder=fast_decoder,
                          receive_timeout=receive_timeout)
    else:
        return Connection(server,
                          auto_bind=bind,
                          version=3,
                          client_strategy=test_strategy,
                          user=simple_credentials[0] or test_user,
                          password=simple_credentials[1] or test_password,
                          authentication=authentication,
                          lazy=lazy_connection,
                          pool_name='pool1',
                          check_names=check_names,
                          collect_usage=usage,
                          fast_decoder=fast_decoder,
                          receive_timeout=receive_timeout)