def __init__(self, config: _LdapConfig, account_handler: ModuleApi):
        self.account_handler: ModuleApi = account_handler

        self.ldap_mode = config.mode
        self.ldap_uris = [config.uri] if isinstance(config.uri,
                                                    str) else config.uri
        if config.tls_options:
            self.ldap_tls = ldap3.Tls(**config.tls_options)
        else:
            self.ldap_tls = ldap3.Tls(validate=ssl.CERT_REQUIRED if config.
                                      validate_cert else ssl.CERT_NONE)
        self.ldap_start_tls = config.start_tls
        self.ldap_base = config.base
        self.ldap_attributes = config.attributes
        if self.ldap_mode == LDAPMode.SEARCH:
            self.ldap_bind_dn = config.bind_dn
            self.ldap_bind_password = config.bind_password
            self.ldap_filter = config.filter

        self.ldap_active_directory = config.active_directory
        if self.ldap_active_directory:
            self.ldap_default_domain = config.default_domain
            # Either: the Active Directory root domain (type str); empty string in case
            # of error; or None if there was no attempt to fetch root domain yet
            self.ldap_root_domain = None  # type: Optional[str]
Exemple #2
0
    def _test_connect(self):

        try:
            if self.config.test_config.cacert or self.config.test_config.cacertpath:
                tls = ldap3.Tls(
                    validate=ssl.CERT_REQUIRED,
                    ca_certs_file=self.config.test_config.cacert,
                    ca_certs_path=self.config.test_config.cacertpath,
                    valid_names=self.config.test_config.alt_names)
            else:
                tls = ldap3.Tls(validate=ssl.CERT_NONE)
        except ldap3.core.exceptions.LDAPSSLConfigurationError as e:
            raise LdapErrorException(e)

        self.server = ldap3.Server(host=self.config.test_config.host,
                                   port=636,
                                   use_ssl=True,
                                   tls=tls,
                                   get_info=ldap3.ALL)
        try:
            self.connection = ldap3.Connection(
                self.server,
                self.config.test_config.admin_user,
                password=self.config.test_config.admin_pw,
                auto_bind=True,
                client_strategy=ldap3.SYNC)
        except ldap3.core.exceptions.LDAPBindError as e:
            raise LdapErrorException(e)
        except ldap3.core.exceptions.LDAPSocketOpenError as e:
            cert_error = self.__parse_certificate_error(e)
            if cert_error:
                raise LdapErrorException(cert_error)
            raise LdapErrorException(e)

        return
Exemple #3
0
 def __init__(self, config: Config):
     self.config = config
     if self.config.no_certificate_checks:
         self.tls = ldap3.Tls(validate=ssl.CERT_NONE)
     else:
         self.tls = ldap3.Tls()
     self.server = ldap3.Server(self.config.ldap_url, tls=self.tls)
     logger.debug("initialized client for {url}".format(url=self.config.ldap_url))
    def connect(self):
        if self._connection:
            return self._connection

        if self._start_tls or self._server_uri.lower().startswith('ldaps://'):
            self._start_tls = True
            tls = None
            if self._validate_certs:
                tls = ldap3.Tls(validate=ssl.CERT_OPTIONAL)
            else:
                tls = ldap3.Tls(validate=ssl.CERT_NONE)

            try:
                server = ldap3.Server(self._server_uri,
                                      tls=tls,
                                      use_ssl=True,
                                      connect_timeout=self._timeout_connect)
            except LDAPException as e:
                raise LDAPException("Invalid parameter for LDAP server.",
                                    str(e))
        else:
            server = ldap3.Server(self._server_uri,
                                  connect_timeout=self._timeout_connect)

        try:
            if self._bind_dn:
                connection = ldap3.Connection(
                    server,
                    auto_bind=False,
                    receive_timeout=self._timeout_receive,
                    user=self._bind_dn,
                    password=self._bind_pw)
            else:
                connection = ldap3.Connection(
                    server,
                    auto_bind=False,
                    receive_timeout=self._timeout_receive,
                    authentication=ldap3.SASL,
                    sasl_mechanism='EXTERNAL',
                    sasl_credentials='')

            if self._start_tls:
                try:
                    connection.start_tls()
                except LDAPException as e:
                    raise LDAPException("Cannot start TLS.", str(e))

            connection.bind()

        except LDAPException as e:
            raise LDAPException("Cannot bind to the server.", str(e))

        self._connection = connection
        return connection
        def create_args(params):
            validate = ssl.CERT_REQUIRED if params.get(
                'verify_certificate', False) else ssl.CERT_NONE

            if params['encryption'] == 'OFF':
                return {}

            if params['encryption'] == 'SSL':
                tls = ldap3.Tls(validate=validate)
                return {'port': 636, 'use_ssl': True, 'tls': tls}

            if params['encryption'] == 'TLS':
                tls = ldap3.Tls(validate=validate)
                return {'tls': tls}
Exemple #6
0
def get_ldap_users(keytab_file_path, ldap_url, base_dn, ldap_query):
    # set keytab path for ldap3 kerberos auth to work
    os.environ["KRB5_CLIENT_KTNAME"] = keytab_file_path

    tls = ldap3.Tls(validate=ssl.CERT_NONE, version=ssl.PROTOCOL_TLSv1_2)
    server = ldap3.Server(ldap_url, use_ssl=True, tls=tls)
    connection = ldap3.Connection(server, authentication=ldap3.SASL, sasl_mechanism='GSSAPI')
    connection.bind()

    # get users
    connection.search(
        search_base=base_dn, search_filter=ldap_query, search_scope=ldap3.SUBTREE,
        attributes=['cn', 'userPrincipalName', 'userAccountControl'])

    ad_search = connection.response

    # disconnect from LDAP
    connection.unbind()

    users_dict = {}

    # fill the users dict
    for element in ad_search:
        users_dict[element['attributes']['userPrincipalName'][0].lower()] = {
            'cn': element['attributes']['cn'][0],
            'dn': element['dn'][element['dn'].upper().find(',OU=') + 1:element['dn'].upper().find(',' + base_dn.upper())],
            'disabled': int(element['attributes']['userAccountControl'][0]) & 2 == 2
            }
    
    return users_dict
Exemple #7
0
 def __init__(self):
     tls_config = ldap3.Tls(validate=cfg.LDAP3_TLS_VALID,
                            version=cfg.LDAP3_TLS_VERSION)
     self._server: Server = ldap3.Server(host=cfg.LDAP3_HOST,
                                         use_ssl=cfg.LDAP3_USE_SSL,
                                         tls=tls_config,
                                         get_info=ldap3.ALL)
 def getConnection(userdn, username, password):
     if self.use_ssl:
         tlsSettings = ldap3.Tls(
             local_private_key_file=self.client_key_file,
             local_certificate_file=self.client_certificate_file,
             ca_certs_file=self.server_ca_file,
             validate=ssl.CERT_REQUIRED)
         server = ldap3.Server(self.server_address,
                               port=self.server_port,
                               use_ssl=True,
                               tls=tlsSettings)
     else:
         server = ldap3.Server(self.server_address,
                               port=self.server_port,
                               use_ssl=False)
     self.log.debug(
         'Attempting to bind {username} with {userdn}'.format(
             username=username, userdn=userdn))
     conn = ldap3.Connection(
         server,
         user=self.escape_userdn_if_needed(userdn),
         password=password,
         auto_bind=self.use_ssl and ldap3.AUTO_BIND_TLS_BEFORE_BIND
         or ldap3.AUTO_BIND_NO_TLS,
     )
     return conn
Exemple #9
0
 def run_ldaps_noEPA(inputUser, inputPassword, dcTarget):
     try:
         tls = ldap3.Tls(validate=ssl.CERT_NONE,
                         version=ssl.PROTOCOL_TLSv1_2)
         ldapServer = ldap3.Server(dcTarget,
                                   use_ssl=True,
                                   port=636,
                                   get_info=ldap3.ALL,
                                   tls=tls)
         ldapConn = ldap3.Connection(ldapServer,
                                     user=inputUser,
                                     password=inputPassword,
                                     authentication=ldap3.NTLM)
         if not ldapConn.bind():
             if "data 80090346" in str(ldapConn.result):
                 return True  #channel binding IS enforced
             elif "data 52e" in str(ldapConn.result):
                 return False  #channel binding not enforced
             else:
                 context.log.error("UNEXPECTED ERROR: " +
                                   str(ldapConn.result))
         else:
             #LDAPS bind successful
             return False  #because channel binding is not enforced
             exit()
     except Exception as e:
         context.log.error("\n   [!] " + dcTarget + " -", str(e))
         context.log.error(
             "        * Ensure DNS is resolving properly, and that you can reach LDAPS on this host"
         )
Exemple #10
0
 def connect_tls(self):
     kerberos = True
     try:
         if kerberos:
             tls_configuration = ldap3.Tls(validate=ssl.CERT_NONE,
                                           version=ssl.PROTOCOL_TLSv1_2)
         else:
             tls_configuration = Tls(local_private_key_file=self.key,
                                     local_certificate_file=self.cacert,
                                     validate=ssl.CERT_REQUIRED,
                                     version=ssl.PROTOCOL_TLSv1,
                                     ca_certs_file=self.cacert)
     except:
         tls_configuration = Tls(validate=ssl.CERT_REQUIRED,
                                 version=ssl.PROTOCOL_TLSv1_2)
     server = Server(self.uri,
                     port=self.port,
                     tls=tls_configuration,
                     get_info=ALL)  #, use_ssl=True,
     self.connection = Connection(
         server,
         user=self.binddn,
         password=self.password,
         #                 auto_bind=AUTO_BIND_NONE,
         version=3,
         authentication=SIMPLE,
         raise_exceptions=True)
     read_server_info = True
     self.connection.start_tls(read_server_info)
     try:
         self.connection.open()
         return self.connection.bind()
     except Exception as e:
         print("LDAP conenction error %s " % e)
     return False
Exemple #11
0
    def __init__(self,
                 server,
                 fqdn,
                 base="",
                 username="",
                 password="",
                 method="NTLM"):
        """
		ActiveDirectoryView constructor.
		Initialize the connection with the LDAP server.

		Two authentication modes:
			* Kerberos (ldap3 will automatically retrieve the $KRB5CCNAME env variable)
			* NTLM (username + password or NTLM hash)

		@server: Server to connect and perform LDAP query to.
		@fqdn: Fully qualified domain name of the Active Directory domain.
		@base: Base for the LDAP queries.
		@username: Username to use for the authentication (for NTLM authentication)
		@password: Username to use for the authentication (for NTLM authentication)
		@method: Either to use NTLM, Kerberos or anonymous authentication.

		@throw ActiveDirectoryLdapException when the connection or the bind does not work.
		"""
        self.username = username
        self.password = password
        self.server = server
        self.fqdn = fqdn
        self.hostnames = []

        if self.server.startswith("ldaps"):
            server = Server(self.server,
                            port=636,
                            use_ssl=True,
                            allowed_referral_hosts=[('*', True)],
                            tls=ldap3.Tls(validate=CERT_NONE))
        else:
            server = Server(self.server)

        if method == "Kerberos":
            self.ldap = Connection(server,
                                   authentication=SASL,
                                   sasl_mechanism=KERBEROS)
        if method == "anonymous":
            self.ldap = Connection(server)
        elif method == "NTLM":
            self.ldap = Connection(server,
                                   user="******".format(
                                       domain=fqdn, username=username),
                                   password=password,
                                   authentication=NTLM,
                                   check_names=True)

        if not self.ldap.bind():
            raise self.ActiveDirectoryLdapException(
                "Unable to bind with provided information")

        self.base_dn = base or ','.join(
            ["dc={}".format(d) for d in fqdn.split(".")])
        self.search_scope = SUBTREE
Exemple #12
0
def get_ldap_users(keytab_file_path, ldap_url, base_dn, ldap_query):
    # Set keytab path for ldap3 kerberos auth to work
    os.environ["KRB5_CLIENT_KTNAME"] = keytab_file_path

    tls = ldap3.Tls(validate=ssl.CERT_NONE, version=ssl.PROTOCOL_TLSv1_2)
    server = ldap3.Server(ldap_url, use_ssl=True, tls=tls)
    connection = ldap3.Connection(server, authentication=ldap3.SASL, sasl_mechanism='GSSAPI')
    connection.bind()

    # Get users
    connection.search(
        search_base=base_dn, search_filter=ldap_query, search_scope=ldap3.SUBTREE,
        attributes=['cn', 'userPrincipalName'])

    ad_search = connection.response

    # Disconnect from LDAP
    connection.unbind()

    users_dict = {}

    # Fill the users dict
    for element in ad_search:
        if not element['dn']:
            continue

        if not element['dn'] in users_dict:
            users_dict[element['dn']] = (element['attributes']['cn'], element['attributes']['userPrincipalName'])

    # Make a list of tuples for further convenience
    return [
        (dn[dn.upper().find(',OU=') + 1:dn.upper().find(',' + base_dn.upper())], users_dict[dn][0], users_dict[dn][1])
        for dn in users_dict]
Exemple #13
0
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)
Exemple #14
0
def get_ldap_group_keys(ldap, pw):
    """
    Return a dict
        {"firstname lastname <email@domain>": "base64 encoded pgp key"}
    for all members of the configured LDAP group.
    """
    if not os.path.exists(ldap['ca_cert']):
        raise RuntimeError('{} does not exist, check LDAP config'.format(
            ldap['ca_cert']))

    tls_conf = ldap3.Tls(validate=ssl.CERT_REQUIRED,
                         version=ssl.PROTOCOL_TLSv1_2,
                         ca_certs_file=ldap['ca_cert'])
    srv = ldap3.Server(ldap['server'],
                       port=ldap.getint('port'),
                       use_ssl=ldap.getboolean('use_ssl'),
                       tls=tls_conf)

    with ldap3.Connection(srv, ldap['bind_dn'], pw) as l:
        if not l.bind():
            raise RuntimeError('Could not bind to LDAP, wrong password?')

        members = sorted(get_group_members(l, ldap['group_dn']))
        key_dns = get_user_keydns(l, ldap, members)
        keys = get_gpg_keys(l, flatten(key_dns.values()))

    user_keys = {}
    for user, dns in key_dns.items():
        user_keys[user] = []
        for dn in dns:
            user_keys[user].append(keys[dn])

    return user_keys
Exemple #15
0
	def __init__(self, server, domain="", base="", username="", password="", method="NTLM"):
		"""
		LdapActiveDirectoryView constructor.
		Initialize the connection with the LDAP server.

		Two authentication modes:
			* Kerberos (ldap3 will automatically retrieve the $KRB5CCNAME env variable)
			* NTLM (username + password or NTLM hash)

		@server: Server to connect and perform LDAP query to.
		@domain: Fully qualified domain name of the Active Directory domain.
		@base: Base for the LDAP queries.
		@username: Username to use for the authentication (for NTLM authentication)
		@password: Username to use for the authentication (for NTLM authentication)
		@method: Either to use NTLM, Kerberos or anonymous authentication.

		@throw ActiveDirectoryLdapException when the connection or the bind does not work.
		"""
		self.username = username
		self.password = password
		self.server = server
		self.domain = domain
		self.hostnames = []
		
		self.set_controls()
		self.set_all_attributes()

		if self.server.startswith("ldaps"):
			server = Server(
				self.server,
				port=636,
				use_ssl=True,
				allowed_referral_hosts=[('*', True)],
				get_info=LDAP3_ALL,
				tls=ldap3.Tls(validate=CERT_NONE)
			)
		else:
			server = Server(self.server, get_info=LDAP3_ALL)

		if method == "Kerberos":
			self.ldap = Connection(server, authentication=SASL, sasl_mechanism=KERBEROS)
		if method == "anonymous":
			self.ldap = Connection(server)
		elif method == "NTLM":
			self.ldap = Connection(
				server,
				user=f"{domain}\\{username}",
				password=password,
				authentication=NTLM, check_names=True
			)

		try:
			if not self.ldap.bind():
				raise self.ActiveDirectoryLdapException("Unable to bind with provided information")
		except LDAPSocketOpenError:
			raise self.ActiveDirectoryLdapException(f"Unable to open connection with {self.server}")

		self.base_dn = base or server.info.other["rootDomainNamingContext"][0]
		self.fqdn = ".".join(map(lambda x: x.replace("DC=", ''), self.base_dn.split(',')))
		self.search_scope = SUBTREE
Exemple #16
0
def connect(using="default"):
    """
    Connect to the LDAP server in the LDAP settings dict with the name `using`
    """
    config = settings.LDAP[using]

    if config.get('tls'):
        tls = ldap3.Tls(
            ca_certs_file=config.get('ca_file'),
            validate=ssl.CERT_REQUIRED,
        )
    else:
        tls = None

    if '_server' not in config:
        server = ldap3.Server(config['host'], tls=tls)
        config['_server'] = server

    conn = ldap3.Connection(
        config['_server'],
        auto_bind=True,
        user=config.get('username'),
        password=config.get('password'),
        lazy=True,
    )

    return conn
Exemple #17
0
 def __init__(self, app):
     self.app = app
     self.host = app.config['LDAP_HOST']
     self.bind = app.config['LDAP_BIND']
     self.password = app.config['LDAP_PASSWORD']
     tls = ldap3.Tls(validate=ssl.CERT_REQUIRED)
     server = ldap3.Server(self.host, port=636, use_ssl=True, get_info=ldap3.ALL, tls=tls)
     self.server = server
Exemple #18
0
def establish_and_return_ldap_connection(host, port, use_ssl, ca_certs_file,
                                         ca_certs_data, bind_dn, bind_pw):
    tls = None
    if ca_certs_file or ca_certs_data:
        tls = ldap3.Tls(ca_certs_file=ca_certs_file,
                        ca_certs_data=ca_certs_data, validate=ssl.CERT_REQUIRED)
    server = ldap3.Server(host=host, port=port, use_ssl=use_ssl, tls=tls)
    return ldap3.Connection(server, user=bind_dn, password=bind_pw, auto_bind=True)
Exemple #19
0
def connect_to_ldap(server_url,
                    base_dn,
                    password,
                    ssl_tls_mode,
                    trusted_cert,
                    private_key_file,
                    server_cert_file,
                    ca_certs_file):
	try:
		import ldap3
		import ssl

		if trusted_cert == 'Yes':
			tls_configuration = ldap3.Tls(validate=ssl.CERT_REQUIRED,
			                              version=ssl.PROTOCOL_TLSv1)
		else:
			tls_configuration = ldap3.Tls(validate=ssl.CERT_NONE,
			                              version=ssl.PROTOCOL_TLSv1)

		if private_key_file:
			tls_configuration.private_key_file = private_key_file
		if server_cert_file:
			tls_configuration.certificate_file = server_cert_file
		if ca_certs_file:
			tls_configuration.ca_certs_file = ca_certs_file

		server = ldap3.Server(host=server_url,
		                      tls=tls_configuration)
		bind_type = ldap3.AUTO_BIND_TLS_BEFORE_BIND if ssl_tls_mode == "StartTLS" else True

		conn = ldap3.Connection(server=server,
		                        user=base_dn,
		                        password=password,
		                        auto_bind=bind_type,
		                        read_only=True,
		                        raise_exceptions=True)

		return conn

	except ImportError:
		msg = _("Please Install the ldap3 library via pip to use ldap functionality.")
		frappe.throw(msg, title=_("LDAP Not Installed"))
	except ldap3.core.exceptions.LDAPInvalidCredentialsResult:
		frappe.throw(_("Invalid Credentials"))
	except Exception as ex:
		frappe.throw(_(str(ex)))
Exemple #20
0
def connection(**kwargs):
    """
    Creates and returns a connection to the LDAP server.

    The user identifier, if given, should be keyword arguments matching the fields
    in settings.LDAP_AUTH_USER_LOOKUP_FIELDS, plus a `password` argument.
    """
    # Format the DN for the username.
    format_username = import_func(settings.LDAP_AUTH_FORMAT_USERNAME)
    kwargs = {key: value for key, value in kwargs.items() if value}
    username = None
    password = None
    if kwargs:
        password = kwargs.pop("password")
        username = format_username(kwargs)
    # Configure the connection.
    if settings.LDAP_AUTH_USE_TLS:
        auto_bind = ldap3.AUTO_BIND_TLS_BEFORE_BIND
    else:
        auto_bind = ldap3.AUTO_BIND_NO_TLS
    tls = ldap3.Tls(**settings.LDAP_AUTH_TLS_PARAMS)
    # Connect.
    try:
        c = ldap3.Connection(
            ldap3.Server(
                settings.LDAP_AUTH_URL,
                allowed_referral_hosts=[("*", True)],
                tls=tls,
            ),
            user=username,
            password=password,
            auto_bind=auto_bind,
            raise_exceptions=True,
        )
    except LDAPException as ex:
        logger.info("LDAP connect failed: {ex}".format(ex=ex))
        yield None
        return
    # If the settings specify an alternative username and password for querying, rebind as that.
    if ((settings.LDAP_AUTH_CONNECTION_USERNAME
         or settings.LDAP_AUTH_CONNECTION_PASSWORD)
            and (settings.LDAP_AUTH_CONNECTION_USERNAME != username
                 or settings.LDAP_AUTH_CONNECTION_PASSWORD != password)):
        try:
            c.rebind(
                user=format_username(
                    {"username": settings.LDAP_AUTH_CONNECTION_USERNAME}),
                password=settings.LDAP_AUTH_CONNECTION_PASSWORD,
            )
        except LDAPException as ex:
            logger.info("LDAP rebind failed: {ex}".format(ex=ex))
            yield None
            return
    # Return the connection.
    try:
        yield Connection(c)
    finally:
        c.unbind()
Exemple #21
0
 def _ldap_server(self):
     use_ssl = self.url.startswith('ldaps')
     tls = None
     if use_ssl:
         v = ssl.CERT_REQUIRED if self.ssl_verify else ssl.CERT_NONE
         tls = ldap3.Tls(validate=v,
                         ca_certs_file=self.ca_certs_file,
                         ca_certs_path=self.ca_certs_dir)
     return ldap3.Server(self.url, use_ssl=use_ssl, tls=tls)
Exemple #22
0
def login(username, password, domain, hashes, dc_ip, port):
    if port == 389:
        user = '******' % (domain, username)
        try:
            ldapServer = ldap3.Server(dc_ip, port=port, get_info=ldap3.ALL)
            if hashes is not None:
                ldapConn = ldap3.Connection(ldapServer, user=user, password=hashes, authentication=ldap3.NTLM)
                if ldapConn.bind():
                    print("[+]Success %s/%s" % (domain, username) )
            else:
                ldapConn = ldap3.Connection(ldapServer, user=user, password=password, authentication=ldap3.NTLM)
                if ldapConn.bind():
                    print("[+]Success %s/%s" % (domain, username) )
        except socket.error:
            print("[-]Could not connect to dc")
            return
    else:
        user = '******' % (domain, username)
        tls = ldap3.Tls(validate=ssl.CERT_NONE, version=ssl.PROTOCOL_TLSv1_2)
        try:
            ldapServer = ldap3.Server(dc_ip, use_ssl=True, port=port, get_info=ldap3.ALL, tls=tls)
            if hashes is not None:
                ldapConn = ldap3.Connection(ldapServer, user=user, password=hashes, authentication=ldap3.NTLM)
                if ldapConn.bind():
                    print("[+]Success %s/%s" % (domain, username) )
            else:
                ldapConn = ldap3.Connection(ldapServer, user=user, password=password, authentication=ldap3.NTLM)
                if ldapConn.bind():
                    print("[+]Success %s/%s" % (domain, username) )
        except ldap3.core.exceptions.LDAPSocketOpenError:
            #try tlsv1
            tls = ldap3.Tls(validate=ssl.CERT_NONE, version=ssl.PROTOCOL_TLSv1)
            ldapServer = ldap3.Server(dc_ip, use_ssl=True, port=port, get_info=ldap3.ALL, tls=tls)
            if hashes is not None:
                ldapConn = ldap3.Connection(ldapServer, user=user, password=hashes, authentication=ldap3.NTLM)
                if ldapConn.bind():
                    print("[+]Success %s/%s" % (domain, username) )
            else:
                ldapConn = ldap3.Connection(ldapServer, user=user, password=password, authentication=ldap3.NTLM)
                if ldapConn.bind():
                    print("[+]Success %s/%s" % (domain, username) )
        except socket.error as e:
            print("[-]Could not connect to dc")
            return
Exemple #23
0
 def ad_connect(self, ldapuri, username, password, port, ca_file):
     tls_configuration = ldap3.Tls(validate=ssl.CERT_REQUIRED,
                                   ca_certs_file=ca_file)
     server = ldap3.Server(ldapuri, use_ssl=True, tls=tls_configuration)
     conn = ldap3.Connection(server,
                             auto_bind=True,
                             user=username,
                             password=password,
                             authentication=ldap3.NTLM)
     self.conn = conn
Exemple #24
0
    def ldapConnectionFactory():
        tls = ldap3.Tls(validate=ldap_cert_verification, version=ssl.PROTOCOL_TLSv1, ca_certs_file=ldap_certs_file)
        server = ldap3.ServerPool(None, ldap3.POOLING_STRATEGY_ROUND_ROBIN, active=True, exhaust=True)
        for q in ldap_servers:
            x=ldap3.Server(q, tls=tls)
            server.add(x)

        conn = ldap3.Connection(server, service_account_user, service_account_pass, check_names=True)
        conn.bind()
        return conn
Exemple #25
0
    def _connect(self, user, password):
        settings = self.settings_dict

        _debug("connecting")
        url = urlparse(settings['URI'])

        if url.scheme == "ldaps":
            use_ssl = True
        elif url.scheme == "ldap":
            use_ssl = False
        else:
            raise RuntimeError("Unknown scheme '%s'" % url.scheme)

        if ":" in url.netloc:
            host, port = url.netloc.split(":")
            port = int(port)
        else:
            host = url.netloc
            if use_ssl:
                port = 636
            else:
                port = 389

        start_tls = False
        if 'START_TLS' in settings and settings['START_TLS']:
            start_tls = True

        tls = None
        if use_ssl or start_tls:
            tls = ldap3.Tls()
            if 'TLS_CA' in settings and settings['TLS_CA']:
                tls.ca_certs_file = settings['TLS_CA']

            if 'REQUIRE_TLS' in settings and settings['REQUIRE_TLS']:
                tls.validate = ssl.CERT_REQUIRED

        s = ldap3.Server(host, port=port, use_ssl=use_ssl, tls=tls)
        c = ldap3.Connection(
            s,  # client_strategy=ldap3.STRATEGY_SYNC_RESTARTABLE,
            user=user,
            password=password,
            authentication=ldap3.AUTH_SIMPLE)
        c.strategy.restartable_sleep_time = 0
        c.strategy.restartable_tries = 1
        c.raise_exceptions = True

        c.open()

        if start_tls:
            c.start_tls()

        c.bind()

        return c
 def ad_connect_tls(self, ldapuri, username, password, port,
                    ca_file):  # connection uses ca file -> is it mandatory
     tls_configuration = ldap3.Tls(validate=ssl.CERT_NONE,
                                   ca_certs_file=None)
     server = ldap3.Server(ldapuri, use_ssl=True, tls=tls_configuration)
     conn = ldap3.Connection(server,
                             auto_bind=True,
                             user=username,
                             password=password,
                             authentication=ldap3.NTLM)
     self.conn = conn  # Var define conn to AD via LDAP
Exemple #27
0
    def __init__(self,
                 user='',
                 password='',
                 host='ldap.csh.rit.edu',
                 base=USERS,
                 app=False,
                 objects=False,
                 debug=False):
        """
        Initializes object and binds to the specified LDAP server
        :param user: LDAP user to bind as
        :param password: Password for LDAP user
        :param host: LDAP server hostname
        :param base: Distinguished name base for user
        :param app: Connect as an app (boolean)
        :param objects: Convert results to csh.Member objects
        :param debug: Activate debug mode (boolean)
        :return: None
        """
        self.host = host
        self.base = base
        self.objects = objects
        self.debug = debug

        # Configure the LDAP server
        tls = ldap.Tls(validate=ssl.CERT_NONE, version=ssl.PROTOCOL_TLSv1)
        self.ldap_server = ldap.Server(self.host, use_ssl=True, tls=tls)

        if user == '':
            # No user specified, use Kerberos via SASL/GSSAPI to bind
            self.ldap_conn = ldap.Connection(self.ldap_server,
                                             authentication=ldap.SASL,
                                             sasl_mechanism='GSSAPI')
        else:
            # Use simple authentication
            if app:
                # Use the APPS base rather than USERS or whatever was passed
                self.base = APPS

            # Construct user's distinguished name
            ldap_user_dn = 'uid={},{}'.format(user, self.base)

            # Set up the connection
            self.ldap_conn = ldap.Connection(self.ldap_server,
                                             user=ldap_user_dn,
                                             password=password)

        # Attempt to bind
        try:
            self.ldap_conn.bind()
        except ldap.LDAPException as e:
            print("Unable to bind to LDAP: " + str(e))
            if self.debug:
                print("[DEBUG] Connection details: " + str(self.ldap_conn))
Exemple #28
0
def connect_gssapi(host):
    serv = ldap3.Server(host,
                        tls=ldap3.Tls(validate=ssl.CERT_REQUIRED),
                        get_info="DSA")
    conn = ldap3.Connection(serv,
                            authentication="SASL",
                            sasl_mechanism="GSSAPI")
    conn.open()
    if not conn.start_tls():
        raise Exception("start_tls failed", conn.result)
    if not conn.bind():
        raise Exception("bind failed", conn.result)
    return conn
Exemple #29
0
def get(args, addr=None):
    username = None
    password = None
    if not args.anonymous:
        username =  args.domain+'\\'+args.username
        if args.password is None:
            args.password = getpass.getpass()
        if args.nthash:
            if len(args.password) != 32:
                logger.error('Error: ntlm hash must be 32 hex chars')
                sys.exit()
            # ldap3 takes LM:NTLM hash then discards the LM hash so we fake the LM hash
            password = '******'+args.password
        else:
            password = args.password
            logger.debug('NTHASH '+hashlib.new('md4', password.encode('utf-16-le')).hexdigest())

    # avail: PROTOCOL_SSLv23, PROTOCOL_TLSv1, PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2
    tls_config = ldap3.Tls(
        validate=ssl.CERT_NONE if args.insecure else ssl.CERT_OPTIONAL,
        version=ssl.PROTOCOL_TLSv1)
    server = ldap3.Server(
        addr or args.server,
        use_ssl=args.tls,
        port=args.port,
        tls=tls_config,
        get_info=ldap3.ALL if args.info else None)
    auth = ldap3.ANONYMOUS if args.anonymous else ldap3.NTLM
    conn = CachingConnection(
        server,
        user=username,
        password=password,
        authentication=auth,
        version=args.version,
        read_only=True,
        auto_range=True,
        auto_bind=False,
        receive_timeout=args.timeout,
        timeout=args.timeout,
        session=args.session,
        server_fqdn=args.server_fqdn,
        default_search_base=args.search_base,
        #sasl_mechanism=ldap3.KERBEROS, sasl_credentials=(args.server_fqdn,) # for kerberos
    )
    conn.open()
    if args.info:
        print(server.info)
    if args.starttls:
        conn.start_tls()
    conn.bind()
    return conn
 def __connect(self):
     """
     The __connect call will cause you to authenticate to the ldap server and be
     ready to make changes
     """
     tls_configuration = ldap3.Tls(validate=2, version=3,ca_certs_file=self.cafile)
     if isinstance(self.ldapURI,list):
         servers = [ ldap3.Server(uri,port=636,use_ssl=True, tls=tls_configuration,get_info=ldap3.ALL) for uri in self.ldapURI]
         self.conn=ldap3.Connection(servers,user=self.user,password=self.passwd,raise_exceptions=True)
     else:
         servers = ldap3.Server(self.ldapURI,port=636,use_ssl=True, tls=tls_configuration,get_info=ldap3.ALL)
         self.conn=ldap3.Connection(servers,user=self.user,password=self.passwd,raise_exceptions=True)
     if not self.conn.bind():
         raise Exception("error in bind {}".format(self.conn.result))