Python ldap3.NTLM Examples

The following are 30 code examples of ldap3.NTLM(). 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: ldaprelayclient.py    From PiBunny with MIT License 6 votes vote down vote up
def sendNegotiate(self, negotiateMessage):
        self.negotiateMessage = negotiateMessage
        self.init_connection()

        with self.connection.lock:
            if not self.connection.sasl_in_progress:
                self.connection.sasl_in_progress = True
                request = bind.bind_operation(self.connection.version, 'SICILY_PACKAGE_DISCOVERY')
                response = self.connection.post_send_single_response(self.connection.send('bindRequest', request, None))
                result = response[0]
                sicily_packages = result['server_creds'].decode('ascii').split(';')

                if 'NTLM' in sicily_packages:  # NTLM available on server
                    request = bind.bind_operation(self.connection.version, 'SICILY_NEGOTIATE_NTLM', self)
                    response = self.connection.post_send_single_response(self.connection.send('bindRequest', request, None))
                    result = response[0]

                    if result['result'] == RESULT_SUCCESS:
                        return result['server_creds']

    #This is a fake function for ldap3 which wants an NTLM client with specific methods 
Example #2
Source File: ldaprelayclient.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
def sendNegotiate(self, negotiateMessage):
        self.negotiateMessage = negotiateMessage
        self.init_connection()

        with self.connection.lock:
            if not self.connection.sasl_in_progress:
                self.connection.sasl_in_progress = True
                request = bind.bind_operation(self.connection.version, 'SICILY_PACKAGE_DISCOVERY')
                response = self.connection.post_send_single_response(self.connection.send('bindRequest', request, None))
                result = response[0]
                sicily_packages = result['server_creds'].decode('ascii').split(';')

                if 'NTLM' in sicily_packages:  # NTLM available on server
                    request = bind.bind_operation(self.connection.version, 'SICILY_NEGOTIATE_NTLM', self)
                    response = self.connection.post_send_single_response(self.connection.send('bindRequest', request, None))
                    result = response[0]

                    if result['result'] == RESULT_SUCCESS:
                        return result['server_creds']

    #This is a fake function for ldap3 which wants an NTLM client with specific methods 
Example #3
Source File: exploitation.py    From aclpwn.py with MIT License 6 votes vote down vote up
def perform_rebind(ldapconnection, contextuser, config, confdict):
    if config.user is not None and contextuser != config.user:
        # we should now switch context to the new user
        print_m('Switching context to %s' % config.user)
        if not config.password:
            prompt = 'Please supply the password or LM:NTLM hashes for the account %s: ' % config.user
            config.password = getpass.getpass(prompt.encode('utf-8'))
        rebind_ldap(ldapconnection, config.user, config.password, config.domain)
        contextuser = config.user
        print_o('Done switching context')
    else:
        # we should re-bind to refresh our access rights
        print_m('Re-binding to LDAP to refresh group memberships of %s' % contextuser)
        # Password depends on the context we are under
        if contextuser == config.user:
            password = config.password
        else:
            password = config.source_password
        rebind_ldap(ldapconnection, contextuser, password, config.domain)
        print_o('Re-bind successful')
    return contextuser 
Example #4
Source File: restore.py    From aclpwn.py with MIT License 6 votes vote down vote up
def rebind_ldap(self, user):
        domain = self.config['domain']

        # Todo: get password from command line args
        try:
            password = self.passdata[user]
        except KeyError:
            prompt = 'Please supply the password or LM:NTLM hashes for the account %s: ' % user
            password = getpass.getpass(prompt.encode('utf-8'))
            # Store for further reference
            self.passdata[user] = password

        if domain is None:
            domain = get_domain(user)
        if '@' in user or '.' in user:
            binduser = get_sam_name(user)
        else:
            binduser = user

        if not self.ldapconnection.rebind('%s\\%s' % (domain, binduser), password, authentication=ldap3.NTLM):
            raise RestoreException('Failed to switch context to %s\\%s: %s' % (domain, binduser, str(self.ldapconnection.result)))

        return user 
Example #5
Source File: ldaprelayclient.py    From Exchange2domain with MIT License 6 votes vote down vote up
def sendAuth(self, authenticateMessageBlob, serverChallenge=None):
        if unpack('B', str(authenticateMessageBlob)[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP:
            respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob)
            token = respToken2['ResponseToken']
        else:
            token = authenticateMessageBlob
        with self.session.connection_lock:
            self.authenticateMessageBlob = token
            request = bind.bind_operation(self.session.version, 'SICILY_RESPONSE_NTLM', self, None)
            response = self.session.post_send_single_response(self.session.send('bindRequest', request, None))
            result = response[0]
        self.session.sasl_in_progress = False

        if result['result'] == RESULT_SUCCESS:
            self.session.bound = True
            self.session.refresh_server_info()
            return None, STATUS_SUCCESS
        else:
            if result['result'] == RESULT_STRONGER_AUTH_REQUIRED and self.PLUGIN_NAME != 'LDAPS':
                raise LDAPRelayClientException('Server rejected authentication because LDAP signing is enabled. Try connecting with TLS enabled (specify target as ldaps://hostname )')
        return None, STATUS_ACCESS_DENIED

    #This is a fake function for ldap3 which wants an NTLM client with specific methods 
Example #6
Source File: ldaprelayclient.py    From PiBunny with MIT License 5 votes vote down vote up
def sendAuth(self, authenticateMessageBlob, serverChallenge=None):
        with self.connection.lock:
            self.authenticateMessageBlob = authenticateMessageBlob
            request = bind.bind_operation(self.connection.version, 'SICILY_RESPONSE_NTLM', self, None)
            response = self.connection.post_send_single_response(self.connection.send('bindRequest', request, None))
            result = response[0]
        self.connection.sasl_in_progress = False

        if result['result'] == RESULT_SUCCESS:
            self.connection.bound = True
            self.connection.refresh_server_info()
        return result

    #This is a fake function for ldap3 which wants an NTLM client with specific methods 
Example #7
Source File: ldaprelayclient.py    From PiBunny with MIT License 5 votes vote down vote up
def init_connection(self):
        self.server = Server(self.target, get_info=ALL)
        self.connection = Connection(self.server, user="a", password="b", authentication=NTLM)
        self.connection.open(False) 
Example #8
Source File: helper.py    From resilient-community-apps with MIT License 5 votes vote down vote up
def __init__(self, app_configs):
        SUPPORTED_LDAP_AUTH_TYPE_TYPES = ["ANONYMOUS", "SIMPLE", "NTLM"]

        self.LDAP_SERVER = self.__get_config_option(app_configs=app_configs, option_name="ldap_server", optional=False, placeholder="xxx.xxx.xxx.xxx")
        self.LDAP_PORT = int(self.__get_config_option(app_configs=app_configs, option_name="ldap_port", optional=False))
        self.LDAP_USE_SSL = self.str_to_bool(self.__get_config_option(app_configs=app_configs, option_name="ldap_use_ssl", optional=False))
        self.LDAP_AUTH_TYPE = self.__get_config_option(app_configs=app_configs, option_name="ldap_auth", optional=False).upper()
        self.LDAP_USER_DN = self.__get_config_option(app_configs=app_configs, option_name="ldap_user_dn", optional=True)
        self.LDAP_USER_NTLM = self.__get_config_option(app_configs=app_configs, option_name="ldap_user_ntlm", optional=True)
        self.LDAP_PASSWORD = self.__get_config_option(app_configs=app_configs, option_name="ldap_password", optional=True)
        self.LDAP_IS_ACTIVE_DIRECTORY = self.str_to_bool(self.__get_config_option(app_configs=app_configs, option_name="ldap_is_active_directory", optional=False))
        self.LDAP_CONNECT_TIMEOUT = int(self.__get_config_option(app_configs=app_configs, option_name="ldap_connect_timeout", optional=False))

        if self.LDAP_AUTH_TYPE not in SUPPORTED_LDAP_AUTH_TYPE_TYPES:
            raise ValueError("Invalid value for 'ldap_auth'. '{0}' is not a supported authentication method. Support methods are: {1}".format(self.LDAP_AUTH_TYPE, SUPPORTED_LDAP_AUTH_TYPE_TYPES))

        if self.LDAP_AUTH_TYPE == "SIMPLE":
            if not self.LDAP_USER_DN or not self.LDAP_PASSWORD:
                raise ValueError("'ldap_user_dn' and 'ldap_password' must be defined in the app.config file if using SIMPLE authentication to your LDAP Server")

        elif self.LDAP_AUTH_TYPE == "NTLM":
            if not self.LDAP_USER_NTLM or not self.LDAP_PASSWORD:
                raise ValueError("'ldap_user_ntlm' and 'ldap_password' must be defined in the app.config file if using NTLM  authentication to your LDAP Server")

        elif self.LDAP_AUTH_TYPE == "ANONYMOUS":
            if self.LDAP_USER_DN or self.LDAP_USER_NTLM or self.LDAP_PASSWORD:
                raise ValueError("'ldap_user_dn', 'ldap_user_ntlm' and 'ldap_password' must be left blank in the app.config file if using ANONYMOUS authentication to your LDAP Server") 
Example #9
Source File: helper.py    From resilient-community-apps with MIT License 5 votes vote down vote up
def get_ldap_connection(self):
        try:
            server = Server(self.LDAP_SERVER, port=self.LDAP_PORT, get_info=ALL, use_ssl=self.LDAP_USE_SSL, connect_timeout=self.LDAP_CONNECT_TIMEOUT)
        
            if self.LDAP_AUTH_TYPE == "NTLM":
                connection = Connection(
                    server=server,
                    user=self.LDAP_USER_NTLM,
                    password=self.LDAP_PASSWORD,
                    authentication=NTLM,
                    return_empty_attributes=True,
                    raise_exceptions=True)

            else:
                connection = Connection(
                    server=server,
                    user=self.LDAP_USER_DN,
                    password=self.LDAP_PASSWORD,
                    authentication=self.LDAP_AUTH_TYPE,
                    return_empty_attributes=True,
                    raise_exceptions=True)

            return connection

        except Exception as err:
            raise ValueError("Cannot connect to LDAP Server. Ensure credentials are correct\n Error: {0}".format(err)) 
Example #10
Source File: restore.py    From CVE-2019-1040 with MIT License 5 votes vote down vote up
def establish_connection(self, user):
        domain = self.config['domain']
        # First check if the server was specified explicitly
        if self.config['server']:
            server = self.config['server']
        else:
            server = self.config['domain']
        # if self.args.server:
        #     server = self.args.server
        # # If not, check if the server was specified in the restore data
        # elif self.config['server']:
        #     server = self.config['server']
        # # Else, assume DNS is set up properly and we can connect to the domain
        # else:
        #     server = self.config['domain']

        #password = getpass.getpass(self.ntlm.encode('utf-8')) 
        password = self.ntlm
        self.passdata[user] = password
        #Todo: get password from command line args
        # try:
        #     password = self.passdata[user]
        # except KeyError:
        #     prompt = 'Please supply the password or LM:NTLM hashes for the account %s: ' % user
        #     password = getpass.getpass(prompt.encode('utf-8'))
        #     # Store for further reference
        #     self.passdata[user] = password

        if domain is None:
            domain = get_domain(user)
        if '@' in user or '.' in user:
            binduser = get_sam_name(user)
        else:
            binduser = user

        ldapserver = ldap3.Server(server, get_info=ldap3.DSA)
        connection = ldap3.Connection(ldapserver, user='%s\\%s' % (domain, binduser), password=password, authentication=ldap3.NTLM)
        if not connection.bind():
            raise RestoreException('Failed to connect to the LDAP server as %s\\%s: %s' % (domain, binduser, str(connection.result)))
        return connection, user 
Example #11
Source File: ldaprelayclient.py    From CVE-2019-1040 with MIT License 5 votes vote down vote up
def initConnection(self):
        self.server = Server("ldaps://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL)
        self.session = Connection(self.server, user="a", password="b", authentication=NTLM)
        self.session.open(False)
        return True 
Example #12
Source File: ldaprelayclient.py    From CVE-2019-1040 with MIT License 5 votes vote down vote up
def initConnection(self):
        self.server = Server("ldap://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL)
        self.session = Connection(self.server, user="a", password="b", authentication=NTLM)
        self.session.open(False)
        return True 
Example #13
Source File: ldaprelayclient.py    From Slackor with GNU General Public License v3.0 5 votes vote down vote up
def initConnection(self):
        self.server = Server("ldaps://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL)
        self.session = Connection(self.server, user="a", password="b", authentication=NTLM)
        self.session.open(False)
        return True 
Example #14
Source File: ldaprelayclient.py    From Slackor with GNU General Public License v3.0 5 votes vote down vote up
def initConnection(self):
        self.server = Server("ldap://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL)
        self.session = Connection(self.server, user="a", password="b", authentication=NTLM)
        self.session.open(False)
        return True 
Example #15
Source File: ldaprelayclient.py    From Exchange2domain with MIT License 5 votes vote down vote up
def initConnection(self):
        self.server = Server("ldaps://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL)
        self.session = Connection(self.server, user="a", password="b", authentication=NTLM)
        self.session.open(False)
        return True 
Example #16
Source File: ldaprelayclient.py    From Exchange2domain with MIT License 5 votes vote down vote up
def initConnection(self):
        self.server = Server("ldap://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL)
        self.session = Connection(self.server, user="a", password="b", authentication=NTLM)
        self.session.open(False)
        return True 
Example #17
Source File: restore.py    From aclpwn.py with MIT License 5 votes vote down vote up
def establish_connection(self, user):
        domain = self.config['domain']
        # First check if the server was specified explicitly
        if self.args.server:
            server = self.args.server
        # If not, check if the server was specified in the restore data
        elif self.config['server']:
            server = self.config['server']
        # Else, assume DNS is set up properly and we can connect to the domain
        else:
            server = self.config['domain']

        # Todo: get password from command line args
        try:
            password = self.passdata[user]
        except KeyError:
            prompt = 'Please supply the password or LM:NTLM hashes for the account %s: ' % user
            password = getpass.getpass(prompt.encode('utf-8'))
            # Store for further reference
            self.passdata[user] = password

        if domain is None:
            domain = get_domain(user)
        if '@' in user or '.' in user:
            binduser = get_sam_name(user)
        else:
            binduser = user

        ldapserver = ldap3.Server(server, get_info=ldap3.DSA)
        connection = ldap3.Connection(ldapserver, user='%s\\%s' % (domain, binduser), password=password, authentication=ldap3.NTLM)
        if not connection.bind():
            raise RestoreException('Failed to connect to the LDAP server as %s\\%s: %s' % (domain, binduser, str(connection.result)))
        return connection, user 
Example #18
Source File: exploitation.py    From aclpwn.py with MIT License 5 votes vote down vote up
def connect_ldap(server, user, password, domain=None):
    if domain is None:
        domain = get_domain(user)
    if '@' in user or '.' in user:
        user = get_sam_name(user)
    ldapserver = ldap3.Server(server, get_info=ldap3.DSA)
    connection = ldap3.Connection(ldapserver, user='%s\\%s' % (domain, user), password=password, authentication=ldap3.NTLM)
    if not connection.bind():
        raise ExploitException('Failed to connect to the LDAP server as %s\\%s: %s' % (domain, user, str(connection.result)))
    return connection 
Example #19
Source File: ldaprelayclient.py    From Exchange2domain with MIT License 5 votes vote down vote up
def sendNegotiate(self, negotiateMessage):
        #Remove the message signing flag
        #For LDAP this is required otherwise it triggers LDAP signing
        negoMessage = NTLMAuthNegotiate()
        negoMessage.fromString(negotiateMessage)
        #negoMessage['flags'] ^= NTLMSSP_NEGOTIATE_SIGN
        self.negotiateMessage = str(negoMessage)

        with self.session.connection_lock:
            if not self.session.sasl_in_progress:
                self.session.sasl_in_progress = True
                request = bind.bind_operation(self.session.version, 'SICILY_PACKAGE_DISCOVERY')
                response = self.session.post_send_single_response(self.session.send('bindRequest', request, None))
                result = response[0]
                try:
                    sicily_packages = result['server_creds'].decode('ascii').split(';')
                except KeyError:
                    raise LDAPRelayClientException('Could not discover authentication methods, server replied: %s' % result)

                if 'NTLM' in sicily_packages:  # NTLM available on server
                    request = bind.bind_operation(self.session.version, 'SICILY_NEGOTIATE_NTLM', self)
                    response = self.session.post_send_single_response(self.session.send('bindRequest', request, None))
                    result = response[0]

                    if result['result'] == RESULT_SUCCESS:
                        challenge = NTLMAuthChallenge()
                        challenge.fromString(result['server_creds'])
                        return challenge
                else:
                    raise LDAPRelayClientException('Server did not offer NTLM authentication!')

    #This is a fake function for ldap3 which wants an NTLM client with specific methods 
Example #20
Source File: exploitation.py    From aclpwn.py with MIT License 5 votes vote down vote up
def rebind_ldap(ldapconnection, user, password, domain=None):
    if domain is None:
        domain = get_domain(user)
    if '@' in user:
        user = get_sam_name(user)
    if not ldapconnection.rebind('%s\\%s' % (domain, user), password, authentication=ldap3.NTLM):
        raise ExploitException('Failed to switch context to %s\\%s: %s' % (domain, user, str(ldapconnection.result))) 
Example #21
Source File: ldaprelayclient.py    From cracke-dit with MIT License 5 votes vote down vote up
def sendAuth(self, authenticateMessageBlob, serverChallenge=None):
        with self.connection.lock:
            self.authenticateMessageBlob = authenticateMessageBlob
            request = bind.bind_operation(self.connection.version, 'SICILY_RESPONSE_NTLM', self, None)
            response = self.connection.post_send_single_response(self.connection.send('bindRequest', request, None))
            result = response[0]
        self.connection.sasl_in_progress = False

        if result['result'] == RESULT_SUCCESS:
            self.connection.bound = True
            self.connection.refresh_server_info()
        return result

    #This is a fake function for ldap3 which wants an NTLM client with specific methods 
Example #22
Source File: ldaprelayclient.py    From cracke-dit with MIT License 5 votes vote down vote up
def sendNegotiate(self, negotiateMessage):
        self.negotiateMessage = negotiateMessage
        self.init_connection()

        with self.connection.lock:
            if not self.connection.sasl_in_progress:
                self.connection.sasl_in_progress = True
                request = bind.bind_operation(self.connection.version, 'SICILY_PACKAGE_DISCOVERY')
                response = self.connection.post_send_single_response(self.connection.send('bindRequest', request, None))
                result = response[0]
                try:
                    sicily_packages = result['server_creds'].decode('ascii').split(';')
                except KeyError:
                    raise LDAPRelayClientException('Could not discover authentication methods, server replied: %s' % result)

                if 'NTLM' in sicily_packages:  # NTLM available on server
                    request = bind.bind_operation(self.connection.version, 'SICILY_NEGOTIATE_NTLM', self)
                    response = self.connection.post_send_single_response(self.connection.send('bindRequest', request, None))
                    result = response[0]

                    if result['result'] == RESULT_SUCCESS:
                        return result['server_creds']
                else:
                    raise LDAPRelayClientException('Server did not offer NTLM authentication!')

    #This is a fake function for ldap3 which wants an NTLM client with specific methods 
Example #23
Source File: ldaprelayclient.py    From cracke-dit with MIT License 5 votes vote down vote up
def init_connection(self):
        self.server = Server(self.target, get_info=ALL)
        self.connection = Connection(self.server, user="a", password="b", authentication=NTLM)
        self.connection.open(False) 
Example #24
Source File: ldaprelayclient.py    From CVE-2017-7494 with GNU General Public License v3.0 5 votes vote down vote up
def sendAuth(self, authenticateMessageBlob, serverChallenge=None):
        with self.connection.lock:
            self.authenticateMessageBlob = authenticateMessageBlob
            request = bind.bind_operation(self.connection.version, 'SICILY_RESPONSE_NTLM', self, None)
            response = self.connection.post_send_single_response(self.connection.send('bindRequest', request, None))
            result = response[0]
        self.connection.sasl_in_progress = False

        if result['result'] == RESULT_SUCCESS:
            self.connection.bound = True
            self.connection.refresh_server_info()
        return result

    #This is a fake function for ldap3 which wants an NTLM client with specific methods 
Example #25
Source File: genserv.py    From genmon with GNU General Public License v2.0 4 votes vote down vote up
def doLdapLogin(username, password):
    if LdapServer == None or LdapServer == "":
        return False
    try:
        from ldap3 import Server, Connection, ALL, NTLM
    except ImportError as importException:
        LogError("LDAP3 import not found, run 'sudo pip install ldap3 && sudo pip3 install ldap3'")
        LogError(importException)
        return False

    HasAdmin = False
    HasReadOnly = False
    SplitName = username.split('\\')
    DomainName = SplitName[0]
    DomainName = DomainName.strip()
    AccountName = SplitName[1]
    AccountName = AccountName.strip()
    server = Server(LdapServer, get_info=ALL)
    conn = Connection(server, user='{}\\{}'.format(DomainName, AccountName), password=password, authentication=NTLM, auto_bind=True)
    conn.search('dc=skipfire,dc=local', '(&(objectclass=user)(sAMAccountName='+AccountName+'))', attributes=['memberOf'])
    for user in sorted(conn.entries):
        for group in user.memberOf:
            if group.upper().find("CN="+LdapAdminGroup.upper()) >= 0:
                HasAdmin = True
            elif group.upper().find("CN="+LdapReadOnlyGroup.upper()) >= 0:
                HasReadOnly = True

    session['logged_in'] = HasAdmin or HasReadOnly
    session['write_access'] = HasAdmin
    if HasAdmin:
        LogError("Admin Login via LDAP")
    elif HasReadOnly:
        LogError("Limited Rights Login via LDAP")
    else:
        LogError("No rights for valid login via LDAP")

    return HasAdmin or HasReadOnly

#------------------------------------------------------------------------------- 
Example #26
Source File: connection.py    From insightconnect-plugins with MIT License 4 votes vote down vote up
def connect(self, params):
        """
        Connect to LDAP
        """
        self.ssl = params.get('use_ssl')
        self.logger.info("Connecting to %s:%d" % (params['host'], params['port']))

        params['port'] = params.get('port') or 389

        use_ssl = False
        if params.get('use_ssl'):
            use_ssl = True

        server = ldap3.Server(
                host=params['host'],
                port=params['port'],
                use_ssl=use_ssl,
                get_info=ldap3.ALL)

        try:
            conn = ldap3.Connection(server=server,
                                    user=params.get('username_password').get('username'),
                                    password=params.get('username_password').get('password'),
                                    auto_encode=True,
                                    auto_escape=True,
                                    auto_bind=True,
                                    auto_referrals=False,
                                    authentication=ldap3.NTLM)
        except exceptions.LDAPBindError as e:
            self.logger.error(f'ldap3 returned the following error {e}')
            raise ConnectionTestException(preset=ConnectionTestException.Preset.USERNAME_PASSWORD)
        except exceptions.LDAPAuthorizationDeniedResult as e:
            self.logger.error(f'ldap3 returned the following error {e}')
            raise ConnectionTestException(preset=ConnectionTestException.Preset.UNAUTHORIZED)
        except exceptions.LDAPSocketOpenError as e:
            self.logger.error(f'ldap3 returned the following error {e}')
            raise ConnectionTestException(
                preset=ConnectionTestException.Preset.SERVICE_UNAVAILABLE)
        except:
            try:
                conn = ldap3.Connection(server=server,
                                        user=params.get('username_password').get('username'),
                                        password=params.get('username_password').get('password'),
                                        auto_referrals=False,
                                        auto_bind=True)
            except exceptions.LDAPBindError as e:
                self.logger.error(f'ldap3 returned the following error {e}')
                raise ConnectionTestException(
                    preset=ConnectionTestException.Preset.USERNAME_PASSWORD)
            except exceptions.LDAPAuthorizationDeniedResult as e:
                self.logger.error(f'ldap3 returned the following error {e}')
                raise ConnectionTestException(preset=ConnectionTestException.Preset.UNAUTHORIZED)
            except exceptions.LDAPSocketOpenError as e:
                self.logger.error(f'ldap3 returned the following error {e}')
                raise ConnectionTestException(
                    preset=ConnectionTestException.Preset.SERVICE_UNAVAILABLE)

        self.logger.info("Connected!")
        self.conn = conn 
Example #27
Source File: ldaprelayclient.py    From CVE-2017-7494 with GNU General Public License v3.0 4 votes vote down vote up
def init_connection(self):
        self.server = Server(self.target, get_info=ALL)
        self.connection = Connection(self.server, user="a", password="b", authentication=NTLM)
        self.connection.open(False) 
Example #28
Source File: authentication.py    From BloodHound.py with MIT License 4 votes vote down vote up
def getLDAPConnection(self, hostname='', baseDN='', protocol='ldaps', gc=False):
        if gc:
            # Global Catalog connection
            if protocol == 'ldaps':
                # Ldap SSL
                server = Server("%s://%s:3269" % (protocol, hostname), get_info=ALL)
            else:
                # Plain LDAP
                server = Server("%s://%s:3268" % (protocol, hostname), get_info=ALL)
        else:
            server = Server("%s://%s" % (protocol, hostname), get_info=ALL)
        # ldap3 supports auth with the NT hash. LM hash is actually ignored since only NTLMv2 is used.
        if self.nt_hash != '':
            ldappass = self.lm_hash + ':' + self.nt_hash
        else:
            ldappass = self.password
        ldaplogin = '%s\\%s' % (self.domain, self.username)
        conn = Connection(server, user=ldaplogin, auto_referrals=False, password=ldappass, authentication=NTLM, receive_timeout=60, auto_range=True)

        # TODO: Kerberos auth for ldap
        if self.kdc is not None:
            logging.error('Kerberos login is not yet supported!')
            # try:
            #     logging.debug('Authenticating to LDAP server using Kerberos')
            #     conn.kerberosLogin(self.username, self.password, self.domain,
            #                        self.lm_hash, self.nt_hash, self.aes_key,
            #                        self.kdc)
            # except KerberosError as e:
            #     logging.warning('Kerberos login failed: %s' % e)
            #     return None
        else:
            logging.debug('Authenticating to LDAP server')
            if not conn.bind():
                result = conn.result
                if result['result'] == RESULT_STRONGER_AUTH_REQUIRED and protocol == 'ldap':
                    logging.warning('LDAP Authentication is refused because LDAP signing is enabled. '
                                    'Trying to connect over LDAPS instead...')
                    return self.getLDAPConnection(hostname, baseDN, 'ldaps')
                else:
                    logging.error('Failure to authenticate with LDAP! Error %s' % result['message'])
                    return None
        return conn 
Example #29
Source File: LDAPIdResolver.py    From privacyidea with GNU Affero General Public License v3.0 4 votes vote down vote up
def checkPass(self, uid, password):
        """
        This function checks the password for a given uid.
        - returns true in case of success
        -         false if password does not match

        """
        if self.authtype == AUTHTYPE.NTLM:  # pragma: no cover
            # fetch the PreWindows 2000 Domain from the self.binddn
            # which would be of the format DOMAIN\username and compose the
            # bind_user to DOMAIN\sAMAcountName
            domain_name = self.binddn.split('\\')[0]
            uinfo = self.getUserInfo(uid)
            # In fact we need the sAMAccountName. If the username mapping is
            # another attribute than the sAMAccountName the authentication
            # will fail!
            bind_user = u"{0!s}\{1!s}".format(domain_name, uinfo.get("username"))
        else:
            bind_user = self._getDN(uid)

        if not self.serverpool:
            self.serverpool = self.get_serverpool_instance(get_info=ldap3.NONE)

        try:
            log.debug("Authtype: {0!r}".format(self.authtype))
            log.debug("user    : {0!r}".format(bind_user))
            # Whatever happens. If we have an empty bind_user, we must break
            # since we must avoid anonymous binds!
            if not bind_user or len(bind_user) < 1:
                raise Exception("No valid user. Empty bind_user.")
            l = self.create_connection(authtype=self.authtype,
                                       server=self.serverpool,
                                       user=bind_user,
                                       password=password,
                                       receive_timeout=self.timeout,
                                       auto_referrals=not self.noreferrals,
                                       start_tls=self.start_tls)
            r = l.bind()
            log.debug("bind result: {0!r}".format(r))
            if not r:
                raise Exception("Wrong credentials")
            log.debug("bind seems successful.")
            l.unbind()
            log.debug("unbind successful.")
        except Exception as e:
            log.warning("failed to check password for {0!r}/{1!r}: {2!r}".format(uid, bind_user, e))
            log.debug(traceback.format_exc())
            return False

        return True 
Example #30
Source File: ldaprelayclient.py    From CVE-2019-1040 with MIT License 4 votes vote down vote up
def sendAuth(self, authenticateMessageBlob, serverChallenge=None):
        if unpack('B', authenticateMessageBlob[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP:
            respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob)
            token = respToken2['ResponseToken']
        else:
            token = authenticateMessageBlob

        authMessage = NTLMAuthChallengeResponse()
        authMessage.fromString(token)
        # When exploiting CVE-2019-1040, remove flags
        if self.serverConfig.remove_mic:
            if authMessage['flags'] & NTLMSSP_NEGOTIATE_SIGN == NTLMSSP_NEGOTIATE_SIGN:
                authMessage['flags'] ^= NTLMSSP_NEGOTIATE_SIGN
            if authMessage['flags'] & NTLMSSP_NEGOTIATE_ALWAYS_SIGN == NTLMSSP_NEGOTIATE_ALWAYS_SIGN:
                authMessage['flags'] ^= NTLMSSP_NEGOTIATE_ALWAYS_SIGN
            if authMessage['flags'] & NTLMSSP_NEGOTIATE_KEY_EXCH == NTLMSSP_NEGOTIATE_KEY_EXCH:
                authMessage['flags'] ^= NTLMSSP_NEGOTIATE_KEY_EXCH
            if authMessage['flags'] & NTLMSSP_NEGOTIATE_VERSION == NTLMSSP_NEGOTIATE_VERSION:
                authMessage['flags'] ^= NTLMSSP_NEGOTIATE_VERSION
            authMessage['MIC'] = b''
            authMessage['MICLen'] = 0
            authMessage['Version'] = b''
            authMessage['VersionLen'] = 0
            token = authMessage.getData()

        with self.session.connection_lock:
            self.authenticateMessageBlob = token
            request = bind.bind_operation(self.session.version, 'SICILY_RESPONSE_NTLM', self, None)
            response = self.session.post_send_single_response(self.session.send('bindRequest', request, None))
            result = response[0]
        self.session.sasl_in_progress = False

        if result['result'] == RESULT_SUCCESS:
            self.session.bound = True
            self.session.refresh_server_info()
            return None, STATUS_SUCCESS
        else:
            if result['result'] == RESULT_STRONGER_AUTH_REQUIRED and self.PLUGIN_NAME != 'LDAPS':
                raise LDAPRelayClientException('Server rejected authentication because LDAP signing is enabled. Try connecting with TLS enabled (specify target as ldaps://hostname )')
        return None, STATUS_ACCESS_DENIED

    #This is a fake function for ldap3 which wants an NTLM client with specific methods