Python impacket.spnego.SPNEGO_NegTokenResp() Examples

The following are 17 code examples of impacket.spnego.SPNEGO_NegTokenResp(). 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.spnego , or try the search function .
Example #1
Source File: smbrelayserver.py    From PiBunny with MIT License 6 votes vote down vote up
def do_ntlm_auth(self,client,SPNEGO_token,authenticateMessage):
        #The NTLM blob is packed in a SPNEGO packet, extract it for methods other than SMB
        respToken2 = SPNEGO_NegTokenResp(SPNEGO_token)
        token = respToken2['ResponseToken']
        clientResponse = None
        if self.target[0] == 'SMB':
            clientResponse, errorCode = client.sendAuth(SPNEGO_token,authenticateMessage)
        if self.target[0] == 'MSSQL':
            #This client needs a proper response code
            try:
                result = client.sendAuth(token)
                if result: #This contains a boolean
                    errorCode = STATUS_SUCCESS
                else:
                    errorCode = STATUS_ACCESS_DENIED
            except Exception, e:
                logging.error("NTLM Message type 3 against %s FAILED" % self.target[1])
                logging.error(str(e))
                errorCode = STATUS_ACCESS_DENIED 
Example #2
Source File: smbrelayserver.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
def do_ntlm_auth(self,client,SPNEGO_token,authenticateMessage):
        #The NTLM blob is packed in a SPNEGO packet, extract it for methods other than SMB
        respToken2 = SPNEGO_NegTokenResp(SPNEGO_token)
        token = respToken2['ResponseToken']
        clientResponse = None
        if self.target[0] == 'SMB':
            clientResponse, errorCode = client.sendAuth(SPNEGO_token,authenticateMessage)
        if self.target[0] == 'MSSQL':
            #This client needs a proper response code
            try:
                result = client.sendAuth(token)
                if result: #This contains a boolean
                    errorCode = STATUS_SUCCESS
                else:
                    errorCode = STATUS_ACCESS_DENIED
            except Exception, e:
                logging.error("NTLM Message type 3 against %s FAILED" % self.target[1])
                logging.error(str(e))
                errorCode = STATUS_ACCESS_DENIED 
Example #3
Source File: smbrelayserver.py    From NtlmRelayToEWS with GNU General Public License v3.0 6 votes vote down vote up
def do_ntlm_auth(self,client,SPNEGO_token,authenticateMessage):
        #The NTLM blob is packed in a SPNEGO packet, extract it for methods other than SMB
        respToken2 = SPNEGO_NegTokenResp(SPNEGO_token)
        token = respToken2['ResponseToken']
        clientResponse = None

        if self.target[0] == 'HTTP' or self.target[0] == 'HTTPS':
            try:
                result = client.sendAuth(token) #Result is a boolean
                if result:
                    errorCode = STATUS_SUCCESS
                else:
                    logging.error("HTTP NTLM auth against %s as %s FAILED" % (self.target[1],self.authUser))
                    errorCode = STATUS_ACCESS_DENIED
            except Exception, e:
                logging.error("NTLM Message type 3 against %s FAILED" % self.target[1])
                logging.error(str(e))
                errorCode = STATUS_ACCESS_DENIED 
Example #4
Source File: httprelayserver.py    From NtlmRelayToEWS with GNU General Public License v3.0 6 votes vote down vote up
def do_ntlm_auth(self,token,authenticateMessage):
			#For some attacks it is important to know the authenticated username, so we store it
			self.authUser = authenticateMessage['user_name']
		
			#TODO: What is this 127.0.0.1 doing here? Maybe document specific use case
			if authenticateMessage['user_name'] != '' or self.target[1] == '127.0.0.1':
				respToken2 = SPNEGO_NegTokenResp()
				respToken2['ResponseToken'] = str(token)

				if self.target[0] == 'HTTP' or self.target[0] == 'HTTPS':
				    try:
				        result = self.client.sendAuth(token) #Result is a boolean
				        if result:
				            return True
				        else:
				            logging.error("HTTP NTLM auth against %s as %s FAILED" % (self.target[1],self.authUser))
				            return False
				    except Exception, e:
				        logging.error("HTTP NTLM Message type 3 against %s FAILED" % self.target[1])
				        logging.error(str(e))
				        return False 
Example #5
Source File: smbrelayserver.py    From cracke-dit with MIT License 6 votes vote down vote up
def do_ntlm_auth(self,client,SPNEGO_token,authenticateMessage):
        #The NTLM blob is packed in a SPNEGO packet, extract it for methods other than SMB
        respToken2 = SPNEGO_NegTokenResp(SPNEGO_token)
        token = respToken2['ResponseToken']
        clientResponse = None
        if self.target[0] == 'SMB':
            clientResponse, errorCode = client.sendAuth(SPNEGO_token,authenticateMessage)
        if self.target[0] == 'MSSQL':
            #This client needs a proper response code
            try:
                result = client.sendAuth(token)
                if result: #This contains a boolean
                    errorCode = STATUS_SUCCESS
                else:
                    errorCode = STATUS_ACCESS_DENIED
            except Exception, e:
                logging.error("NTLM Message type 3 against %s FAILED" % self.target[1])
                logging.error(str(e))
                errorCode = STATUS_ACCESS_DENIED 
Example #6
Source File: kerberosv5.py    From PiBunny with MIT License 5 votes vote down vote up
def getKerberosType3(cipher, sessionKey, auth_data):
    negTokenResp = SPNEGO_NegTokenResp(auth_data)
    # If DCE_STYLE = FALSE
    #ap_rep = decoder.decode(negTokenResp['ResponseToken'][16:], asn1Spec=AP_REP())[0]
    try:
        krbError = KerberosError(packet = decoder.decode(negTokenResp['ResponseToken'][15:], asn1Spec = KRB_ERROR())[0])
    except Exception, e:
        pass 
Example #7
Source File: httprelayserver.py    From PiBunny with MIT License 5 votes vote down vote up
def do_ntlm_auth(self,token,authenticateMessage):
            #For some attacks it is important to know the authenticated username, so we store it
            self.authUser = authenticateMessage['user_name']
            
            #TODO: What is this 127.0.0.1 doing here? Maybe document specific use case
            if authenticateMessage['user_name'] != '' or self.target[1] == '127.0.0.1':
                respToken2 = SPNEGO_NegTokenResp()
                respToken2['ResponseToken'] = str(token)
                if self.target[0] == 'SMB':
                    clientResponse, errorCode = self.client.sendAuth(respToken2.getData(),self.challengeMessage['challenge'])
                if self.target[0] == 'MSSQL':
                    try:
                        result = self.client.sendAuth(token)
                        return result #This contains a boolean
                    except Exception, e:
                        logging.error("NTLM Message type 3 against %s FAILED" % self.target[1])
                        logging.error(str(e))
                        return False

                if self.target[0] == 'LDAP' or self.target[0] == 'LDAPS':
                    try:
                        result = self.client.sendAuth(token) #Result dict
                        if result['result'] == 0 and result['description'] == 'success':
                            return True
                        else:
                            logging.error("LDAP bind against %s as %s FAILED" % (self.target[1],self.authUser))
                            logging.error('Error: %s. Message: %s' % (result['description'],str(result['message'])))
                            return False
                        #Failed example:
                        #{'dn': u'', 'saslCreds': None, 'referrals': None, 'description': 'invalidCredentials', 'result': 49, 'message': u'8009030C: LdapErr: DSID-0C0905FE, comment: AcceptSecurityContext error, data 52e, v23f0\x00', 'type': 'bindResponse'}
                        #Ok example:
                        #{'dn': u'', 'saslCreds': None, 'referrals': None, 'description': 'success', 'result': 0, 'message': u'', 'type': 'bindResponse'}
                    except Exception, e:
                        logging.error("NTLM Message type 3 against %s FAILED" % self.target[1])
                        logging.error(str(e))
                        return False 
Example #8
Source File: kerberosv5.py    From cracke-dit with MIT License 5 votes vote down vote up
def getKerberosType3(cipher, sessionKey, auth_data):
    negTokenResp = SPNEGO_NegTokenResp(auth_data)
    # If DCE_STYLE = FALSE
    #ap_rep = decoder.decode(negTokenResp['ResponseToken'][16:], asn1Spec=AP_REP())[0]
    try:
        krbError = KerberosError(packet = decoder.decode(negTokenResp['ResponseToken'][15:], asn1Spec = KRB_ERROR())[0])
    except Exception, e:
        pass 
Example #9
Source File: httprelayserver.py    From cracke-dit with MIT License 5 votes vote down vote up
def do_ntlm_auth(self,token,authenticateMessage):
            #For some attacks it is important to know the authenticated username, so we store it
            self.authUser = authenticateMessage['user_name']
            
            #TODO: What is this 127.0.0.1 doing here? Maybe document specific use case
            if authenticateMessage['user_name'] != '' or self.target[1] == '127.0.0.1':
                respToken2 = SPNEGO_NegTokenResp()
                respToken2['ResponseToken'] = str(token)
                if self.target[0] == 'SMB':
                    clientResponse, errorCode = self.client.sendAuth(respToken2.getData(),self.challengeMessage['challenge'])
                if self.target[0] == 'MSSQL':
                    try:
                        result = self.client.sendAuth(token)
                        return result #This contains a boolean
                    except Exception, e:
                        logging.error("NTLM Message type 3 against %s FAILED" % self.target[1])
                        logging.error(str(e))
                        return False

                if self.target[0] == 'LDAP' or self.target[0] == 'LDAPS':
                    try:
                        result = self.client.sendAuth(token) #Result dict
                        if result['result'] == 0 and result['description'] == 'success':
                            return True
                        else:
                            logging.error("LDAP bind against %s as %s FAILED" % (self.target[1],self.authUser))
                            logging.error('Error: %s. Message: %s' % (result['description'],str(result['message'])))
                            return False
                        #Failed example:
                        #{'dn': u'', 'saslCreds': None, 'referrals': None, 'description': 'invalidCredentials', 'result': 49, 'message': u'8009030C: LdapErr: DSID-0C0905FE, comment: AcceptSecurityContext error, data 52e, v23f0\x00', 'type': 'bindResponse'}
                        #Ok example:
                        #{'dn': u'', 'saslCreds': None, 'referrals': None, 'description': 'success', 'result': 0, 'message': u'', 'type': 'bindResponse'}
                    except Exception, e:
                        logging.error("NTLM Message type 3 against %s FAILED" % self.target[1])
                        logging.error(str(e))
                        return False 
Example #10
Source File: kerberosv5.py    From CVE-2017-7494 with GNU General Public License v3.0 5 votes vote down vote up
def getKerberosType3(cipher, sessionKey, auth_data):
    negTokenResp = SPNEGO_NegTokenResp(auth_data)
    # If DCE_STYLE = FALSE
    #ap_rep = decoder.decode(negTokenResp['ResponseToken'][16:], asn1Spec=AP_REP())[0]
    try:
        krbError = KerberosError(packet = decoder.decode(negTokenResp['ResponseToken'][15:], asn1Spec = KRB_ERROR())[0])
    except Exception, e:
        pass 
Example #11
Source File: httprelayserver.py    From CVE-2017-7494 with GNU General Public License v3.0 5 votes vote down vote up
def do_ntlm_auth(self,token,authenticateMessage):
            #For some attacks it is important to know the authenticated username, so we store it
            self.authUser = authenticateMessage['user_name']
            
            #TODO: What is this 127.0.0.1 doing here? Maybe document specific use case
            if authenticateMessage['user_name'] != '' or self.target[1] == '127.0.0.1':
                respToken2 = SPNEGO_NegTokenResp()
                respToken2['ResponseToken'] = str(token)
                if self.target[0] == 'SMB':
                    clientResponse, errorCode = self.client.sendAuth(respToken2.getData(),self.challengeMessage['challenge'])
                if self.target[0] == 'MSSQL':
                    try:
                        result = self.client.sendAuth(token)
                        return result #This contains a boolean
                    except Exception, e:
                        logging.error("NTLM Message type 3 against %s FAILED" % self.target[1])
                        logging.error(str(e))
                        return False

                if self.target[0] == 'LDAP' or self.target[0] == 'LDAPS':
                    try:
                        result = self.client.sendAuth(token) #Result dict
                        if result['result'] == 0 and result['description'] == 'success':
                            return True
                        else:
                            logging.error("LDAP bind against %s as %s FAILED" % (self.target[1],self.authUser))
                            logging.error('Error: %s. Message: %s' % (result['description'],str(result['message'])))
                            return False
                        #Failed example:
                        #{'dn': u'', 'saslCreds': None, 'referrals': None, 'description': 'invalidCredentials', 'result': 49, 'message': u'8009030C: LdapErr: DSID-0C0905FE, comment: AcceptSecurityContext error, data 52e, v23f0\x00', 'type': 'bindResponse'}
                        #Ok example:
                        #{'dn': u'', 'saslCreds': None, 'referrals': None, 'description': 'success', 'result': 0, 'message': u'', 'type': 'bindResponse'}
                    except Exception, e:
                        logging.error("NTLM Message type 3 against %s FAILED" % self.target[1])
                        logging.error(str(e))
                        return False 
Example #12
Source File: smbrelayclient.py    From cracke-dit with MIT License 4 votes vote down vote up
def sendNegotiate(self, negotiateMessage):
        smb = NewSMBPacket()
        smb['Flags1'] = SMB.FLAGS1_PATHCASELESS
        smb['Flags2'] = SMB.FLAGS2_EXTENDED_SECURITY 
        # Are we required to sign SMB? If so we do it, if not we skip it
        if self._SignatureRequired: 
           smb['Flags2'] |= SMB.FLAGS2_SMB_SECURITY_SIGNATURE
          

        sessionSetup = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX)
        sessionSetup['Parameters'] = SMBSessionSetupAndX_Extended_Parameters()
        sessionSetup['Data']       = SMBSessionSetupAndX_Extended_Data()

        sessionSetup['Parameters']['MaxBufferSize']        = 65535
        sessionSetup['Parameters']['MaxMpxCount']          = 2
        sessionSetup['Parameters']['VcNumber']             = 1
        sessionSetup['Parameters']['SessionKey']           = 0
        sessionSetup['Parameters']['Capabilities']         = SMB.CAP_EXTENDED_SECURITY | SMB.CAP_USE_NT_ERRORS | SMB.CAP_UNICODE

        # Let's build a NegTokenInit with the NTLMSSP
        # TODO: In the future we should be able to choose different providers

        blob = SPNEGO_NegTokenInit() 

        # NTLMSSP
        blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]
        blob['MechToken'] = str(negotiateMessage)

        sessionSetup['Parameters']['SecurityBlobLength']  = len(blob)
        sessionSetup['Parameters'].getData()
        sessionSetup['Data']['SecurityBlob']       = blob.getData()

        # Fake Data here, don't want to get us fingerprinted
        sessionSetup['Data']['NativeOS']      = 'Unix'
        sessionSetup['Data']['NativeLanMan']  = 'Samba'

        smb.addCommand(sessionSetup)
        self.sendSMB(smb)
        smb = self.recvSMB()

        try:
            smb.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX)
        except Exception:
            logging.error("SessionSetup Error!")
            raise
        else:
            # We will need to use this uid field for all future requests/responses
            self._uid = smb['Uid']

            # Now we have to extract the blob to continue the auth process
            sessionResponse   = SMBCommand(smb['Data'][0])
            sessionParameters = SMBSessionSetupAndX_Extended_Response_Parameters(sessionResponse['Parameters'])
            sessionData       = SMBSessionSetupAndX_Extended_Response_Data(flags = smb['Flags2'])
            sessionData['SecurityBlobLength'] = sessionParameters['SecurityBlobLength']
            sessionData.fromString(sessionResponse['Data'])
            respToken = SPNEGO_NegTokenResp(sessionData['SecurityBlob'])

            return respToken['ResponseToken'] 
Example #13
Source File: smbrelayx.py    From Slackor with GNU General Public License v3.0 4 votes vote down vote up
def sendNegotiate(self, negotiateMessage):
        smb = NewSMBPacket()
        smb['Flags1'] = SMB.FLAGS1_PATHCASELESS
        smb['Flags2'] = SMB.FLAGS2_EXTENDED_SECURITY 
        # Are we required to sign SMB? If so we do it, if not we skip it
        if self._SignatureRequired: 
           smb['Flags2'] |= SMB.FLAGS2_SMB_SECURITY_SIGNATURE
          

        sessionSetup = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX)
        sessionSetup['Parameters'] = SMBSessionSetupAndX_Extended_Parameters()
        sessionSetup['Data']       = SMBSessionSetupAndX_Extended_Data()

        sessionSetup['Parameters']['MaxBufferSize']        = 65535
        sessionSetup['Parameters']['MaxMpxCount']          = 2
        sessionSetup['Parameters']['VcNumber']             = 1
        sessionSetup['Parameters']['SessionKey']           = 0
        sessionSetup['Parameters']['Capabilities'] = SMB.CAP_EXTENDED_SECURITY | SMB.CAP_USE_NT_ERRORS | SMB.CAP_UNICODE

        # Let's build a NegTokenInit with the NTLMSSP
        # TODO: In the future we should be able to choose different providers

        blob = SPNEGO_NegTokenInit() 

        # NTLMSSP
        blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]
        blob['MechToken'] = negotiateMessage

        sessionSetup['Parameters']['SecurityBlobLength']  = len(blob)
        sessionSetup['Parameters'].getData()
        sessionSetup['Data']['SecurityBlob']       = blob.getData()

        # Fake Data here, don't want to get us fingerprinted
        sessionSetup['Data']['NativeOS']      = 'Unix'
        sessionSetup['Data']['NativeLanMan']  = 'Samba'

        smb.addCommand(sessionSetup)
        self.sendSMB(smb)
        smb = self.recvSMB()

        try:
            smb.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX)
        except Exception:
            logging.error("SessionSetup Error!")
            raise
        else:
            # We will need to use this uid field for all future requests/responses
            self._uid = smb['Uid']

            # Now we have to extract the blob to continue the auth process
            sessionResponse   = SMBCommand(smb['Data'][0])
            sessionParameters = SMBSessionSetupAndX_Extended_Response_Parameters(sessionResponse['Parameters'])
            sessionData       = SMBSessionSetupAndX_Extended_Response_Data(flags = smb['Flags2'])
            sessionData['SecurityBlobLength'] = sessionParameters['SecurityBlobLength']
            sessionData.fromString(sessionResponse['Data'])
            respToken = SPNEGO_NegTokenResp(sessionData['SecurityBlob'])

            return respToken['ResponseToken'] 
Example #14
Source File: kerberosv5.py    From Slackor with GNU General Public License v3.0 4 votes vote down vote up
def getKerberosType3(cipher, sessionKey, auth_data):
    negTokenResp = SPNEGO_NegTokenResp(auth_data)
    # If DCE_STYLE = FALSE
    #ap_rep = decoder.decode(negTokenResp['ResponseToken'][16:], asn1Spec=AP_REP())[0]
    try:
        krbError = KerberosError(packet = decoder.decode(negTokenResp['ResponseToken'][15:], asn1Spec = KRB_ERROR())[0])
    except Exception:
        pass
    else:
        raise krbError

    ap_rep = decoder.decode(negTokenResp['ResponseToken'], asn1Spec=AP_REP())[0]

    cipherText = ap_rep['enc-part']['cipher']

    # Key Usage 12
    # AP-REP encrypted part (includes application session
    # subkey), encrypted with the application session key
    # (Section 5.5.2)
    plainText = cipher.decrypt(sessionKey, 12, cipherText)

    encAPRepPart = decoder.decode(plainText, asn1Spec = EncAPRepPart())[0]

    cipher = _enctype_table[int(encAPRepPart['subkey']['keytype'])]()
    sessionKey2 = Key(cipher.enctype, encAPRepPart['subkey']['keyvalue'].asOctets())

    sequenceNumber = int(encAPRepPart['seq-number'])

    encAPRepPart['subkey'].clear()
    encAPRepPart = encAPRepPart.clone()

    now = datetime.datetime.utcnow()
    encAPRepPart['cusec'] = now.microsecond
    encAPRepPart['ctime'] = KerberosTime.to_asn1(now)
    encAPRepPart['seq-number'] = sequenceNumber
    encodedAuthenticator = encoder.encode(encAPRepPart)

    encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 12, encodedAuthenticator, None)

    ap_rep['enc-part'].clear()
    ap_rep['enc-part']['etype'] = cipher.enctype
    ap_rep['enc-part']['cipher'] = encryptedEncodedAuthenticator

    resp = SPNEGO_NegTokenResp()
    resp['ResponseToken'] = encoder.encode(ap_rep)

    return cipher, sessionKey2, resp.getData() 
Example #15
Source File: smbrelayx.py    From PiBunny with MIT License 4 votes vote down vote up
def sendNegotiate(self, negotiateMessage):
        smb = NewSMBPacket()
        smb['Flags1'] = SMB.FLAGS1_PATHCASELESS
        smb['Flags2'] = SMB.FLAGS2_EXTENDED_SECURITY 
        # Are we required to sign SMB? If so we do it, if not we skip it
        if self._SignatureRequired: 
           smb['Flags2'] |= SMB.FLAGS2_SMB_SECURITY_SIGNATURE
          

        sessionSetup = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX)
        sessionSetup['Parameters'] = SMBSessionSetupAndX_Extended_Parameters()
        sessionSetup['Data']       = SMBSessionSetupAndX_Extended_Data()

        sessionSetup['Parameters']['MaxBufferSize']        = 65535
        sessionSetup['Parameters']['MaxMpxCount']          = 2
        sessionSetup['Parameters']['VcNumber']             = 1
        sessionSetup['Parameters']['SessionKey']           = 0
        sessionSetup['Parameters']['Capabilities'] = SMB.CAP_EXTENDED_SECURITY | SMB.CAP_USE_NT_ERRORS | SMB.CAP_UNICODE

        # Let's build a NegTokenInit with the NTLMSSP
        # TODO: In the future we should be able to choose different providers

        blob = SPNEGO_NegTokenInit() 

        # NTLMSSP
        blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]
        blob['MechToken'] = str(negotiateMessage)

        sessionSetup['Parameters']['SecurityBlobLength']  = len(blob)
        sessionSetup['Parameters'].getData()
        sessionSetup['Data']['SecurityBlob']       = blob.getData()

        # Fake Data here, don't want to get us fingerprinted
        sessionSetup['Data']['NativeOS']      = 'Unix'
        sessionSetup['Data']['NativeLanMan']  = 'Samba'

        smb.addCommand(sessionSetup)
        self.sendSMB(smb)
        smb = self.recvSMB()

        try:
            smb.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX)
        except Exception:
            logging.error("SessionSetup Error!")
            raise
        else:
            # We will need to use this uid field for all future requests/responses
            self._uid = smb['Uid']

            # Now we have to extract the blob to continue the auth process
            sessionResponse   = SMBCommand(smb['Data'][0])
            sessionParameters = SMBSessionSetupAndX_Extended_Response_Parameters(sessionResponse['Parameters'])
            sessionData       = SMBSessionSetupAndX_Extended_Response_Data(flags = smb['Flags2'])
            sessionData['SecurityBlobLength'] = sessionParameters['SecurityBlobLength']
            sessionData.fromString(sessionResponse['Data'])
            respToken = SPNEGO_NegTokenResp(sessionData['SecurityBlob'])

            return respToken['ResponseToken'] 
Example #16
Source File: smbrelayclient.py    From PiBunny with MIT License 4 votes vote down vote up
def sendNegotiate(self, negotiateMessage):
        smb = NewSMBPacket()
        smb['Flags1'] = SMB.FLAGS1_PATHCASELESS
        smb['Flags2'] = SMB.FLAGS2_EXTENDED_SECURITY 
        # Are we required to sign SMB? If so we do it, if not we skip it
        if self._SignatureRequired: 
           smb['Flags2'] |= SMB.FLAGS2_SMB_SECURITY_SIGNATURE
          

        sessionSetup = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX)
        sessionSetup['Parameters'] = SMBSessionSetupAndX_Extended_Parameters()
        sessionSetup['Data']       = SMBSessionSetupAndX_Extended_Data()

        sessionSetup['Parameters']['MaxBufferSize']        = 65535
        sessionSetup['Parameters']['MaxMpxCount']          = 2
        sessionSetup['Parameters']['VcNumber']             = 1
        sessionSetup['Parameters']['SessionKey']           = 0
        sessionSetup['Parameters']['Capabilities']         = SMB.CAP_EXTENDED_SECURITY | SMB.CAP_USE_NT_ERRORS | SMB.CAP_UNICODE

        # Let's build a NegTokenInit with the NTLMSSP
        # TODO: In the future we should be able to choose different providers

        blob = SPNEGO_NegTokenInit() 

        # NTLMSSP
        blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]
        blob['MechToken'] = str(negotiateMessage)

        sessionSetup['Parameters']['SecurityBlobLength']  = len(blob)
        sessionSetup['Parameters'].getData()
        sessionSetup['Data']['SecurityBlob']       = blob.getData()

        # Fake Data here, don't want to get us fingerprinted
        sessionSetup['Data']['NativeOS']      = 'Unix'
        sessionSetup['Data']['NativeLanMan']  = 'Samba'

        smb.addCommand(sessionSetup)
        self.sendSMB(smb)
        smb = self.recvSMB()

        try:
            smb.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX)
        except Exception:
            logging.error("SessionSetup Error!")
            raise
        else:
            # We will need to use this uid field for all future requests/responses
            self._uid = smb['Uid']

            # Now we have to extract the blob to continue the auth process
            sessionResponse   = SMBCommand(smb['Data'][0])
            sessionParameters = SMBSessionSetupAndX_Extended_Response_Parameters(sessionResponse['Parameters'])
            sessionData       = SMBSessionSetupAndX_Extended_Response_Data(flags = smb['Flags2'])
            sessionData['SecurityBlobLength'] = sessionParameters['SecurityBlobLength']
            sessionData.fromString(sessionResponse['Data'])
            respToken = SPNEGO_NegTokenResp(sessionData['SecurityBlob'])

            return respToken['ResponseToken'] 
Example #17
Source File: smbrelayclient.py    From CVE-2017-7494 with GNU General Public License v3.0 4 votes vote down vote up
def sendNegotiate(self, negotiateMessage):
        smb = NewSMBPacket()
        smb['Flags1'] = SMB.FLAGS1_PATHCASELESS
        smb['Flags2'] = SMB.FLAGS2_EXTENDED_SECURITY 
        # Are we required to sign SMB? If so we do it, if not we skip it
        if self._SignatureRequired: 
           smb['Flags2'] |= SMB.FLAGS2_SMB_SECURITY_SIGNATURE
          

        sessionSetup = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX)
        sessionSetup['Parameters'] = SMBSessionSetupAndX_Extended_Parameters()
        sessionSetup['Data']       = SMBSessionSetupAndX_Extended_Data()

        sessionSetup['Parameters']['MaxBufferSize']        = 65535
        sessionSetup['Parameters']['MaxMpxCount']          = 2
        sessionSetup['Parameters']['VcNumber']             = 1
        sessionSetup['Parameters']['SessionKey']           = 0
        sessionSetup['Parameters']['Capabilities']         = SMB.CAP_EXTENDED_SECURITY | SMB.CAP_USE_NT_ERRORS | SMB.CAP_UNICODE

        # Let's build a NegTokenInit with the NTLMSSP
        # TODO: In the future we should be able to choose different providers

        blob = SPNEGO_NegTokenInit() 

        # NTLMSSP
        blob['MechTypes'] = [TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']]
        blob['MechToken'] = str(negotiateMessage)

        sessionSetup['Parameters']['SecurityBlobLength']  = len(blob)
        sessionSetup['Parameters'].getData()
        sessionSetup['Data']['SecurityBlob']       = blob.getData()

        # Fake Data here, don't want to get us fingerprinted
        sessionSetup['Data']['NativeOS']      = 'Unix'
        sessionSetup['Data']['NativeLanMan']  = 'Samba'

        smb.addCommand(sessionSetup)
        self.sendSMB(smb)
        smb = self.recvSMB()

        try:
            smb.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX)
        except Exception:
            logging.error("SessionSetup Error!")
            raise
        else:
            # We will need to use this uid field for all future requests/responses
            self._uid = smb['Uid']

            # Now we have to extract the blob to continue the auth process
            sessionResponse   = SMBCommand(smb['Data'][0])
            sessionParameters = SMBSessionSetupAndX_Extended_Response_Parameters(sessionResponse['Parameters'])
            sessionData       = SMBSessionSetupAndX_Extended_Response_Data(flags = smb['Flags2'])
            sessionData['SecurityBlobLength'] = sessionParameters['SecurityBlobLength']
            sessionData.fromString(sessionResponse['Data'])
            respToken = SPNEGO_NegTokenResp(sessionData['SecurityBlob'])

            return respToken['ResponseToken']