Python impacket.smb.SMB_DIALECT Examples

The following are 30 code examples of impacket.smb.SMB_DIALECT(). 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 impacket.smb , or try the search function .
Example #1
Source File: smbconnection.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
def login(self, user, password, domain = '', lmhash = '', nthash = '', ntlmFallback = True):
        """
        logins into the target system

        :param string user: username
        :param string password: password for the user
        :param string domain: domain where the account is valid for
        :param string lmhash: LMHASH used to authenticate using hashes (password is not used)
        :param string nthash: NTHASH used to authenticate using hashes (password is not used)
        :param bool ntlmFallback: If True it will try NTLMv1 authentication if NTLMv2 fails. Only available for SMBv1

        :return: None, raises a Session Error if error.
        """
        self._ntlmFallback = ntlmFallback
        try:
            if self.getDialect() == smb.SMB_DIALECT:
                return self._SMBConnection.login(user, password, domain, lmhash, nthash, ntlmFallback)
            else:
                return self._SMBConnection.login(user, password, domain, lmhash, nthash)
        except (smb.SessionError, smb3.SessionError), e:
            raise SessionError(e.get_error_code()) 
Example #2
Source File: SMB_Core.py    From SMBetray with GNU General Public License v3.0 6 votes vote down vote up
def getServerSupportedDialects(self, ip, port = 445):
		'''Connects to the specified server on the provided port(445 default) and enumeratesSMBKey the supported dialects'''
		dialects = [SMB_DIALECT, SMB2_DIALECT_002, SMB2_DIALECT_21, SMB2_DIALECT_30, SMB2_DIALECT_302 ]#, SMB2_DIALECT_311]
		
		# Check SMBv1
		try:
			# Build a generic SMBv1 negotiate packet and only show support for SMBv1
			smb 	= NewSMBPacket(data = unhexlify("ff534d4272000000001845680000000000000000000000000000ed4300000100000e00024e54204c4d20302e3132000200"))
			rawData = str(smb)
			netbios = struct.pack('>i', len(str(rawData)))
			rpkt 	= str(netbios) + str(rawData)
			# Connect through
			client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			client.connect((ip, port))
			client.sendall(rpkt)
			response = client.recv(999999)
			client.close()
			del(client)
		except Exception, e:
			# It's not supported, bummer
			dialects.remove(SMB_DIALECT) 
Example #3
Source File: smbconnection.py    From Slackor with GNU General Public License v3.0 6 votes vote down vote up
def login(self, user, password, domain = '', lmhash = '', nthash = '', ntlmFallback = True):
        """
        logins into the target system

        :param string user: username
        :param string password: password for the user
        :param string domain: domain where the account is valid for
        :param string lmhash: LMHASH used to authenticate using hashes (password is not used)
        :param string nthash: NTHASH used to authenticate using hashes (password is not used)
        :param bool ntlmFallback: If True it will try NTLMv1 authentication if NTLMv2 fails. Only available for SMBv1

        :return: None, raises a Session Error if error.
        """
        self._ntlmFallback = ntlmFallback
        try:
            if self.getDialect() == smb.SMB_DIALECT:
                return self._SMBConnection.login(user, password, domain, lmhash, nthash, ntlmFallback)
            else:
                return self._SMBConnection.login(user, password, domain, lmhash, nthash)
        except (smb.SessionError, smb3.SessionError) as e:
            raise SessionError(e.get_error_code(), e.get_error_packet()) 
Example #4
Source File: smbconnection.py    From Slackor with GNU General Public License v3.0 6 votes vote down vote up
def queryInfo(self, treeId, fileId):
        """
        queries basic information about an opened file/directory

        :param HANDLE treeId: a valid handle for the share where the file is to be opened
        :param HANDLE fileId: a valid handle for the file/directory to be closed

        :return: a smb.SMBQueryFileBasicInfo structure.  raises a SessionError exception if error.

        """
        try:
            if self.getDialect() == smb.SMB_DIALECT:
                res = self._SMBConnection.query_file_info(treeId, fileId)
            else:
                res = self._SMBConnection.queryInfo(treeId, fileId)
            return smb.SMBQueryFileStandardInfo(res)
        except (smb.SessionError, smb3.SessionError) as e:
            raise SessionError(e.get_error_code(), e.get_error_packet()) 
Example #5
Source File: smbconnection.py    From cracke-dit with MIT License 6 votes vote down vote up
def writeNamedPipe(self, treeId, fileId, data, waitAnswer = True):
        """
        writes to a named pipe

        :param HANDLE treeId: a valid handle for the share where the pipe is
        :param HANDLE fileId: a valid handle for the pipe
        :param string data: buffer with the data to write
        :param boolean waitAnswer: whether or not to wait for an answer

        :return: None, raises a SessionError exception if error.

        """
        try:
            if self.getDialect() == smb.SMB_DIALECT:
                return self._SMBConnection.write_andx(treeId, fileId, data, wait_answer = waitAnswer, write_pipe_mode = True)
            else:
                return self.writeFile(treeId, fileId, data, 0)
        except (smb.SessionError, smb3.SessionError), e:
            raise SessionError(e.get_error_code(), e.get_error_packet()) 
Example #6
Source File: smbconnection.py    From cracke-dit with MIT License 6 votes vote down vote up
def login(self, user, password, domain = '', lmhash = '', nthash = '', ntlmFallback = True):
        """
        logins into the target system

        :param string user: username
        :param string password: password for the user
        :param string domain: domain where the account is valid for
        :param string lmhash: LMHASH used to authenticate using hashes (password is not used)
        :param string nthash: NTHASH used to authenticate using hashes (password is not used)
        :param bool ntlmFallback: If True it will try NTLMv1 authentication if NTLMv2 fails. Only available for SMBv1

        :return: None, raises a Session Error if error.
        """
        self._ntlmFallback = ntlmFallback
        try:
            if self.getDialect() == smb.SMB_DIALECT:
                return self._SMBConnection.login(user, password, domain, lmhash, nthash, ntlmFallback)
            else:
                return self._SMBConnection.login(user, password, domain, lmhash, nthash)
        except (smb.SessionError, smb3.SessionError), e:
            raise SessionError(e.get_error_code(), e.get_error_packet()) 
Example #7
Source File: smbconnection.py    From PiBunny with MIT License 6 votes vote down vote up
def login(self, user, password, domain = '', lmhash = '', nthash = '', ntlmFallback = True):
        """
        logins into the target system

        :param string user: username
        :param string password: password for the user
        :param string domain: domain where the account is valid for
        :param string lmhash: LMHASH used to authenticate using hashes (password is not used)
        :param string nthash: NTHASH used to authenticate using hashes (password is not used)
        :param bool ntlmFallback: If True it will try NTLMv1 authentication if NTLMv2 fails. Only available for SMBv1

        :return: None, raises a Session Error if error.
        """
        self._ntlmFallback = ntlmFallback
        try:
            if self.getDialect() == smb.SMB_DIALECT:
                return self._SMBConnection.login(user, password, domain, lmhash, nthash, ntlmFallback)
            else:
                return self._SMBConnection.login(user, password, domain, lmhash, nthash)
        except (smb.SessionError, smb3.SessionError), e:
            raise SessionError(e.get_error_code()) 
Example #8
Source File: smbconnection.py    From PiBunny with MIT License 6 votes vote down vote up
def queryInfo(self, treeId, fileId):
        """
        queries basic information about an opened file/directory

        :param HANDLE treeId: a valid handle for the share where the file is to be opened
        :param HANDLE fileId: a valid handle for the file/directory to be closed

        :return: a smb.SMBQueryFileBasicInfo structure.  raises a SessionError exception if error.

        """
        try:
            if self.getDialect() == smb.SMB_DIALECT:
                res = self._SMBConnection.query_file_info(treeId, fileId)
            else:
                res = self._SMBConnection.queryInfo(treeId, fileId)
            return smb.SMBQueryFileStandardInfo(res)
        except (smb.SessionError, smb3.SessionError), e:
            raise SessionError(e.get_error_code()) 
Example #9
Source File: smbconnection.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
def writeNamedPipe(self, treeId, fileId, data, waitAnswer = True):
        """
        writes to a named pipe

        :param HANDLE treeId: a valid handle for the share where the pipe is
        :param HANDLE fileId: a valid handle for the pipe
        :param string data: buffer with the data to write
        :param boolean waitAnswer: whether or not to wait for an answer

        :return: None, raises a SessionError exception if error.

        """
        try:
            if self.getDialect() == smb.SMB_DIALECT:
                return self._SMBConnection.write_andx(treeId, fileId, data, wait_answer = waitAnswer, write_pipe_mode = True)
            else:
                return self.writeFile(treeId, fileId, data, 0)
        except (smb.SessionError, smb3.SessionError), e:
            raise SessionError(e.get_error_code()) 
Example #10
Source File: smbconnection.py    From PiBunny with MIT License 6 votes vote down vote up
def writeNamedPipe(self, treeId, fileId, data, waitAnswer = True):
        """
        writes to a named pipe

        :param HANDLE treeId: a valid handle for the share where the pipe is
        :param HANDLE fileId: a valid handle for the pipe
        :param string data: buffer with the data to write
        :param boolean waitAnswer: whether or not to wait for an answer

        :return: None, raises a SessionError exception if error.

        """
        try:
            if self.getDialect() == smb.SMB_DIALECT:
                return self._SMBConnection.write_andx(treeId, fileId, data, wait_answer = waitAnswer, write_pipe_mode = True)
            else:
                return self.writeFile(treeId, fileId, data, 0)
        except (smb.SessionError, smb3.SessionError), e:
            raise SessionError(e.get_error_code()) 
Example #11
Source File: smbconnection.py    From PiBunny with MIT License 5 votes vote down vote up
def connectTree(self,share):
        if self.getDialect() == smb.SMB_DIALECT:
            # If we already have a UNC we do nothing.
            if ntpath.ismount(share) is False:
                # Else we build it
                share = ntpath.basename(share)
                share = '\\\\' + self.getRemoteHost() + '\\' + share
        try:
            return self._SMBConnection.connect_tree(share)
        except (smb.SessionError, smb3.SessionError), e:
            raise SessionError(e.get_error_code()) 
Example #12
Source File: smbconnection.py    From PiBunny with MIT License 5 votes vote down vote up
def __init__(self, remoteName='', remoteHost='', myName=None, sess_port=nmb.SMB_SESSION_PORT, timeout=60, preferredDialect=None,
                 existingConnection=None, manualNegotiate=False):

        self._SMBConnection = 0
        self._dialect       = ''
        self._nmbSession    = 0
        self._sess_port     = sess_port
        self._myName        = myName
        self._remoteHost    = remoteHost
        self._remoteName    = remoteName
        self._timeout       = timeout
        self._preferredDialect = preferredDialect
        self._existingConnection = existingConnection
        self._manualNegotiate = manualNegotiate
        self._doKerberos = False
        self._kdcHost = None
        self._useCache = True
        self._ntlmFallback = True

        if existingConnection is not None:
            # Existing Connection must be a smb or smb3 instance
            assert ( isinstance(existingConnection,smb.SMB) or isinstance(existingConnection, smb3.SMB3))
            self._SMBConnection = existingConnection
            self._preferredDialect = self._SMBConnection.getDialect()
            self._doKerberos = self._SMBConnection.getKerberos()
            return

        ##preferredDialect = smb.SMB_DIALECT

        if manualNegotiate is False:
            self.negotiateSession(preferredDialect) 
Example #13
Source File: samrdump.py    From PiBunny with MIT License 5 votes vote down vote up
def dump(self, remoteName, remoteHost):
        """Dumps the list of users and shares registered present at
        remoteName. remoteName is a valid host name or IP address.
        """

        entries = []

        logging.info('Retrieving endpoint list from %s' % remoteName)

        stringbinding = 'ncacn_np:%s[\pipe\samr]' % remoteName
        logging.debug('StringBinding %s'%stringbinding)
        rpctransport = transport.DCERPCTransportFactory(stringbinding)
        rpctransport.set_dport(self.__port)
        rpctransport.setRemoteHost(remoteHost)

        if hasattr(rpctransport,'preferred_dialect'):
            rpctransport.preferred_dialect(SMB_DIALECT)
        if hasattr(rpctransport, 'set_credentials'):
            # This method exists only for selected protocol sequences.
            rpctransport.set_credentials(self.__username, self.__password, self.__domain, self.__lmhash,
                                         self.__nthash, self.__aesKey)
        rpctransport.set_kerberos(self.__doKerberos, self.__kdcHost)

        try:
            entries = self.__fetchList(rpctransport)
        except Exception, e:
            logging.critical(str(e))

        # Display results. 
Example #14
Source File: smb.py    From ActiveReign with GNU General Public License v3.0 5 votes vote down vote up
def smbv1_con(self):
        try:
            self.con = SMBConnection(self.client, self.ip, sess_port=self.port, preferredDialect=SMB_DIALECT, timeout=int(self.timeout))
            self.smbv1=True
            self.con.setTimeout(self.timeout)
            self.logger.debug('SMBv1: Connected to: {}'.format(self.ip))
            return True
        except Exception as e:
            self.logger.debug('SMBv1: Error creating connection to {}: {}'.format(self.host, e))
            return False 
Example #15
Source File: smbconnection.py    From Slackor with GNU General Public License v3.0 5 votes vote down vote up
def setSessionKey(self, key):
        if self.getDialect() == smb.SMB_DIALECT:
            return self._SMBConnection.set_session_key(key)
        else:
            return self._SMBConnection.setSessionKey(key) 
Example #16
Source File: smbconnection.py    From Slackor with GNU General Public License v3.0 5 votes vote down vote up
def getSessionKey(self):
        if self.getDialect() == smb.SMB_DIALECT:
            return self._SMBConnection.get_session_key()
        else:
            return self._SMBConnection.getSessionKey() 
Example #17
Source File: smbconnection.py    From PiBunny with MIT License 5 votes vote down vote up
def getSessionKey(self):
        if self.getDialect() == smb.SMB_DIALECT:
            return self._SMBConnection.get_session_key()
        else:
            return self._SMBConnection.getSessionKey() 
Example #18
Source File: smbconnection.py    From Slackor with GNU General Public License v3.0 5 votes vote down vote up
def connectTree(self,share):
        if self.getDialect() == smb.SMB_DIALECT:
            # If we already have a UNC we do nothing.
            if ntpath.ismount(share) is False:
                # Else we build it
                share = ntpath.basename(share)
                share = '\\\\' + self.getRemoteHost() + '\\' + share
        try:
            return self._SMBConnection.connect_tree(share)
        except (smb.SessionError, smb3.SessionError) as e:
            raise SessionError(e.get_error_code(), e.get_error_packet()) 
Example #19
Source File: smbconnection.py    From CVE-2017-7494 with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, remoteName='', remoteHost='', myName=None, sess_port=nmb.SMB_SESSION_PORT, timeout=60, preferredDialect=None,
                 existingConnection=None, manualNegotiate=False):

        self._SMBConnection = 0
        self._dialect       = ''
        self._nmbSession    = 0
        self._sess_port     = sess_port
        self._myName        = myName
        self._remoteHost    = remoteHost
        self._remoteName    = remoteName
        self._timeout       = timeout
        self._preferredDialect = preferredDialect
        self._existingConnection = existingConnection
        self._manualNegotiate = manualNegotiate
        self._doKerberos = False
        self._kdcHost = None
        self._useCache = True
        self._ntlmFallback = True

        if existingConnection is not None:
            # Existing Connection must be a smb or smb3 instance
            assert ( isinstance(existingConnection,smb.SMB) or isinstance(existingConnection, smb3.SMB3))
            self._SMBConnection = existingConnection
            self._preferredDialect = self._SMBConnection.getDialect()
            self._doKerberos = self._SMBConnection.getKerberos()
            return

        ##preferredDialect = smb.SMB_DIALECT

        if manualNegotiate is False:
            self.negotiateSession(preferredDialect) 
Example #20
Source File: smbconnection.py    From Slackor with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, remoteName='', remoteHost='', myName=None, sess_port=nmb.SMB_SESSION_PORT, timeout=60, preferredDialect=None,
                 existingConnection=None, manualNegotiate=False):

        self._SMBConnection = 0
        self._dialect       = ''
        self._nmbSession    = 0
        self._sess_port     = sess_port
        self._myName        = myName
        self._remoteHost    = remoteHost
        self._remoteName    = remoteName
        self._timeout       = timeout
        self._preferredDialect = preferredDialect
        self._existingConnection = existingConnection
        self._manualNegotiate = manualNegotiate
        self._doKerberos = False
        self._kdcHost = None
        self._useCache = True
        self._ntlmFallback = True

        if existingConnection is not None:
            # Existing Connection must be a smb or smb3 instance
            assert ( isinstance(existingConnection,smb.SMB) or isinstance(existingConnection, smb3.SMB3))
            self._SMBConnection = existingConnection
            self._preferredDialect = self._SMBConnection.getDialect()
            self._doKerberos = self._SMBConnection.getKerberos()
            return

        ##preferredDialect = smb.SMB_DIALECT

        if manualNegotiate is False:
            self.negotiateSession(preferredDialect) 
Example #21
Source File: smbconnection.py    From PiBunny with MIT License 5 votes vote down vote up
def setSessionKey(self, key):
        if self.getDialect() == smb.SMB_DIALECT:
            return self._SMBConnection.set_session_key(key)
        else:
            return self._SMBConnection.setSessionKey(key) 
Example #22
Source File: smbconnection.py    From cracke-dit with MIT License 5 votes vote down vote up
def connectTree(self,share):
        if self.getDialect() == smb.SMB_DIALECT:
            # If we already have a UNC we do nothing.
            if ntpath.ismount(share) is False:
                # Else we build it
                share = ntpath.basename(share)
                share = '\\\\' + self.getRemoteHost() + '\\' + share
        try:
            return self._SMBConnection.connect_tree(share)
        except (smb.SessionError, smb3.SessionError), e:
            raise SessionError(e.get_error_code(), e.get_error_packet()) 
Example #23
Source File: smbconnection.py    From CVE-2017-7494 with GNU General Public License v3.0 5 votes vote down vote up
def connectTree(self,share):
        if self.getDialect() == smb.SMB_DIALECT:
            # If we already have a UNC we do nothing.
            if ntpath.ismount(share) is False:
                # Else we build it
                share = ntpath.basename(share)
                share = '\\\\' + self.getRemoteHost() + '\\' + share
        try:
            return self._SMBConnection.connect_tree(share)
        except (smb.SessionError, smb3.SessionError), e:
            raise SessionError(e.get_error_code()) 
Example #24
Source File: smbconnection.py    From CVE-2017-7494 with GNU General Public License v3.0 5 votes vote down vote up
def getSessionKey(self):
        if self.getDialect() == smb.SMB_DIALECT:
            return self._SMBConnection.get_session_key()
        else:
            return self._SMBConnection.getSessionKey() 
Example #25
Source File: smbconnection.py    From CVE-2017-7494 with GNU General Public License v3.0 5 votes vote down vote up
def setSessionKey(self, key):
        if self.getDialect() == smb.SMB_DIALECT:
            return self._SMBConnection.set_session_key(key)
        else:
            return self._SMBConnection.setSessionKey(key) 
Example #26
Source File: ldap.py    From CrackMapExec with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def create_smbv1_conn(self):
        try:
            self.conn = SMBConnection(self.host, self.host, None, 445, preferredDialect=SMB_DIALECT)
            self.smbv1 = True
        except socket.error as e:
            if str(e).find('Connection reset by peer') != -1:
                logging.debug('SMBv1 might be disabled on {}'.format(self.host))
            return False
        except Exception as e:
            logging.debug('Error creating SMBv1 connection to {}: {}'.format(self.host, e))
            return False

        return True 
Example #27
Source File: smb.py    From CrackMapExec with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def create_smbv1_conn(self):
        try:
            self.conn = SMBConnection(self.host, self.host, None, self.args.port, preferredDialect=SMB_DIALECT)
            self.smbv1 = True
        except socket.error as e:
            if str(e).find('Connection reset by peer') != -1:
                logging.debug('SMBv1 might be disabled on {}'.format(self.host))
            return False
        except Exception as e:
            logging.debug('Error creating SMBv1 connection to {}: {}'.format(self.host, e))
            return False

        return True 
Example #28
Source File: smbconnection.py    From cracke-dit with MIT License 5 votes vote down vote up
def __init__(self, remoteName='', remoteHost='', myName=None, sess_port=nmb.SMB_SESSION_PORT, timeout=60, preferredDialect=None,
                 existingConnection=None, manualNegotiate=False):

        self._SMBConnection = 0
        self._dialect       = ''
        self._nmbSession    = 0
        self._sess_port     = sess_port
        self._myName        = myName
        self._remoteHost    = remoteHost
        self._remoteName    = remoteName
        self._timeout       = timeout
        self._preferredDialect = preferredDialect
        self._existingConnection = existingConnection
        self._manualNegotiate = manualNegotiate
        self._doKerberos = False
        self._kdcHost = None
        self._useCache = True
        self._ntlmFallback = True

        if existingConnection is not None:
            # Existing Connection must be a smb or smb3 instance
            assert ( isinstance(existingConnection,smb.SMB) or isinstance(existingConnection, smb3.SMB3))
            self._SMBConnection = existingConnection
            self._preferredDialect = self._SMBConnection.getDialect()
            self._doKerberos = self._SMBConnection.getKerberos()
            return

        ##preferredDialect = smb.SMB_DIALECT

        if manualNegotiate is False:
            self.negotiateSession(preferredDialect) 
Example #29
Source File: SMB_Core.py    From SMBetray with GNU General Public License v3.0 5 votes vote down vote up
def restackSMBChainedMessages(self, SMBPacketList):
		try:
			# Takes in a list of NewSMBPacket or SMB2Packets	
			if SMBPacketList[0].__class__.__name__ == 'SMB2Packet':	
				reStacked = ""
				for i in range(0, len(SMBPacketList)):
					if(i < len(SMBPacketList) - 1):
						SMBPacketList[i]['NextCommand'] = len(str(SMBPacketList[i])) + ((8 - (len(str(SMBPacketList[i])) % 8)) % 8)
						SMBPacketList[i]['Data'] = SMBPacketList[i]['Data'] + str('\x00' * ((8 - (len(str(SMBPacketList[i])) % 8)) % 8)) #Padding
					else:
						SMBPacketList[i]['NextCommand'] = 0
					reStacked += str(SMBPacketList[i])
				netbios = struct.pack('>i', len(str(reStacked)))
				# Return the ready-to-send packet
				return str(netbios) + str(reStacked)

			if SMBPacketList[0].__class__.__name__ == 'NewSMBPacket':
				# SMBv1 Uses ANDX to chain messages

				# TODO: fix this
				reStacked = ""
				for i in range(0, len(SMBPacketList)):
					reStacked += str(SMBPacketList[i])
				netbios = struct.pack('>i', len(str(reStacked)))
				# Return the ready-to-send packet
				return str(netbios) + str(reStacked)

		except Exception, e:
			logging.error("[SMB_Core::restackSMBChainedMessages] " + str(traceback.format_exc()))
			return SMBPacketList

	# Returns a list of supported dialects as constants,
	# such as SMB_DIALECT and SMB2_DIALECT_302 
Example #30
Source File: smbconnection.py    From cracke-dit with MIT License 5 votes vote down vote up
def getSessionKey(self):
        if self.getDialect() == smb.SMB_DIALECT:
            return self._SMBConnection.get_session_key()
        else:
            return self._SMBConnection.getSessionKey()