Python ldap3.Tls() Examples

The following are 10 code examples of ldap3.Tls(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ldap3 , or try the search function .
Example #1
Source File: test_ldap3_login.py    From flask-ldap3-login with MIT License 7 votes vote down vote up
def test_server_with_tls_with_ssl(self):
        """
        Ensures a server is created/added to the pool, however that the server
        was instantiated with `tls=<TLS CTX OBJECT>` and use_ssl=True.
        """
        fake_tls_ctx = Tls()

        ldap3_manager = ldap3_login.LDAP3LoginManager()
        self.app.config.update(AddServerTestCase.DEFAULT_CONFIG)
        ldap3_manager.init_app(self.app)
        ldap3_manager.add_server(
            "ad2.mydomain.com", 389, use_ssl=True, tls_ctx=fake_tls_ctx, app=self.app
        )

        self.assertEqual(len(self.app.ldap3_login_manager_server_pool.servers), 1)

        server = self.app.ldap3_login_manager_server_pool.servers[-1]
        self.assertEqual(server.tls, fake_tls_ctx)
        self.assertTrue(server.use_ssl) 
Example #2
Source File: __init__.py    From flask-ldap3-login with MIT License 6 votes vote down vote up
def add_server(self, hostname, port, use_ssl, tls_ctx=None, app=None):
        """
        Add an additional server to the server pool and return the
        freshly created server.

        Args:
            hostname (str): Hostname of the server
            port (int): Port of the server
            use_ssl (bool): True if SSL is to be used when connecting.
            tls_ctx (ldap3.Tls): An optional TLS context object to use
                when connecting.
            app (flask.Flask): The app on which to add the server. If not
                given, ``flask.current_app`` is used.

        Returns:
            ldap3.Server: The freshly created server object.
        """
        if app is None:
            app = current_app._get_current_object()
        if not use_ssl and tls_ctx:
            raise ValueError("Cannot specify a TLS context and not use SSL!")
        server = ldap3.Server(hostname, port=port, use_ssl=use_ssl, tls=tls_ctx)
        app.ldap3_login_manager_server_pool.add(server)
        return server 
Example #3
Source File: Active_Directory_Query.py    From content with MIT License 6 votes vote down vote up
def initialize_server(host, port, secure_connection, unsecure):
    """
    uses the instance configuration to initialize the LDAP server

    :param host: host or ip
    :type host: string
    :param port: port or None
    :type port: number
    :param secure_connection: SSL or None
    :type secure_connection: string
    :param unsecure: trust any cert
    :type unsecure: boolean
    :return: ldap3 Server
    :rtype: Server
    """

    if secure_connection == "SSL":
        # intialize server with ssl
        # port is configured by default as 389 or as 636 for LDAPS if not specified in configuration
        demisto.debug("initializing sever with ssl (unsecure: {}). port: {}". format(unsecure, port or 'default(636)'))
        if not unsecure:
            demisto.debug("will require server certificate.")
            tls = Tls(validate=ssl.CERT_REQUIRED, ca_certs_file=os.environ.get('SSL_CERT_FILE'))
            if port:
                return Server(host, port=port, use_ssl=True, tls=tls)
            return Server(host, use_ssl=True, tls=tls)
        if port:
            return Server(host, port=port, use_ssl=True)
        return Server(host, use_ssl=True)
    demisto.debug("initializing server without secure connection. port: {}". format(port or 'default(389)'))
    if port:
        return Server(host, port=port)
    return Server(host) 
Example #4
Source File: backends.py    From django_auth_ldap3 with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self):
        tls_config = None

        if settings.TLS:
            tls_opts = {
                'validate': ssl.CERT_REQUIRED if settings.TLS_VALIDATE else ssl.CERT_NONE
            }

            if settings.TLS_CA_CERTS:
                tls_opts['ca_certs_file'] = settings.TLS_CA_CERTS

            if settings.TLS_PRIVATE_KEY:
                tls_opts['local_private_key_file'] = settings.TLS_PRIVATE_KEY

            if settings.TLS_LOCAL_CERT:
                tls_opts['local_certificate_file'] = settings.TLS_LOCAL_CERT

            tls_config = ldap3.Tls(**tls_opts)

        self.backend = ldap3.Server(settings.URI, use_ssl=settings.TLS, tls=tls_config) 
Example #5
Source File: ad_users.py    From django_auth_ldap3_ad with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #6
Source File: models.py    From realms-wiki with GNU General Public License v2.0 5 votes vote down vote up
def setup_tls_options(self):
        if self.config['START_TLS'] or self.config['URI'].startswith('ldaps://'):
            # noinspection PyUnresolvedReferences
            self.tls = ldap3.Tls(
                local_certificate_file=self.config.get('TLS_OPTIONS', {}).get('CLIENT_CERT_FILE'),
                local_private_key_file=self.config.get('TLS_OPTIONS', {}).get('CLIENT_PRIVKEY_FILE'),
                local_private_key_password=self.config.get('TLS_OPTIONS', {}).get('CLIENT_PRIVKEY_PASSWORD'),
                validate=self.config.get('TLS_OPTIONS', {}).get('VALIDATE', ssl.CERT_REQUIRED),
                ca_certs_file=self.config.get('TLS_OPTIONS', {}).get('CA_CERTS_FILE'),
                version=self.config.get('TLS_OPTIONS', {}).get('VERSION', ssl.PROTOCOL_SSLv23)
            ) 
Example #7
Source File: client_ldap3.py    From code with MIT License 5 votes vote down vote up
def __init__(self, url, require_tls=True):
        Core.debug("creating ldap3 connection to %r", url)
        serv = ldap3.Server(url,
                            tls=ldap3.Tls(validate=ssl.CERT_REQUIRED),
                            get_info=ldap3.DSA)
        self.conn = ldap3.Connection(serv,
                                     #authentication=ldap3.SASL,
                                     #sasl_mechanism=ldap3.GSSAPI,
                                     raise_exceptions=True)
        self.conn.open()
        if require_tls and not url.startswith(("ldaps://", "ldapi://")):
            self.conn.start_tls()

        self._controls = {c[0] for c in self.conn.server.info.supported_controls}
        self._features = {c[0] for c in self.conn.server.info.supported_features} 
Example #8
Source File: ldap.py    From privacyidea with GNU Affero General Public License v3.0 4 votes vote down vote up
def load_config(self, config):
        """
        This loads the configuration dictionary, which contains the necessary
        information for the machine resolver to find and connect to the
        machine store.

        class=computer or sAMAccountType=805306369 (MachineAccount)
        * hostname: attribute dNSHostName
        * id: DN or objectSid
        * ip: N/A

        :param config: The configuration dictionary to run the machine resolver
        :type config: dict
        :return: None
        """
        self.uri = config.get("LDAPURI")
        if self.uri is None:
            raise MachineResolverError("LDAPURI is missing!")
        self.basedn = config.get("LDAPBASE")
        if self.basedn is None:
            raise MachineResolverError("LDAPBASE is missing!")
        self.binddn = config.get("BINDDN")
        self.bindpw = config.get("BINDPW")
        self.timeout = float(config.get("TIMEOUT", 5))
        self.sizelimit = config.get("SIZELIMIT", 500)
        self.hostname_attribute = config.get("HOSTNAMEATTRIBUTE")
        self.id_attribute = config.get("IDATTRIBUTE", "DN")
        self.ip_attribute = config.get("IPATTRIBUTE")
        self.search_filter = config.get("SEARCHFILTER",
                                        "(objectClass=computer)")

        self.noreferrals = is_true(config.get("NOREFERRALS", False))
        self.authtype = config.get("AUTHTYPE", AUTHTYPE.SIMPLE)
        self.start_tls = is_true(config.get("START_TLS", False))
        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 
Example #9
Source File: ldap.py    From privacyidea with GNU Affero General Public License v3.0 4 votes vote down vote up
def testconnection(params):
        """
        Test if the given filename exists.

        :param params:
        :return:
        """
        success = False
        ldap_uri = params.get("LDAPURI")
        if is_true(params.get("TLS_VERIFY")) \
                and (ldap_uri.lower().startswith("ldaps") or
                                    params.get("START_TLS")):
            tls_ca_file = params.get("TLS_CA_FILE") or DEFAULT_CA_FILE
            tls_context = Tls(validate=ssl.CERT_REQUIRED,
                              version=ssl.PROTOCOL_TLSv1,
                              ca_certs_file=tls_ca_file)
        else:
            tls_context = None
        try:
            server_pool = IdResolver.create_serverpool(ldap_uri,
                                                       float(params.get(
                                                        "TIMEOUT", 5)),
                                                       tls_context=tls_context)
            l = IdResolver.create_connection(authtype=\
                                                 params.get("AUTHTYPE",
                                                            AUTHTYPE.SIMPLE),
                                             server=server_pool,
                                             user=params.get("BINDDN"),
                                             password=params.get("BINDPW"),
                                             auto_referrals=not params.get(
                                                 "NOREFERRALS"),
                                             start_tls=params.get("START_TLS", False))
            if not l.bind():
                raise Exception("Wrong credentials")
            # search for users...
            l.search(search_base=params["LDAPBASE"],
                     search_scope=ldap3.SUBTREE,
                     search_filter="(&" + params["SEARCHFILTER"] + ")",
                     attributes=[ params["HOSTNAMEATTRIBUTE"] ])

            count = len([x for x in l.response if x.get("type") ==
                         "searchResEntry"])
            desc = _("Your LDAP config seems to be OK, %i machine objects "
                     "found.")\
                % count

            l.unbind()
            success = True

        except Exception as e:
            desc = "{0!r}".format(e)

        return success, desc 
Example #10
Source File: __init__.py    From flask-ldapconn with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def init_app(self, app):
        ssl_defaults = ssl.get_default_verify_paths()

        # 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_CONNECT_TIMEOUT', 10)
        app.config.setdefault('LDAP_READ_ONLY', False)
        app.config.setdefault('LDAP_VALID_NAMES', None)
        app.config.setdefault('LDAP_PRIVATE_KEY_PASSWORD', None)
        app.config.setdefault('LDAP_RAISE_EXCEPTIONS', False)

        app.config.setdefault('LDAP_CONNECTION_STRATEGY', SYNC)

        app.config.setdefault('LDAP_USE_SSL', False)
        app.config.setdefault('LDAP_USE_TLS', True)
        app.config.setdefault('LDAP_TLS_VERSION', ssl.PROTOCOL_TLSv1)
        app.config.setdefault('LDAP_REQUIRE_CERT', ssl.CERT_REQUIRED)

        app.config.setdefault('LDAP_CLIENT_PRIVATE_KEY', None)
        app.config.setdefault('LDAP_CLIENT_CERT', None)

        app.config.setdefault('LDAP_CA_CERTS_FILE', ssl_defaults.cafile)
        app.config.setdefault('LDAP_CA_CERTS_PATH', ssl_defaults.capath)
        app.config.setdefault('LDAP_CA_CERTS_DATA', None)

        app.config.setdefault('FORCE_ATTRIBUTE_VALUE_AS_LIST', 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_CA_CERTS_FILE'],
            valid_names=app.config['LDAP_VALID_NAMES'],
            ca_certs_path=app.config['LDAP_CA_CERTS_PATH'],
            ca_certs_data=app.config['LDAP_CA_CERTS_DATA'],
            local_private_key_password=app.config['LDAP_PRIVATE_KEY_PASSWORD']
        )

        self.ldap_server = Server(
            host=app.config['LDAP_SERVER'],
            port=app.config['LDAP_PORT'],
            use_ssl=app.config['LDAP_USE_SSL'],
            connect_timeout=app.config['LDAP_CONNECT_TIMEOUT'],
            tls=self.tls,
            get_info=ALL
        )

        # Store ldap_conn object to extensions
        app.extensions['ldap_conn'] = self

        # Teardown appcontext
        app.teardown_appcontext(self.teardown)