diff options
-rw-r--r-- | docs/KNOWN_BUGS | 7 | ||||
-rw-r--r-- | tests/python_dependencies/impacket/nmb.py | 46 | ||||
-rw-r--r-- | tests/python_dependencies/impacket/ntlm.py | 78 | ||||
-rw-r--r-- | tests/python_dependencies/impacket/smb.py | 22 | ||||
-rw-r--r-- | tests/python_dependencies/impacket/smb3.py | 69 | ||||
-rw-r--r-- | tests/python_dependencies/impacket/smbserver.py | 228 | ||||
-rw-r--r-- | tests/python_dependencies/impacket/spnego.py | 154 | ||||
-rw-r--r-- | tests/python_dependencies/impacket/structure.py | 69 | ||||
-rw-r--r-- | tests/python_dependencies/impacket/uuid.py | 21 |
9 files changed, 352 insertions, 342 deletions
diff --git a/docs/KNOWN_BUGS b/docs/KNOWN_BUGS index 92956c617..67c7b1661 100644 --- a/docs/KNOWN_BUGS +++ b/docs/KNOWN_BUGS @@ -46,7 +46,6 @@ problems may have been fixed or changed somewhat since this was written! 4.5 Improve --data-urlencode space encoding 5. Build and portability issues - 5.1 tests not compatible with python3 5.2 curl-config --libs contains private details 5.3 curl compiled on OSX 10.13 failed to run on OSX 10.10 5.4 Cannot compile against a static build of OpenLDAP @@ -372,12 +371,6 @@ problems may have been fixed or changed somewhat since this was written! 5. Build and portability issues -5.1 tests not compatible with python3 - - The smb test server still needs python2. - - See https://github.com/curl/curl/issues/3289 - 5.2 curl-config --libs contains private details "curl-config --libs" will include details set in LDFLAGS when configure is diff --git a/tests/python_dependencies/impacket/nmb.py b/tests/python_dependencies/impacket/nmb.py index dc8777e65..791377bc2 100644 --- a/tests/python_dependencies/impacket/nmb.py +++ b/tests/python_dependencies/impacket/nmb.py @@ -1,3 +1,5 @@ +from __future__ import print_function +from __future__ import absolute_import # Copyright (c) 2003-2016 CORE Security Technologies # # This software is provided under under a slightly modified version @@ -40,7 +42,7 @@ from random import randint from struct import pack, unpack import time -from structure import Structure +from .structure import Structure CVS_REVISION = '$Revision: 526 $' @@ -454,7 +456,7 @@ class NetBIOS: except socket.error: pass if not has_bind: - raise NetBIOSError, ( 'Cannot bind to a good UDP port', ERRCLASS_OS, errno.EAGAIN ) + raise NetBIOSError( 'Cannot bind to a good UDP port', ERRCLASS_OS, errno.EAGAIN) self.__sock = s # Set the default NetBIOS domain nameserver. @@ -531,15 +533,15 @@ class NetBIOS: if res.get_rcode() == 0x03: return None else: - raise NetBIOSError, ( 'Negative name query response', ERRCLASS_QUERY, res.get_rcode() ) + raise NetBIOSError( 'Negative name query response', ERRCLASS_QUERY, res.get_rcode()) if res.get_ancount() != 1: raise NetBIOSError( 'Malformed response') return NBPositiveNameQueryResponse(res.get_answers()) - except select.error, ex: + except select.error as ex: if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: - raise NetBIOSError, ( 'Error occurs while waiting for response', ERRCLASS_OS, ex[0] ) + raise NetBIOSError( 'Error occurs while waiting for response', ERRCLASS_OS, ex[0]) raise @@ -570,25 +572,25 @@ class NetBIOS: else: try: data, _ = self.__sock.recvfrom(65536, 0) - except Exception, e: - raise NetBIOSError, "recvfrom error: %s" % str(e) + except Exception as e: + raise NetBIOSError("recvfrom error: %s" % str(e)) self.__sock.close() res = NetBIOSPacket(data) if res.get_trn_id() == p.get_trn_id(): if res.get_rcode(): if res.get_rcode() == 0x03: # I'm just guessing here - raise NetBIOSError, "Cannot get data from server" + raise NetBIOSError("Cannot get data from server") else: - raise NetBIOSError, ( 'Negative name query response', ERRCLASS_QUERY, res.get_rcode() ) + raise NetBIOSError( 'Negative name query response', ERRCLASS_QUERY, res.get_rcode()) answ = NBNodeStatusResponse(res.get_answers()) self.mac = answ.get_mac() return answ.get_node_names() - except select.error, ex: + except select.error as ex: if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: - raise NetBIOSError, ( 'Error occurs while waiting for response', ERRCLASS_OS, ex[0] ) - except socket.error, ex: - raise NetBIOSError, 'Connection error: %s' % str(ex) + raise NetBIOSError( 'Error occurs while waiting for response', ERRCLASS_OS, ex[0]) + except socket.error as ex: + raise NetBIOSError('Connection error: %s' % str(ex)) # Perform first and second level encoding of name as specified in RFC 1001 (Section 4) def encode_name(name, type, scope): @@ -841,7 +843,7 @@ class NetBIOSTCPSession(NetBIOSSession): af, socktype, proto, canonname, sa = socket.getaddrinfo(peer[0], peer[1], 0, socket.SOCK_STREAM)[0] sock = socket.socket(af, socktype, proto) sock.connect(sa) - except socket.error, e: + except socket.error as e: raise socket.error("Connection error (%s:%s)" % (peer[0], peer[1]), e) return sock @@ -866,7 +868,7 @@ class NetBIOSTCPSession(NetBIOSSession): while 1: p = self.recv_packet(timeout) if p.get_type() == NETBIOS_SESSION_NEGATIVE_RESPONSE: - raise NetBIOSError, ( 'Cannot request session', ERRCLASS_SESSION, ord(p.get_trailer()[0]) ) + raise NetBIOSError( 'Cannot request session', ERRCLASS_SESSION, ord(p.get_trailer()[0])) elif p.get_type() == NETBIOS_SESSION_POSITIVE_RESPONSE: break else: @@ -896,13 +898,13 @@ class NetBIOSTCPSession(NetBIOSSession): received = self._sock.recv(bytes_left) if len(received) == 0: - raise NetBIOSError, ( 'Error while reading from remote', ERRCLASS_OS, None) + raise NetBIOSError( 'Error while reading from remote', ERRCLASS_OS, None) data = data + received bytes_left = read_length - len(data) - except select.error, ex: + except select.error as ex: if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: - raise NetBIOSError, ( 'Error occurs while reading from remote', ERRCLASS_OS, ex[0] ) + raise NetBIOSError( 'Error occurs while reading from remote', ERRCLASS_OS, ex[0]) return data @@ -919,13 +921,13 @@ class NetBIOSTCPSession(NetBIOSSession): received = self._sock.recv(bytes_left) if len(received) == 0: - raise NetBIOSError, ( 'Error while reading from remote', ERRCLASS_OS, None) + raise NetBIOSError( 'Error while reading from remote', ERRCLASS_OS, None) data = data + received bytes_left = read_length - len(data) - except select.error, ex: + except select.error as ex: if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: - raise NetBIOSError, ( 'Error occurs while reading from remote', ERRCLASS_OS, ex[0] ) + raise NetBIOSError( 'Error occurs while reading from remote', ERRCLASS_OS, ex[0]) return data @@ -974,7 +976,7 @@ def main(): n = get_netbios_host_by_name("some-host") - print n + print(n) if __name__ == '__main__': main() diff --git a/tests/python_dependencies/impacket/ntlm.py b/tests/python_dependencies/impacket/ntlm.py index 8376644bd..8845e9d50 100644 --- a/tests/python_dependencies/impacket/ntlm.py +++ b/tests/python_dependencies/impacket/ntlm.py @@ -1,3 +1,4 @@ +from __future__ import print_function # Copyright (c) 2003-2016 CORE Security Technologies: # # This software is provided under under a slightly modified version @@ -17,8 +18,8 @@ from impacket.structure import Structure from impacket import LOG -# This is important. NTLMv2 is not negotiated by the client or server. -# It is used if set locally on both sides. Change this item if you don't want to use +# This is important. NTLMv2 is not negotiated by the client or server. +# It is used if set locally on both sides. Change this item if you don't want to use # NTLMv2 by default and fall back to NTLMv1 (with EXTENDED_SESSION_SECURITY or not) # Check the following links: # http://davenport.sourceforge.net/ntlm.html @@ -209,7 +210,7 @@ class AV_PAIRS(): self.fields[key] = (len(value),value) def __getitem__(self, key): - if self.fields.has_key(key): + if key in self.fields: return self.fields[key] return None @@ -236,16 +237,16 @@ class AV_PAIRS(): def dump(self): for i in self.fields.keys(): - print "%s: {%r}" % (i,self[i]) + print("%s: {%r}" % (i,self[i])) def getData(self): - if self.fields.has_key(NTLMSSP_AV_EOL): + if NTLMSSP_AV_EOL in self.fields: del self.fields[NTLMSSP_AV_EOL] ans = '' for i in self.fields.keys(): ans+= struct.pack('<HH', i, self[i][0]) ans+= self[i][1] - + # end with a NTLMSSP_AV_EOL ans += struct.pack('<HH', NTLMSSP_AV_EOL, 0) @@ -260,7 +261,7 @@ class NTLMAuthMixin: minor_v = struct.unpack('B',self['os_version'][1])[0] build_v = struct.unpack('H',self['os_version'][2:4]) return (mayor_v,minor_v,build_v) - + class NTLMAuthNegotiate(Structure, NTLMAuthMixin): structure = ( @@ -276,7 +277,7 @@ class NTLMAuthNegotiate(Structure, NTLMAuthMixin): ('os_version',':'), ('host_name',':'), ('domain_name',':')) - + def __init__(self): Structure.__init__(self) self['flags']= ( @@ -293,7 +294,7 @@ class NTLMAuthNegotiate(Structure, NTLMAuthMixin): self['host_name']='' self['domain_name']='' self['os_version']='' - + def getData(self): if len(self.fields['host_name']) > 0: self['flags'] |= NTLMSSP_NEGOTIATE_OEM_WORKSTATION_SUPPLIED @@ -342,7 +343,7 @@ class NTLMAuthChallenge(Structure): ('TargetInfoFields_len','<H-TargetInfoFields'), ('TargetInfoFields_max_len','<H-TargetInfoFields'), ('TargetInfoFields_offset','<L'), - ('VersionLen','_-Version','self.checkVersion(self["flags"])'), + ('VersionLen','_-Version','self.checkVersion(self["flags"])'), ('Version',':'), ('domain_name',':'), ('TargetInfoFields',':')) @@ -365,11 +366,11 @@ class NTLMAuthChallenge(Structure): self['TargetInfoFields'] = self['TargetInfoFields'][:self['TargetInfoFields_len']] # We gotta process the TargetInfoFields #if self['TargetInfoFields_len'] > 0: - # av_pairs = AV_PAIRS(self['TargetInfoFields'][:self['TargetInfoFields_len']]) + # av_pairs = AV_PAIRS(self['TargetInfoFields'][:self['TargetInfoFields_len']]) # self['TargetInfoFields'] = av_pairs return self - + class NTLMAuthChallengeResponse(Structure, NTLMAuthMixin): structure = ( @@ -394,7 +395,7 @@ class NTLMAuthChallengeResponse(Structure, NTLMAuthMixin): ('session_key_max_len','<H-session_key'), ('session_key_offset','<L'), ('flags','<L'), - ('VersionLen','_-Version','self.checkVersion(self["flags"])'), + ('VersionLen','_-Version','self.checkVersion(self["flags"])'), ('Version',':=""'), ('MICLen','_-MIC','self.checkMIC(self["flags"])'), ('MIC',':=""'), @@ -424,7 +425,7 @@ class NTLMAuthChallengeResponse(Structure, NTLMAuthMixin): # NTLMSSP_TARGET | 0) # Here we do the stuff - if username and ( lmhash != '' or nthash != ''): + if username and ( lmhash != '' or nthash != ''): self['lanman'] = get_ntlmv1_response(lmhash, challenge) self['ntlm'] = get_ntlmv1_response(nthash, challenge) elif (username and password): @@ -450,7 +451,7 @@ class NTLMAuthChallengeResponse(Structure, NTLMAuthMixin): if flags & NTLMSSP_NEGOTIATE_VERSION == 0: return 0 return 16 - + def getData(self): self['domain_offset']=64+self.checkMIC(self["flags"])+self.checkVersion(self["flags"]) self['user_offset']=64+self.checkMIC(self["flags"])+self.checkVersion(self["flags"])+len(self['domain_name']) @@ -463,7 +464,7 @@ class NTLMAuthChallengeResponse(Structure, NTLMAuthMixin): def fromString(self,data): Structure.fromString(self,data) # [MS-NLMP] page 27 - # Payload data can be present in any order within the Payload field, + # Payload data can be present in any order within the Payload field, # with variable-length padding before or after the data domain_offset = self['domain_offset'] @@ -478,15 +479,15 @@ class NTLMAuthChallengeResponse(Structure, NTLMAuthMixin): user_end = self['user_len'] + user_offset self['user_name'] = data[ user_offset: user_end ] - ntlm_offset = self['ntlm_offset'] - ntlm_end = self['ntlm_len'] + ntlm_offset + ntlm_offset = self['ntlm_offset'] + ntlm_end = self['ntlm_len'] + ntlm_offset self['ntlm'] = data[ ntlm_offset : ntlm_end ] - lanman_offset = self['lanman_offset'] + lanman_offset = self['lanman_offset'] lanman_end = self['lanman_len'] + lanman_offset self['lanman'] = data[ lanman_offset : lanman_end] - #if len(data) >= 36: + #if len(data) >= 36: # self['os_version'] = data[32:36] #else: # self['os_version'] = '' @@ -607,11 +608,11 @@ def getNTLMSSPType3(type1, type2, user, password, domain, lmhash = '', nthash = # Let's start with the original flags sent in the type1 message responseFlags = type1['flags'] - # Token received and parsed. Depending on the authentication + # Token received and parsed. Depending on the authentication # method we will create a valid ChallengeResponse ntlmChallengeResponse = NTLMAuthChallengeResponse(user, password, ntlmChallenge['challenge']) - clientChallenge = "".join([random.choice(string.digits+string.letters) for i in xrange(8)]) + clientChallenge = "".join([random.choice(string.digits+string.letters) for i in range(8)]) serverName = ntlmChallenge['TargetInfoFields'] @@ -647,7 +648,7 @@ def getNTLMSSPType3(type1, type2, user, password, domain, lmhash = '', nthash = if ntlmChallenge['flags'] & NTLMSSP_NEGOTIATE_KEY_EXCH: # not exactly what I call random tho :\ # exportedSessionKey = this is the key we should use to sign - exportedSessionKey = "".join([random.choice(string.digits+string.letters) for i in xrange(16)]) + exportedSessionKey = "".join([random.choice(string.digits+string.letters) for i in range(16)]) #exportedSessionKey = "A"*16 #print "keyExchangeKey %r" % keyExchangeKey # Let's generate the right session key based on the challenge flags @@ -677,7 +678,7 @@ def getNTLMSSPType3(type1, type2, user, password, domain, lmhash = '', nthash = ntlmChallengeResponse['domain_name'] = domain.encode('utf-16le') ntlmChallengeResponse['lanman'] = lmResponse ntlmChallengeResponse['ntlm'] = ntResponse - if encryptedRandomSessionKey is not None: + if encryptedRandomSessionKey is not None: ntlmChallengeResponse['session_key'] = encryptedRandomSessionKey return ntlmChallengeResponse, exportedSessionKey @@ -688,13 +689,13 @@ def getNTLMSSPType3(type1, type2, user, password, domain, lmhash = '', nthash = def generateSessionKeyV1(password, lmhash, nthash): if POW: hash = POW.Digest(POW.MD4_DIGEST) - else: + else: hash = MD4.new() hash.update(NTOWFv1(password, lmhash, nthash)) return hash.digest() - + def computeResponseNTLMv1(flags, serverChallenge, clientChallenge, serverName, domain, user, password, lmhash='', nthash='', use_ntlmv2 = USE_NTLMv2): - if (user == '' and password == ''): + if (user == '' and password == ''): # Special case for anonymous authentication lmResponse = '' ntResponse = '' @@ -713,7 +714,7 @@ def computeResponseNTLMv1(flags, serverChallenge, clientChallenge, serverName, d else: ntResponse = get_ntlmv1_response(nthash,serverChallenge) lmResponse = get_ntlmv1_response(lmhash, serverChallenge) - + sessionBaseKey = generateSessionKeyV1(password, lmhash, nthash) return ntResponse, lmResponse, sessionBaseKey @@ -727,7 +728,7 @@ def compute_lmhash(password): def NTOWFv1(password, lmhash = '', nthash=''): if nthash != '': return nthash - return compute_nthash(password) + return compute_nthash(password) def LMOWFv1(password, lmhash = '', nthash=''): if lmhash != '': @@ -738,13 +739,15 @@ def compute_nthash(password): # This is done according to Samba's encryption specification (docs/html/ENCRYPTION.html) try: password = unicode(password).encode('utf_16le') + except NameError: # unicode() was removed in Python 3 + password = str(password).encode('utf_16le') except UnicodeDecodeError: import sys password = password.decode(sys.getfilesystemencoding()).encode('utf_16le') if POW: hash = POW.Digest(POW.MD4_DIGEST) - else: + else: hash = MD4.new() hash.update(password) return hash.digest() @@ -780,7 +783,7 @@ def MAC(flags, handle, signingKey, seqNum, message): messageSignature['SeqNum'] = handle('\x00\x00\x00\x00') messageSignature['SeqNum'] = struct.unpack('<i',messageSignature['SeqNum'])[0] ^ seqNum messageSignature['RandomPad'] = 0 - + return messageSignature def SEAL(flags, signingKey, sealingKey, messageToSign, messageToEncrypt, seqNum, handle): @@ -863,7 +866,7 @@ def KXKEY(flags, sessionBaseKey, lmChallengeResponse, serverChallenge, password, raise "Can't create a valid KXKEY!" return keyExchangeKey - + def hmac_md5(key, data): if POW: h = POW.Hmac(POW.MD5_DIGEST, key) @@ -878,7 +881,7 @@ def hmac_md5(key, data): def NTOWFv2( user, password, domain, hash = ''): if hash != '': - theHash = hash + theHash = hash else: theHash = compute_nthash(password) return hmac_md5(theHash, user.upper().encode('utf-16le') + domain.encode('utf-16le')) @@ -907,7 +910,7 @@ def computeResponseNTLMv2(flags, serverChallenge, clientChallenge, serverName, #aTime = '\x00'*8 av_pairs[NTLMSSP_AV_TIME] = aTime serverName = av_pairs.getData() - + ###################### #aTime = '\x00'*8 ###################### @@ -937,20 +940,20 @@ class NTLM_HTTP(object): if msg_64 != '': msg = base64.b64decode(msg_64[5:]) # Remove the 'NTLM ' msg_type = ord(msg[8]) - + for _cls in NTLM_HTTP.__subclasses__(): if msg_type == _cls.MSG_TYPE: instance = _cls() instance.fromString(msg) return instance - + class NTLM_HTTP_AuthRequired(NTLM_HTTP): commonHdr = () # Message 0 means the first HTTP request e.g. 'GET /bla.png' MSG_TYPE = 0 - def fromString(self,data): + def fromString(self,data): pass @@ -968,4 +971,3 @@ class NTLM_HTTP_AuthChallengeResponse(NTLM_HTTP, NTLMAuthChallengeResponse): def __init__(self): NTLMAuthChallengeResponse.__init__(self) - diff --git a/tests/python_dependencies/impacket/smb.py b/tests/python_dependencies/impacket/smb.py index 95efb2c63..c4ea6fc68 100644 --- a/tests/python_dependencies/impacket/smb.py +++ b/tests/python_dependencies/impacket/smb.py @@ -629,9 +629,9 @@ class SharedFile: @staticmethod def __convert_smbtime(t): x = t >> 32 - y = t & 0xffffffffL + y = t & 0xffffffff geo_cal_offset = 11644473600.0 # = 369.0 * 365.25 * 24 * 60 * 60 - (3.0 * 24 * 60 * 60 + 6.0 * 60 * 60) - return (x * 4.0 * (1 << 30) + (y & 0xfff00000L)) * 1.0e-7 - geo_cal_offset + return (x * 4.0 * (1 << 30) + (y & 0xfff00000)) * 1.0e-7 - geo_cal_offset # Contain information about a SMB machine @@ -676,12 +676,12 @@ class NewSMBPacket(Structure): def __init__(self, **kargs): Structure.__init__(self, **kargs) - if self.fields.has_key('Flags2') is False: + if ('Flags2' in self.fields) is False: self['Flags2'] = 0 - if self.fields.has_key('Flags1') is False: + if ('Flags1' in self.fields) is False: self['Flags1'] = 0 - if not kargs.has_key('data'): + if 'data' not in kargs: self['Data'] = [] def addCommand(self, command): @@ -709,9 +709,9 @@ class NewSMBPacket(Structure): return 1 elif self.isMoreProcessingRequired(): return 1 - raise SessionError, ("SMB Library Error", self['ErrorClass'] + (self['_reserved'] << 8), self['ErrorCode'], self['Flags2'] & SMB.FLAGS2_NT_STATUS) + raise SessionError("SMB Library Error", self['ErrorClass'] + (self['_reserved'] << 8), self['ErrorCode'], self['Flags2'] & SMB.FLAGS2_NT_STATUS) else: - raise UnsupportedFeature, ("Unexpected answer from server: Got %d, Expected %d" % (self['Command'], cmd)) + raise UnsupportedFeature("Unexpected answer from server: Got %d, Expected %d" % (self['Command'], cmd)) class SMBCommand(Structure): @@ -2550,7 +2550,7 @@ class SMB: if s.get_error_class() == 0x00 and s.get_error_code() == 0x00: return 1 else: - raise SessionError, ( "SMB Library Error", s.get_error_class()+ (s.get_reserved() << 8), s.get_error_code() , s.get_flags2() & SMB.FLAGS2_NT_STATUS ) + raise SessionError( "SMB Library Error", s.get_error_class()+ (s.get_reserved() << 8), s.get_error_code() , s.get_flags2() & SMB.FLAGS2_NT_STATUS) else: break return 0 @@ -2583,7 +2583,7 @@ class SMB: self.__server_name = self._dialects_data['ServerName'] if self._dialects_parameters['DialectIndex'] == 0xffff: - raise UnsupportedFeature,"Remote server does not know NT LM 0.12" + raise UnsupportedFeature("Remote server does not know NT LM 0.12") return 1 else: return 0 @@ -2734,7 +2734,7 @@ class SMB: self._SigningSessionKey = key def get_encryption_key(self): - if self._dialects_data.fields.has_key('Challenge'): + if 'Challenge' in self._dialects_data.fields: return self._dialects_data['Challenge'] else: return None @@ -3241,7 +3241,7 @@ class SMB: pass # Parse Version to know the target Operating system name. Not provided elsewhere anymore - if ntlmChallenge.fields.has_key('Version'): + if 'Version' in ntlmChallenge.fields: version = ntlmChallenge['Version'] if len(version) >= 4: diff --git a/tests/python_dependencies/impacket/smb3.py b/tests/python_dependencies/impacket/smb3.py index 5548e4b0c..d81c7e117 100644 --- a/tests/python_dependencies/impacket/smb3.py +++ b/tests/python_dependencies/impacket/smb3.py @@ -1,3 +1,4 @@ +from __future__ import print_function # Copyright (c) 2003-2016 CORE Security Technologies # # This software is provided under under a slightly modified version @@ -231,13 +232,13 @@ class SMB3: self.negotiateSession(preferredDialect) def printStatus(self): - print "CONNECTION" + print("CONNECTION") for i in self._Connection.items(): - print "%-40s : %s" % i - print - print "SESSION" + print("%-40s : %s" % i) + print() + print("SESSION") for i in self._Session.items(): - print "%-40s : %s" % i + print("%-40s : %s" % i) def getServerName(self): return self._Session['ServerName'] @@ -308,7 +309,7 @@ class SMB3: packet['SessionID'] = self._Session['SessionID'] # Default the credit charge to 1 unless set by the caller - if packet.fields.has_key('CreditCharge') is False: + if ('CreditCharge' in packet.fields) is False: packet['CreditCharge'] = 1 # Standard credit request after negotiating protocol @@ -318,7 +319,7 @@ class SMB3: messageId = packet['MessageID'] if self._Session['SigningActivated'] is True and self._Connection['SequenceWindow'] > 2: - if packet['TreeID'] > 0 and self._Session['TreeConnectTable'].has_key(packet['TreeID']) is True: + if packet['TreeID'] > 0 and (packet['TreeID'] in self._Session['TreeConnectTable']) is True: if self._Session['TreeConnectTable'][packet['TreeID']]['EncryptData'] is False: packet['Flags'] = SMB2_FLAGS_SIGNED self.signSMB(packet) @@ -350,7 +351,7 @@ class SMB3: def recvSMB(self, packetID = None): # First, verify we don't have the packet already - if self._Connection['OutstandingResponses'].has_key(packetID): + if packetID in self._Connection['OutstandingResponses']: return self._Connection['OutstandingResponses'].pop(packetID) data = self._NetBIOSSession.recv_packet(self._timeout) @@ -727,7 +728,7 @@ class SMB3: pass # Parse Version to know the target Operating system name. Not provided elsewhere anymore - if ntlmChallenge.fields.has_key('Version'): + if 'Version' in ntlmChallenge.fields: version = ntlmChallenge['Version'] if len(version) >= 4: @@ -785,7 +786,7 @@ class SMB3: #print self._Session['TreeConnectTable'] share = share.split('\\')[-1] - if self._Session['TreeConnectTable'].has_key(share): + if share in self._Session['TreeConnectTable']: # Already connected, no need to reconnect treeEntry = self._Session['TreeConnectTable'][share] treeEntry['NumberOfUses'] += 1 @@ -837,10 +838,10 @@ class SMB3: return packet['TreeID'] def disconnectTree(self, treeId): - if self._Session['TreeConnectTable'].has_key(treeId) is False: + if (treeId in self._Session['TreeConnectTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) - if self._Session['TreeConnectTable'].has_key(treeId): + if treeId in self._Session['TreeConnectTable']: # More than 1 use? descrease it and return, if not, send the packet if self._Session['TreeConnectTable'][treeId]['NumberOfUses'] > 1: treeEntry = self._Session['TreeConnectTable'][treeId] @@ -862,7 +863,7 @@ class SMB3: return True def create(self, treeId, fileName, desiredAccess, shareMode, creationOptions, creationDisposition, fileAttributes, impersonationLevel = SMB2_IL_IMPERSONATION, securityFlags = 0, oplockLevel = SMB2_OPLOCK_LEVEL_NONE, createContexts = None): - if self._Session['TreeConnectTable'].has_key(treeId) is False: + if (treeId in self._Session['TreeConnectTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) fileName = string.replace(fileName, '/', '\\') @@ -885,7 +886,7 @@ class SMB3: # Is this file NOT on the root directory? if len(fileName.split('\\')) > 2: parentDir = ntpath.dirname(pathName) - if self.GlobalFileTable.has_key(parentDir): + if parentDir in self.GlobalFileTable: LOG.critical("Don't know what to do now! :-o") raise else: @@ -957,9 +958,9 @@ class SMB3: return str(createResponse['FileID']) def close(self, treeId, fileId): - if self._Session['TreeConnectTable'].has_key(treeId) is False: + if (treeId in self._Session['TreeConnectTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) - if self._Session['OpenTable'].has_key(fileId) is False: + if (fileId in self._Session['OpenTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) packet = self.SMB_PACKET() @@ -988,9 +989,9 @@ class SMB3: # This function should NOT be used for reading files directly, but another higher # level function should be used that will break the read into smaller pieces - if self._Session['TreeConnectTable'].has_key(treeId) is False: + if (treeId in self._Session['TreeConnectTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) - if self._Session['OpenTable'].has_key(fileId) is False: + if (fileId in self._Session['OpenTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) packet = self.SMB_PACKET() @@ -1030,9 +1031,9 @@ class SMB3: # This function should NOT be used for writing directly to files, but another higher # level function should be used that will break the writes into smaller pieces - if self._Session['TreeConnectTable'].has_key(treeId) is False: + if (treeId in self._Session['TreeConnectTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) - if self._Session['OpenTable'].has_key(fileId) is False: + if (fileId in self._Session['OpenTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) packet = self.SMB_PACKET() @@ -1071,9 +1072,9 @@ class SMB3: return bytesWritten def queryDirectory(self, treeId, fileId, searchString = '*', resumeIndex = 0, informationClass = FILENAMES_INFORMATION, maxBufferSize = None, enumRestart = False, singleEntry = False): - if self._Session['TreeConnectTable'].has_key(treeId) is False: + if (treeId in self._Session['TreeConnectTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) - if self._Session['OpenTable'].has_key(fileId) is False: + if (fileId in self._Session['OpenTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) packet = self.SMB_PACKET() @@ -1124,12 +1125,12 @@ class SMB3: self.sendSMB(packet) def ioctl(self, treeId, fileId = None, ctlCode = -1, flags = 0, inputBlob = '', maxInputResponse = None, maxOutputResponse = None, waitAnswer = 1): - if self._Session['TreeConnectTable'].has_key(treeId) is False: + if (treeId in self._Session['TreeConnectTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) if fileId is None: fileId = '\xff'*16 else: - if self._Session['OpenTable'].has_key(fileId) is False: + if (fileId in self._Session['OpenTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) packet = self.SMB_PACKET() @@ -1165,9 +1166,9 @@ class SMB3: return smbIoctlResponse['Buffer'] def flush(self,treeId, fileId): - if self._Session['TreeConnectTable'].has_key(treeId) is False: + if (treeId in self._Session['TreeConnectTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) - if self._Session['OpenTable'].has_key(fileId) is False: + if (fileId in self._Session['OpenTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) packet = self.SMB_PACKET() @@ -1186,9 +1187,9 @@ class SMB3: return True def lock(self, treeId, fileId, locks, lockSequence = 0): - if self._Session['TreeConnectTable'].has_key(treeId) is False: + if (treeId in self._Session['TreeConnectTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) - if self._Session['OpenTable'].has_key(fileId) is False: + if (fileId in self._Session['OpenTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) packet = self.SMB_PACKET() @@ -1248,9 +1249,9 @@ class SMB3: return True def queryInfo(self, treeId, fileId, inputBlob = '', infoType = SMB2_0_INFO_FILE, fileInfoClass = SMB2_FILE_STANDARD_INFO, additionalInformation = 0, flags = 0 ): - if self._Session['TreeConnectTable'].has_key(treeId) is False: + if (treeId in self._Session['TreeConnectTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) - if self._Session['OpenTable'].has_key(fileId) is False: + if (fileId in self._Session['OpenTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) packet = self.SMB_PACKET() @@ -1280,9 +1281,9 @@ class SMB3: return queryResponse['Buffer'] def setInfo(self, treeId, fileId, inputBlob = '', infoType = SMB2_0_INFO_FILE, fileInfoClass = SMB2_FILE_STANDARD_INFO, additionalInformation = 0 ): - if self._Session['TreeConnectTable'].has_key(treeId) is False: + if (treeId in self._Session['TreeConnectTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) - if self._Session['OpenTable'].has_key(fileId) is False: + if (fileId in self._Session['OpenTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) packet = self.SMB_PACKET() @@ -1385,7 +1386,7 @@ class SMB3: files.append(smb.SharedFile(fileInfo['CreationTime'],fileInfo['LastAccessTime'],fileInfo['LastChangeTime'],fileInfo['EndOfFile'],fileInfo['AllocationSize'],fileInfo['ExtFileAttributes'],fileInfo['FileName'].decode('utf-16le'), fileInfo['FileName'].decode('utf-16le'))) nextOffset = fileInfo['NextEntryOffset'] res = res[nextOffset:] - except SessionError, e: + except SessionError as e: if (e.get_error_code()) != STATUS_NO_MORE_FILES: raise break @@ -1512,7 +1513,7 @@ class SMB3: def waitNamedPipe(self, treeId, pipename, timeout = 5): pipename = ntpath.basename(pipename) - if self._Session['TreeConnectTable'].has_key(treeId) is False: + if (treeId in self._Session['TreeConnectTable']) is False: raise SessionError(STATUS_INVALID_PARAMETER) if len(pipename) > 0xffff: raise SessionError(STATUS_INVALID_PARAMETER) diff --git a/tests/python_dependencies/impacket/smbserver.py b/tests/python_dependencies/impacket/smbserver.py index aa795e52e..3473c9f0c 100644 --- a/tests/python_dependencies/impacket/smbserver.py +++ b/tests/python_dependencies/impacket/smbserver.py @@ -54,6 +54,12 @@ from impacket.nt_errors import STATUS_NO_MORE_FILES, STATUS_NETWORK_NAME_DELETED STATUS_SMB_BAD_UID = 0x005B0002 STATUS_SMB_BAD_TID = 0x00050002 +try: + unicode # Python 2 +except NameError: + unicode = str # Python 3 + + # Utility functions # and general functions. # There are some common functions that can be accessed from more than one SMB @@ -80,7 +86,7 @@ def outputToJohnFormat(challenge, username, domain, lmresponse, ntresponse): else: # NTLMv1 ret_value = {'hash_string':'%s::%s:%s:%s:%s' % (username, domain, hexlify(lmresponse), hexlify(ntresponse), hexlify(challenge)), 'hash_version':'ntlm'} - except Exception, e: + except Exception as e: LOG.error("outputToJohnFormat: %s" % e) pass @@ -183,7 +189,7 @@ def openFile(path,fileName, accessMode, fileAttributes, openMode): if sys.platform == 'win32': mode |= os.O_BINARY fid = os.open(pathName, mode) - except Exception, e: + except Exception as e: LOG.error("openFile: %s,%s" % (pathName, mode) ,e) fid = 0 errorCode = STATUS_ACCESS_DENIED @@ -442,7 +448,7 @@ def queryPathInformation(path, filename, level): else: # NOT FOUND return None, STATUS_OBJECT_NAME_NOT_FOUND - except Exception, e: + except Exception as e: LOG.error('queryPathInfo: %s' % e) raise @@ -486,7 +492,7 @@ class TRANSCommands: # (beto) If offset == 0 it crashes explorer.exe on windows 7 entry['RemarkOffsetLow'] = 20 * len(shares) + len(tailData) respData += entry.getData() - if shares[i].has_key('comment'): + if 'comment' in shares[i]: tailData += shares[i]['comment'] + '\x00' else: tailData += '\x00' @@ -511,7 +517,7 @@ class TRANSCommands: shareInfo['NetworkName'] = request['ShareName'].upper() + '\x00' shareInfo['Type'] = int(share['share type']) respData = shareInfo.getData() - if share.has_key('comment'): + if 'comment' in share: shareInfo['RemarkOffsetLow'] = len(respData) respData += share['comment'] + '\x00' respParameters['TotalBytesAvailable'] = len(respData) @@ -538,7 +544,7 @@ class TRANSCommands: # Extract the FID fid = struct.unpack('<H', transParameters['Setup'][2:])[0] - if connData['OpenedFiles'].has_key(fid): + if fid in connData['OpenedFiles']: fileHandle = connData['OpenedFiles'][fid]['FileHandle'] if fileHandle != PIPE_FILE_DESCRIPTOR: os.write(fileHandle,data) @@ -566,7 +572,7 @@ class TRANS2Commands: respData = '' errorCode = STATUS_SUCCESS setPathInfoParameters = smb.SMBSetPathInformation_Parameters(flags = recvPacket['Flags2'], data = parameters) - if connData['ConnectedShares'].has_key(recvPacket['Tid']): + if recvPacket['Tid'] in connData['ConnectedShares']: path = connData['ConnectedShares'][recvPacket['Tid']]['path'] fileName = decodeSMBString(recvPacket['Flags2'], setPathInfoParameters['FileName']) fileName = os.path.normpath(fileName.replace('\\','/')) @@ -619,8 +625,8 @@ class TRANS2Commands: errorCode = STATUS_SUCCESS setFileInfoParameters = smb.SMBSetFileInformation_Parameters(parameters) - if connData['ConnectedShares'].has_key(recvPacket['Tid']): - if connData['OpenedFiles'].has_key(setFileInfoParameters['FID']): + if recvPacket['Tid'] in connData['ConnectedShares']: + if setFileInfoParameters['FID'] in connData['OpenedFiles']: fileName = connData['OpenedFiles'][setFileInfoParameters['FID']]['FileName'] informationLevel = setFileInfoParameters['InformationLevel'] if informationLevel == smb.SMB_SET_FILE_DISPOSITION_INFO: @@ -675,8 +681,8 @@ class TRANS2Commands: queryFileInfoParameters = smb.SMBQueryFileInformation_Parameters(parameters) - if connData['ConnectedShares'].has_key(recvPacket['Tid']): - if connData['OpenedFiles'].has_key(queryFileInfoParameters['FID']): + if recvPacket['Tid'] in connData['ConnectedShares']: + if queryFileInfoParameters['FID'] in connData['OpenedFiles']: fileName = connData['OpenedFiles'][queryFileInfoParameters['FID']]['FileName'] infoRecord, errorCode = queryFileInformation('', fileName, queryFileInfoParameters['InformationLevel']) @@ -704,11 +710,11 @@ class TRANS2Commands: queryPathInfoParameters = smb.SMBQueryPathInformation_Parameters(flags = recvPacket['Flags2'], data = parameters) - if connData['ConnectedShares'].has_key(recvPacket['Tid']): + if recvPacket['Tid'] in connData['ConnectedShares']: path = connData['ConnectedShares'][recvPacket['Tid']]['path'] try: infoRecord, errorCode = queryPathInformation(path, decodeSMBString(recvPacket['Flags2'], queryPathInfoParameters['FileName']), queryPathInfoParameters['InformationLevel']) - except Exception, e: + except Exception as e: smbServer.log("queryPathInformation: %s" % e,logging.ERROR) if infoRecord is not None: @@ -726,7 +732,7 @@ class TRANS2Commands: connData = smbServer.getConnectionData(connId) errorCode = 0 # Get the Tid associated - if connData['ConnectedShares'].has_key(recvPacket['Tid']): + if recvPacket['Tid'] in connData['ConnectedShares']: data = queryFsInformation(connData['ConnectedShares'][recvPacket['Tid']]['path'], '', struct.unpack('<H',parameters)[0]) smbServer.setConnectionData(connId, connData) @@ -744,8 +750,8 @@ class TRANS2Commands: findNext2Parameters = smb.SMBFindNext2_Parameters(flags = recvPacket['Flags2'], data = parameters) sid = findNext2Parameters['SID'] - if connData['ConnectedShares'].has_key(recvPacket['Tid']): - if connData['SIDs'].has_key(sid): + if recvPacket['Tid'] in connData['ConnectedShares']: + if sid in connData['SIDs']: searchResult = connData['SIDs'][sid] respParameters = smb.SMBFindNext2Response_Parameters() endOfSearch = 1 @@ -790,7 +796,7 @@ class TRANS2Commands: respData = '' findFirst2Parameters = smb.SMBFindFirst2_Parameters( recvPacket['Flags2'], data = parameters) - if connData['ConnectedShares'].has_key(recvPacket['Tid']): + if recvPacket['Tid'] in connData['ConnectedShares']: path = connData['ConnectedShares'][recvPacket['Tid']]['path'] searchResult, searchCount, errorCode = findFirst2(path, @@ -881,7 +887,7 @@ class SMBCommands: else: command = struct.unpack('<H', transParameters['Setup'][:2])[0] - if transCommands.has_key(command): + if command in transCommands: # Call the TRANS subcommand setup = '' parameters = '' @@ -893,7 +899,7 @@ class SMBCommands: transData['Trans_Parameters'], transData['Trans_Data'], transParameters['MaxDataCount']) - except Exception, e: + except Exception as e: #print 'Transaction: %s' % e,e smbServer.log('Transaction: (%r,%s)' % (command, e), logging.ERROR) errorCode = STATUS_ACCESS_DENIED @@ -1018,7 +1024,7 @@ class SMBCommands: # Call the handler for this TRANSACTION command = NTTransParameters['Function'] - if transCommands.has_key(command): + if command in transCommands: # Call the NT TRANS subcommand setup = '' parameters = '' @@ -1030,7 +1036,7 @@ class SMBCommands: NTTransData['NT_Trans_Parameters'], NTTransData['NT_Trans_Data'], NTTransParameters['MaxDataCount']) - except Exception, e: + except Exception as e: smbServer.log('NTTransaction: (0x%x,%s)' % (command, e), logging.ERROR) errorCode = STATUS_ACCESS_DENIED #raise @@ -1157,7 +1163,7 @@ class SMBCommands: # Call the handler for this TRANSACTION command = struct.unpack('<H', trans2Parameters['Setup'])[0] - if transCommands.has_key(command): + if command in transCommands: # Call the TRANS2 subcommand try: setup, parameters, data, errorCode = transCommands[command](connId, @@ -1166,7 +1172,7 @@ class SMBCommands: trans2Data['Trans_Parameters'], trans2Data['Trans_Data'], trans2Parameters['MaxDataCount']) - except Exception, e: + except Exception as e: smbServer.log('Transaction2: (0x%x,%s)' % (command, e), logging.ERROR) #import traceback #traceback.print_exc() @@ -1282,7 +1288,7 @@ class SMBCommands: comClose = smb.SMBClose_Parameters(SMBCommand['Parameters']) - if connData['OpenedFiles'].has_key(comClose['FID']): + if comClose['FID'] in connData['OpenedFiles']: errorCode = STATUS_SUCCESS fileHandle = connData['OpenedFiles'][comClose['FID']]['FileHandle'] try: @@ -1290,7 +1296,7 @@ class SMBCommands: connData['OpenedFiles'][comClose['FID']]['Socket'].close() elif fileHandle != VOID_FILE_DESCRIPTOR: os.close(fileHandle) - except Exception, e: + except Exception as e: smbServer.log("comClose %s" % e, logging.ERROR) errorCode = STATUS_ACCESS_DENIED else: @@ -1298,7 +1304,7 @@ class SMBCommands: if connData['OpenedFiles'][comClose['FID']]['DeleteOnClose'] is True: try: os.remove(connData['OpenedFiles'][comClose['FID']]['FileName']) - except Exception, e: + except Exception as e: smbServer.log("comClose %s" % e, logging.ERROR) errorCode = STATUS_ACCESS_DENIED del(connData['OpenedFiles'][comClose['FID']]) @@ -1326,7 +1332,7 @@ class SMBCommands: comWriteParameters = smb.SMBWrite_Parameters(SMBCommand['Parameters']) comWriteData = smb.SMBWrite_Data(SMBCommand['Data']) - if connData['OpenedFiles'].has_key(comWriteParameters['Fid']): + if comWriteParameters['Fid'] in connData['OpenedFiles']: fileHandle = connData['OpenedFiles'][comWriteParameters['Fid']]['FileHandle'] errorCode = STATUS_SUCCESS try: @@ -1340,7 +1346,7 @@ class SMBCommands: sock = connData['OpenedFiles'][comWriteParameters['Fid']]['Socket'] sock.send(comWriteData['Data']) respParameters['Count'] = comWriteParameters['Count'] - except Exception, e: + except Exception as e: smbServer.log('smbComWrite: %s' % e, logging.ERROR) errorCode = STATUS_ACCESS_DENIED else: @@ -1367,12 +1373,12 @@ class SMBCommands: comFlush = smb.SMBFlush_Parameters(SMBCommand['Parameters']) - if connData['OpenedFiles'].has_key(comFlush['FID']): + if comFlush['FID'] in connData['OpenedFiles']: errorCode = STATUS_SUCCESS fileHandle = connData['OpenedFiles'][comFlush['FID']]['FileHandle'] try: os.fsync(fileHandle) - except Exception, e: + except Exception as e: smbServer.log("comFlush %s" % e, logging.ERROR) errorCode = STATUS_ACCESS_DENIED else: @@ -1400,7 +1406,7 @@ class SMBCommands: comCreateDirectoryData= smb.SMBCreateDirectory_Data(flags = recvPacket['Flags2'], data = SMBCommand['Data']) # Get the Tid associated - if connData['ConnectedShares'].has_key(recvPacket['Tid']): + if recvPacket['Tid'] in connData['ConnectedShares']: errorCode = STATUS_SUCCESS path = connData['ConnectedShares'][recvPacket['Tid']]['path'] fileName = os.path.normpath(decodeSMBString(recvPacket['Flags2'],comCreateDirectoryData['DirectoryName']).replace('\\','/')) @@ -1417,7 +1423,7 @@ class SMBCommands: else: try: os.mkdir(pathName) - except Exception, e: + except Exception as e: smbServer.log("smbComCreateDirectory: %s" % e, logging.ERROR) errorCode = STATUS_ACCESS_DENIED else: @@ -1444,7 +1450,7 @@ class SMBCommands: comRenameData = smb.SMBRename_Data(flags = recvPacket['Flags2'], data = SMBCommand['Data']) # Get the Tid associated - if connData['ConnectedShares'].has_key(recvPacket['Tid']): + if recvPacket['Tid'] in connData['ConnectedShares']: errorCode = STATUS_SUCCESS path = connData['ConnectedShares'][recvPacket['Tid']]['path'] oldFileName = os.path.normpath(decodeSMBString(recvPacket['Flags2'],comRenameData['OldFileName']).replace('\\','/')) @@ -1466,7 +1472,7 @@ class SMBCommands: else: try: os.rename(oldPathName,newPathName) - except OSError, e: + except OSError as e: smbServer.log("smbComRename: %s" % e, logging.ERROR) errorCode = STATUS_ACCESS_DENIED else: @@ -1494,7 +1500,7 @@ class SMBCommands: comDeleteData = smb.SMBDelete_Data(flags = recvPacket['Flags2'], data = SMBCommand['Data']) # Get the Tid associated - if connData['ConnectedShares'].has_key(recvPacket['Tid']): + if recvPacket['Tid'] in connData['ConnectedShares']: errorCode = STATUS_SUCCESS path = connData['ConnectedShares'][recvPacket['Tid']]['path'] fileName = os.path.normpath(decodeSMBString(recvPacket['Flags2'],comDeleteData['FileName']).replace('\\','/')) @@ -1510,7 +1516,7 @@ class SMBCommands: else: try: os.remove(pathName) - except OSError, e: + except OSError as e: smbServer.log("smbComDelete: %s" % e, logging.ERROR) errorCode = STATUS_ACCESS_DENIED else: @@ -1538,7 +1544,7 @@ class SMBCommands: comDeleteDirectoryData= smb.SMBDeleteDirectory_Data(flags = recvPacket['Flags2'], data = SMBCommand['Data']) # Get the Tid associated - if connData['ConnectedShares'].has_key(recvPacket['Tid']): + if recvPacket['Tid'] in connData['ConnectedShares']: errorCode = STATUS_SUCCESS path = connData['ConnectedShares'][recvPacket['Tid']]['path'] fileName = os.path.normpath(decodeSMBString(recvPacket['Flags2'],comDeleteDirectoryData['DirectoryName']).replace('\\','/')) @@ -1554,7 +1560,7 @@ class SMBCommands: else: try: os.rmdir(pathName) - except OSError, e: + except OSError as e: smbServer.log("smbComDeleteDirectory: %s" % e,logging.ERROR) if e.errno == errno.ENOTEMPTY: errorCode = STATUS_DIRECTORY_NOT_EMPTY @@ -1593,13 +1599,13 @@ class SMBCommands: writeAndXData.fromString(SMBCommand['Data']) - if connData['OpenedFiles'].has_key(writeAndX['Fid']): + if writeAndX['Fid'] in connData['OpenedFiles']: fileHandle = connData['OpenedFiles'][writeAndX['Fid']]['FileHandle'] errorCode = STATUS_SUCCESS try: if fileHandle != PIPE_FILE_DESCRIPTOR: offset = writeAndX['Offset'] - if writeAndX.fields.has_key('HighOffset'): + if 'HighOffset' in writeAndX.fields: offset += (writeAndX['HighOffset'] << 32) # If we're trying to write past the file end we just skip the write call (Vista does this) if os.lseek(fileHandle, 0, 2) >= offset: @@ -1611,7 +1617,7 @@ class SMBCommands: respParameters['Count'] = writeAndX['DataLength'] respParameters['Available']= 0xff - except Exception, e: + except Exception as e: smbServer.log('smbComWriteAndx: %s' % e, logging.ERROR) errorCode = STATUS_ACCESS_DENIED else: @@ -1637,7 +1643,7 @@ class SMBCommands: comReadParameters = smb.SMBRead_Parameters(SMBCommand['Parameters']) - if connData['OpenedFiles'].has_key(comReadParameters['Fid']): + if comReadParameters['Fid'] in connData['OpenedFiles']: fileHandle = connData['OpenedFiles'][comReadParameters['Fid']]['FileHandle'] errorCode = STATUS_SUCCESS try: @@ -1651,7 +1657,7 @@ class SMBCommands: respParameters['Count'] = len(content) respData['DataLength'] = len(content) respData['Data'] = content - except Exception, e: + except Exception as e: smbServer.log('smbComRead: %s ' % e, logging.ERROR) errorCode = STATUS_ACCESS_DENIED else: @@ -1680,13 +1686,13 @@ class SMBCommands: else: readAndX = smb.SMBReadAndX_Parameters(SMBCommand['Parameters']) - if connData['OpenedFiles'].has_key(readAndX['Fid']): + if readAndX['Fid'] in connData['OpenedFiles']: fileHandle = connData['OpenedFiles'][readAndX['Fid']]['FileHandle'] errorCode = 0 try: if fileHandle != PIPE_FILE_DESCRIPTOR: offset = readAndX['Offset'] - if readAndX.fields.has_key('HighOffset'): + if 'HighOffset' in readAndX.fields: offset += (readAndX['HighOffset'] << 32) os.lseek(fileHandle,offset,0) content = os.read(fileHandle,readAndX['MaxCount']) @@ -1698,7 +1704,7 @@ class SMBCommands: respParameters['DataOffset'] = 59 respParameters['DataCount_Hi'] = 0 respData = content - except Exception, e: + except Exception as e: smbServer.log('smbComReadAndX: %s ' % e, logging.ERROR) errorCode = STATUS_ACCESS_DENIED else: @@ -1725,7 +1731,7 @@ class SMBCommands: queryInformation= smb.SMBQueryInformation_Data(flags = recvPacket['Flags2'], data = SMBCommand['Data']) # Get the Tid associated - if connData['ConnectedShares'].has_key(recvPacket['Tid']): + if recvPacket['Tid'] in connData['ConnectedShares']: fileSize, lastWriteTime, fileAttributes = queryFsInformation( connData['ConnectedShares'][recvPacket['Tid']]['path'], decodeSMBString(recvPacket['Flags2'],queryInformation['FileName'])) @@ -1755,7 +1761,7 @@ class SMBCommands: respData = '' # Get the Tid associated - if connData['ConnectedShares'].has_key(recvPacket['Tid']): + if recvPacket['Tid'] in connData['ConnectedShares']: totalUnits, freeUnits = queryDiskInformation( connData['ConnectedShares'][recvPacket['Tid']]['path']) @@ -1807,7 +1813,7 @@ class SMBCommands: respParameters = '' respData = '' - if connData['ConnectedShares'].has_key(recvPacket['Tid']): + if recvPacket['Tid'] in connData['ConnectedShares']: smbServer.log("Disconnecting Share(%d:%s)" % (recvPacket['Tid'],connData['ConnectedShares'][recvPacket['Tid']]['shareName'])) del(connData['ConnectedShares'][recvPacket['Tid']]) errorCode = STATUS_SUCCESS @@ -1854,7 +1860,7 @@ class SMBCommands: queryInformation2 = smb.SMBQueryInformation2_Parameters(SMBCommand['Parameters']) errorCode = 0xFF - if connData['OpenedFiles'].has_key(queryInformation2['Fid']): + if queryInformation2['Fid'] in connData['OpenedFiles']: errorCode = STATUS_SUCCESS pathName = connData['OpenedFiles'][queryInformation2['Fid']]['FileName'] try: @@ -1873,7 +1879,7 @@ class SMBCommands: if os.path.isfile(pathName): attribs = smb.SMB_FILE_ATTRIBUTE_NORMAL respParameters['FileAttributes'] = attribs - except Exception, e: + except Exception as e: smbServer.log('smbComQueryInformation2 %s' % e,logging.ERROR) errorCode = STATUS_ACCESS_DENIED @@ -1904,14 +1910,14 @@ class SMBCommands: # respParameters['VolumeGUID'] = '\x00' # Get the Tid associated - if connData['ConnectedShares'].has_key(recvPacket['Tid']): + if recvPacket['Tid'] in connData['ConnectedShares']: # If we have a rootFid, the path is relative to that fid errorCode = STATUS_SUCCESS if ntCreateAndXParameters['RootFid'] > 0: path = connData['OpenedFiles'][ntCreateAndXParameters['RootFid']]['FileName'] LOG.debug("RootFid present %s!" % path) else: - if connData['ConnectedShares'][recvPacket['Tid']].has_key('path'): + if 'path' in connData['ConnectedShares'][recvPacket['Tid']]: path = connData['ConnectedShares'][recvPacket['Tid']]['path'] else: path = 'NONE' @@ -1947,7 +1953,7 @@ class SMBCommands: else: mode |= os.O_CREAT elif createDisposition & smb.FILE_OPEN == smb.FILE_OPEN: - if os.path.exists(pathName) is not True and smbServer.getRegisteredNamedPipes().has_key(unicode(pathName)) is not True: + if os.path.exists(pathName) is not True and (unicode(pathName) in smbServer.getRegisteredNamedPipes()) is not True: errorCode = STATUS_NO_SUCH_FILE if errorCode == STATUS_SUCCESS: @@ -1969,7 +1975,7 @@ class SMBCommands: # Let's create the directory os.mkdir(pathName) mode = os.O_RDONLY - except Exception, e: + except Exception as e: smbServer.log("NTCreateAndX: %s,%s,%s" % (pathName,mode,e),logging.ERROR) errorCode = STATUS_ACCESS_DENIED if createOptions & smb.FILE_NON_DIRECTORY_FILE == smb.FILE_NON_DIRECTORY_FILE: @@ -1989,13 +1995,13 @@ class SMBCommands: else: if sys.platform == 'win32': mode |= os.O_BINARY - if smbServer.getRegisteredNamedPipes().has_key(unicode(pathName)): + if unicode(pathName) in smbServer.getRegisteredNamedPipes(): fid = PIPE_FILE_DESCRIPTOR sock = socket.socket() sock.connect(smbServer.getRegisteredNamedPipes()[unicode(pathName)]) else: fid = os.open(pathName, mode) - except Exception, e: + except Exception as e: smbServer.log("NTCreateAndX: %s,%s,%s" % (pathName,mode,e),logging.ERROR) #print e fid = 0 @@ -2074,7 +2080,7 @@ class SMBCommands: openAndXData = smb.SMBOpenAndX_Data( flags = recvPacket['Flags2'], data = SMBCommand['Data']) # Get the Tid associated - if connData['ConnectedShares'].has_key(recvPacket['Tid']): + if recvPacket['Tid'] in connData['ConnectedShares']: path = connData['ConnectedShares'][recvPacket['Tid']]['path'] openedFile, mode, pathName, errorCode = openFile(path, decodeSMBString(recvPacket['Flags2'],openAndXData['FileName']), @@ -2223,7 +2229,7 @@ class SMBCommands: mechType = blob['MechTypes'][0] if mechType != TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']: # Nope, do we know it? - if MechTypes.has_key(mechType): + if mechType in MechTypes: mechStr = MechTypes[mechType] else: mechStr = hexlify(mechType) @@ -2431,7 +2437,7 @@ class SMBCommands: _dialects_parameters = smb.SMBNTLMDialect_Parameters() _dialects_data= smb.SMBNTLMDialect_Data() _dialects_data['Payload'] = '' - if connData.has_key('EncryptionKey'): + if 'EncryptionKey' in connData: _dialects_data['Challenge'] = connData['EncryptionKey'] _dialects_parameters['ChallengeLength'] = len(str(_dialects_data)) else: @@ -2463,7 +2469,7 @@ class SMBCommands: connData['_dialects_data'] = _dialects_data connData['_dialects_parameters'] = _dialects_parameters - except Exception, e: + except Exception as e: # No NTLM throw an error smbServer.log('smbComNegotiate: %s' % e, logging.ERROR) respSMBCommand['Data'] = struct.pack('<H',0xffff) @@ -2570,7 +2576,7 @@ class SMB2Commands: mechType = blob['MechTypes'][0] if mechType != TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider']: # Nope, do we know it? - if MechTypes.has_key(mechType): + if mechType in MechTypes: mechStr = MechTypes[mechType] else: mechStr = hexlify(mechType) @@ -2781,10 +2787,10 @@ class SMB2Commands: respSMBCommand['Buffer'] = '\x00' # Get the Tid associated - if connData['ConnectedShares'].has_key(recvPacket['TreeID']): + if recvPacket['TreeID'] in connData['ConnectedShares']: # If we have a rootFid, the path is relative to that fid errorCode = STATUS_SUCCESS - if connData['ConnectedShares'][recvPacket['TreeID']].has_key('path'): + if 'path' in connData['ConnectedShares'][recvPacket['TreeID']]: path = connData['ConnectedShares'][recvPacket['TreeID']]['path'] else: path = 'NONE' @@ -2820,7 +2826,7 @@ class SMB2Commands: else: mode |= os.O_CREAT elif createDisposition & smb2.FILE_OPEN == smb2.FILE_OPEN: - if os.path.exists(pathName) is not True and smbServer.getRegisteredNamedPipes().has_key(unicode(pathName)) is not True: + if os.path.exists(pathName) is not True and (unicode(pathName) in smbServer.getRegisteredNamedPipes()) is not True: errorCode = STATUS_NO_SUCH_FILE if errorCode == STATUS_SUCCESS: @@ -2842,7 +2848,7 @@ class SMB2Commands: # Let's create the directory os.mkdir(pathName) mode = os.O_RDONLY - except Exception, e: + except Exception as e: smbServer.log("SMB2_CREATE: %s,%s,%s" % (pathName,mode,e),logging.ERROR) errorCode = STATUS_ACCESS_DENIED if createOptions & smb2.FILE_NON_DIRECTORY_FILE == smb2.FILE_NON_DIRECTORY_FILE: @@ -2862,13 +2868,13 @@ class SMB2Commands: else: if sys.platform == 'win32': mode |= os.O_BINARY - if smbServer.getRegisteredNamedPipes().has_key(unicode(pathName)): + if unicode(pathName) in smbServer.getRegisteredNamedPipes(): fid = PIPE_FILE_DESCRIPTOR sock = socket.socket() sock.connect(smbServer.getRegisteredNamedPipes()[unicode(pathName)]) else: fid = os.open(pathName, mode) - except Exception, e: + except Exception as e: smbServer.log("SMB2_CREATE: %s,%s,%s" % (pathName,mode,e),logging.ERROR) #print e fid = 0 @@ -2939,14 +2945,14 @@ class SMB2Commands: if str(closeRequest['FileID']) == '\xff'*16: # Let's take the data from the lastRequest - if connData['LastRequest'].has_key('SMB2_CREATE'): + if 'SMB2_CREATE' in connData['LastRequest']: fileID = connData['LastRequest']['SMB2_CREATE']['FileID'] else: fileID = str(closeRequest['FileID']) else: fileID = str(closeRequest['FileID']) - if connData['OpenedFiles'].has_key(fileID): + if fileID in connData['OpenedFiles']: errorCode = STATUS_SUCCESS fileHandle = connData['OpenedFiles'][fileID]['FileHandle'] pathName = connData['OpenedFiles'][fileID]['FileName'] @@ -2957,7 +2963,7 @@ class SMB2Commands: elif fileHandle != VOID_FILE_DESCRIPTOR: os.close(fileHandle) infoRecord, errorCode = queryFileInformation(os.path.dirname(pathName), os.path.basename(pathName), smb2.SMB2_FILE_NETWORK_OPEN_INFO) - except Exception, e: + except Exception as e: smbServer.log("SMB2_CLOSE %s" % e, logging.ERROR) errorCode = STATUS_INVALID_HANDLE else: @@ -2968,7 +2974,7 @@ class SMB2Commands: shutil.rmtree(connData['OpenedFiles'][fileID]['FileName']) else: os.remove(connData['OpenedFiles'][fileID]['FileName']) - except Exception, e: + except Exception as e: smbServer.log("SMB2_CLOSE %s" % e, logging.ERROR) errorCode = STATUS_ACCESS_DENIED @@ -3004,15 +3010,15 @@ class SMB2Commands: if str(queryInfo['FileID']) == '\xff'*16: # Let's take the data from the lastRequest - if connData['LastRequest'].has_key('SMB2_CREATE'): + if 'SMB2_CREATE' in connData['LastRequest']: fileID = connData['LastRequest']['SMB2_CREATE']['FileID'] else: fileID = str(queryInfo['FileID']) else: fileID = str(queryInfo['FileID']) - if connData['ConnectedShares'].has_key(recvPacket['TreeID']): - if connData['OpenedFiles'].has_key(fileID): + if recvPacket['TreeID'] in connData['ConnectedShares']: + if fileID in connData['OpenedFiles']: fileName = connData['OpenedFiles'][fileID]['FileName'] if queryInfo['InfoType'] == smb2.SMB2_0_INFO_FILE: @@ -3055,16 +3061,16 @@ class SMB2Commands: if str(setInfo['FileID']) == '\xff'*16: # Let's take the data from the lastRequest - if connData['LastRequest'].has_key('SMB2_CREATE'): + if 'SMB2_CREATE' in connData['LastRequest']: fileID = connData['LastRequest']['SMB2_CREATE']['FileID'] else: fileID = str(setInfo['FileID']) else: fileID = str(setInfo['FileID']) - if connData['ConnectedShares'].has_key(recvPacket['TreeID']): + if recvPacket['TreeID'] in connData['ConnectedShares']: path = connData['ConnectedShares'][recvPacket['TreeID']]['path'] - if connData['OpenedFiles'].has_key(fileID): + if fileID in connData['OpenedFiles']: pathName = connData['OpenedFiles'][fileID]['FileName'] if setInfo['InfoType'] == smb2.SMB2_0_INFO_FILE: @@ -3104,7 +3110,7 @@ class SMB2Commands: try: os.rename(pathName,newPathName) connData['OpenedFiles'][fileID]['FileName'] = newPathName - except Exception, e: + except Exception as e: smbServer.log("smb2SetInfo: %s" % e, logging.ERROR) errorCode = STATUS_ACCESS_DENIED else: @@ -3145,14 +3151,14 @@ class SMB2Commands: if str(writeRequest['FileID']) == '\xff'*16: # Let's take the data from the lastRequest - if connData['LastRequest'].has_key('SMB2_CREATE'): + if 'SMB2_CREATE' in connData['LastRequest']: fileID = connData['LastRequest']['SMB2_CREATE']['FileID'] else: fileID = str(writeRequest['FileID']) else: fileID = str(writeRequest['FileID']) - if connData['OpenedFiles'].has_key(fileID): + if fileID in connData['OpenedFiles']: fileHandle = connData['OpenedFiles'][fileID]['FileHandle'] errorCode = STATUS_SUCCESS try: @@ -3168,7 +3174,7 @@ class SMB2Commands: respSMBCommand['Count'] = writeRequest['Length'] respSMBCommand['Remaining']= 0xff - except Exception, e: + except Exception as e: smbServer.log('SMB2_WRITE: %s' % e, logging.ERROR) errorCode = STATUS_ACCESS_DENIED else: @@ -3188,14 +3194,14 @@ class SMB2Commands: if str(readRequest['FileID']) == '\xff'*16: # Let's take the data from the lastRequest - if connData['LastRequest'].has_key('SMB2_CREATE'): + if 'SMB2_CREATE' in connData['LastRequest']: fileID = connData['LastRequest']['SMB2_CREATE']['FileID'] else: fileID = str(readRequest['FileID']) else: fileID = str(readRequest['FileID']) - if connData['OpenedFiles'].has_key(fileID): + if fileID in connData['OpenedFiles']: fileHandle = connData['OpenedFiles'][fileID]['FileHandle'] errorCode = 0 try: @@ -3211,7 +3217,7 @@ class SMB2Commands: respSMBCommand['DataLength'] = len(content) respSMBCommand['DataRemaining']= 0 respSMBCommand['Buffer'] = content - except Exception, e: + except Exception as e: smbServer.log('SMB2_READ: %s ' % e, logging.ERROR) errorCode = STATUS_ACCESS_DENIED else: @@ -3227,12 +3233,12 @@ class SMB2Commands: respSMBCommand = smb2.SMB2Flush_Response() flushRequest = smb2.SMB2Flush(recvPacket['Data']) - if connData['OpenedFiles'].has_key(str(flushRequest['FileID'])): + if str(flushRequest['FileID']) in connData['OpenedFiles']: fileHandle = connData['OpenedFiles'][str(flushRequest['FileID'])]['FileHandle'] errorCode = STATUS_SUCCESS try: os.fsync(fileHandle) - except Exception, e: + except Exception as e: smbServer.log("SMB2_FLUSH %s" % e, logging.ERROR) errorCode = STATUS_ACCESS_DENIED else: @@ -3251,21 +3257,21 @@ class SMB2Commands: respSMBCommand['Buffer'] = '\x00' # The server MUST locate the tree connection, as specified in section 3.3.5.2.11. - if connData['ConnectedShares'].has_key(recvPacket['TreeID']) is False: + if (recvPacket['TreeID'] in connData['ConnectedShares']) is False: return [smb2.SMB2Error()], None, STATUS_NETWORK_NAME_DELETED # Next, the server MUST locate the open for the directory to be queried # If no open is found, the server MUST fail the request with STATUS_FILE_CLOSED if str(queryDirectoryRequest['FileID']) == '\xff'*16: # Let's take the data from the lastRequest - if connData['LastRequest'].has_key('SMB2_CREATE'): + if 'SMB2_CREATE' in connData['LastRequest']: fileID = connData['LastRequest']['SMB2_CREATE']['FileID'] else: fileID = str(queryDirectoryRequest['FileID']) else: fileID = str(queryDirectoryRequest['FileID']) - if connData['OpenedFiles'].has_key(fileID) is False: + if (fileID in connData['OpenedFiles']) is False: return [smb2.SMB2Error()], None, STATUS_FILE_CLOSED # If the open is not an open to a directory, the request MUST be failed @@ -3383,7 +3389,7 @@ class SMB2Commands: respSMBCommand = smb2.SMB2TreeDisconnect_Response() - if connData['ConnectedShares'].has_key(recvPacket['TreeID']): + if recvPacket['TreeID'] in connData['ConnectedShares']: smbServer.log("Disconnecting Share(%d:%s)" % (recvPacket['TreeID'],connData['ConnectedShares'][recvPacket['TreeID']]['shareName'])) del(connData['ConnectedShares'][recvPacket['TreeID']]) errorCode = STATUS_SUCCESS @@ -3420,7 +3426,7 @@ class SMB2Commands: ioctlRequest = smb2.SMB2Ioctl(recvPacket['Data']) ioctls = smbServer.getIoctls() - if ioctls.has_key(ioctlRequest['CtlCode']): + if ioctlRequest['CtlCode'] in ioctls: outputData, errorCode = ioctls[ioctlRequest['CtlCode']](connId, smbServer, ioctlRequest) if errorCode == STATUS_SUCCESS: respSMBCommand['CtlCode'] = ioctlRequest['CtlCode'] @@ -3475,7 +3481,7 @@ class Ioctls: ioctlResponse = '' - if connData['OpenedFiles'].has_key(str(ioctlRequest['FileID'])): + if str(ioctlRequest['FileID']) in connData['OpenedFiles']: fileHandle = connData['OpenedFiles'][str(ioctlRequest['FileID'])]['FileHandle'] errorCode = STATUS_SUCCESS try: @@ -3485,7 +3491,7 @@ class Ioctls: sock = connData['OpenedFiles'][str(ioctlRequest['FileID'])]['Socket'] sock.sendall(ioctlRequest['Buffer']) ioctlResponse = sock.recv(ioctlRequest['MaxOutputResponse']) - except Exception, e: + except Exception as e: smbServer.log('fsctlPipeTransceive: %s ' % e, logging.ERROR) errorCode = STATUS_ACCESS_DENIED else: @@ -3551,7 +3557,7 @@ class SMBSERVERHandler(SocketServer.BaseRequestHandler): # a single packet for i in resp: session.send_packet(str(i)) - except Exception, e: + except Exception as e: self.__SMB.log("Handle: %s" % e) #import traceback #traceback.print_exc() @@ -3734,7 +3740,7 @@ smb.SMB.TRANS_TRANSACT_NMPIPE :self.__smbTransHandler.transactNamedPipe def getConnectionData(self, connId, checkStatus = True): conn = self.__activeConnections[connId] if checkStatus is True: - if conn.has_key('Authenticated') is not True: + if ('Authenticated' in conn) is not True: # Can't keep going further raise Exception("User not Authenticated!") return conn @@ -3747,13 +3753,13 @@ smb.SMB.TRANS_TRANSACT_NMPIPE :self.__smbTransHandler.transactNamedPipe return True def unregisterNamedPipe(self, pipeName): - if self.__registeredNamedPipes.has_key(pipeName): + if pipeName in self.__registeredNamedPipes: del(self.__registeredNamedPipes[unicode(pipeName)]) return True return False def unregisterTransaction(self, transCommand): - if self.__smbTransCommands.has_key(transCommand): + if transCommand in self.__smbTransCommands: del(self.__smbTransCommands[transCommand]) def hookTransaction(self, transCommand, callback): @@ -3788,7 +3794,7 @@ smb.SMB.TRANS_TRANSACT_NMPIPE :self.__smbTransHandler.transactNamedPipe # respData: the data reponse of the transaction # errorCode: the NT error code - if self.__smbTransCommands.has_key(transCommand): + if transCommand in self.__smbTransCommands: originalCommand = self.__smbTransCommands[transCommand] else: originalCommand = None @@ -3797,13 +3803,13 @@ smb.SMB.TRANS_TRANSACT_NMPIPE :self.__smbTransHandler.transactNamedPipe return originalCommand def unregisterTransaction2(self, transCommand): - if self.__smbTrans2Commands.has_key(transCommand): + if transCommand in self.__smbTrans2Commands: del(self.__smbTrans2Commands[transCommand]) def hookTransaction2(self, transCommand, callback): # Here we should add to __smbTrans2Commands # Same description as Transaction - if self.__smbTrans2Commands.has_key(transCommand): + if transCommand in self.__smbTrans2Commands: originalCommand = self.__smbTrans2Commands[transCommand] else: originalCommand = None @@ -3812,13 +3818,13 @@ smb.SMB.TRANS_TRANSACT_NMPIPE :self.__smbTransHandler.transactNamedPipe return originalCommand def unregisterNTTransaction(self, transCommand): - if self.__smbNTTransCommands.has_key(transCommand): + if transCommand in self.__smbNTTransCommands: del(self.__smbNTTransCommands[transCommand]) def hookNTTransaction(self, transCommand, callback): # Here we should add to __smbNTTransCommands # Same description as Transaction - if self.__smbNTTransCommands.has_key(transCommand): + if transCommand in self.__smbNTTransCommands: originalCommand = self.__smbNTTransCommands[transCommand] else: originalCommand = None @@ -3827,7 +3833,7 @@ smb.SMB.TRANS_TRANSACT_NMPIPE :self.__smbTransHandler.transactNamedPipe return originalCommand def unregisterSmbCommand(self, smbCommand): - if self.__smbCommands.has_key(smbCommand): + if smbCommand in self.__smbCommands: del(self.__smbCommands[smbCommand]) def hookSmbCommand(self, smbCommand, callback): @@ -3866,7 +3872,7 @@ smb.SMB.TRANS_TRANSACT_NMPIPE :self.__smbTransHandler.transactNamedPipe # transCommands: a list of transaction subcommands already registered # - if self.__smbCommands.has_key(smbCommand): + if smbCommand in self.__smbCommands: originalCommand = self.__smbCommands[smbCommand] else: originalCommand = None @@ -3875,11 +3881,11 @@ smb.SMB.TRANS_TRANSACT_NMPIPE :self.__smbTransHandler.transactNamedPipe return originalCommand def unregisterSmb2Command(self, smb2Command): - if self.__smb2Commands.has_key(smb2Command): + if smb2Command in self.__smb2Commands: del(self.__smb2Commands[smb2Command]) def hookSmb2Command(self, smb2Command, callback): - if self.__smb2Commands.has_key(smb2Command): + if smb2Command in self.__smb2Commands: originalCommand = self.__smb2Commands[smb2Command] else: originalCommand = None @@ -3969,13 +3975,13 @@ smb.SMB.TRANS_TRANSACT_NMPIPE :self.__smbTransHandler.transactNamedPipe packet, self.__smbTransCommands) else: - if self.__smbCommands.has_key(packet['Command']): + if packet['Command'] in self.__smbCommands: if self.__SMB2Support is True: if packet['Command'] == smb.SMB.SMB_COM_NEGOTIATE: try: respCommands, respPackets, errorCode = self.__smb2Commands[smb2.SMB2_NEGOTIATE](connId, self, packet, True) isSMB2 = True - except Exception, e: + except Exception as e: self.log('SMB2_NEGOTIATE: %s' % e, logging.ERROR) # If something went wrong, let's fallback to SMB1 respCommands, respPackets, errorCode = self.__smbCommands[packet['Command']]( @@ -4006,7 +4012,7 @@ smb.SMB.TRANS_TRANSACT_NMPIPE :self.__smbTransHandler.transactNamedPipe else: done = False while not done: - if self.__smb2Commands.has_key(packet['Command']): + if packet['Command'] in self.__smb2Commands: if self.__SMB2Support is True: respCommands, respPackets, errorCode = self.__smb2Commands[packet['Command']]( connId, @@ -4025,7 +4031,7 @@ smb.SMB.TRANS_TRANSACT_NMPIPE :self.__smbTransHandler.transactNamedPipe else: done = True - except Exception, e: + except Exception as e: #import traceback #traceback.print_exc() # Something wen't wrong, defaulting to Bad user ID diff --git a/tests/python_dependencies/impacket/spnego.py b/tests/python_dependencies/impacket/spnego.py index 43e65fb5c..98069f579 100644 --- a/tests/python_dependencies/impacket/spnego.py +++ b/tests/python_dependencies/impacket/spnego.py @@ -1,3 +1,4 @@ +from __future__ import print_function # Copyright (c) 2003-2016 CORE Security Technologies # # This software is provided under under a slightly modified version @@ -13,7 +14,7 @@ from struct import pack, unpack, calcsize ############### GSS Stuff ################ -GSS_API_SPNEGO_UUID = '\x2b\x06\x01\x05\x05\x02' +GSS_API_SPNEGO_UUID = '\x2b\x06\x01\x05\x05\x02' ASN1_SEQUENCE = 0x30 ASN1_AID = 0x60 ASN1_OID = 0x06 @@ -33,59 +34,59 @@ MechTypes = { TypesMech = dict((v,k) for k, v in MechTypes.iteritems()) def asn1encode(data = ''): - #res = asn1.SEQUENCE(str).encode() - #import binascii - #print '\nalex asn1encode str: %s\n' % binascii.hexlify(str) - if 0 <= len(data) <= 0x7F: - res = pack('B', len(data)) + data - elif 0x80 <= len(data) <= 0xFF: - res = pack('BB', 0x81, len(data)) + data - elif 0x100 <= len(data) <= 0xFFFF: - res = pack('!BH', 0x82, len(data)) + data - elif 0x10000 <= len(data) <= 0xffffff: - res = pack('!BBH', 0x83, len(data) >> 16, len(data) & 0xFFFF) + data - elif 0x1000000 <= len(data) <= 0xffffffff: - res = pack('!BL', 0x84, len(data)) + data - else: - raise Exception('Error in asn1encode') - return str(res) + #res = asn1.SEQUENCE(str).encode() + #import binascii + #print '\nalex asn1encode str: %s\n' % binascii.hexlify(str) + if 0 <= len(data) <= 0x7F: + res = pack('B', len(data)) + data + elif 0x80 <= len(data) <= 0xFF: + res = pack('BB', 0x81, len(data)) + data + elif 0x100 <= len(data) <= 0xFFFF: + res = pack('!BH', 0x82, len(data)) + data + elif 0x10000 <= len(data) <= 0xffffff: + res = pack('!BBH', 0x83, len(data) >> 16, len(data) & 0xFFFF) + data + elif 0x1000000 <= len(data) <= 0xffffffff: + res = pack('!BL', 0x84, len(data)) + data + else: + raise Exception('Error in asn1encode') + return str(res) def asn1decode(data = ''): - len1 = unpack('B', data[:1])[0] - data = data[1:] - if len1 == 0x81: - pad = calcsize('B') - len2 = unpack('B',data[:pad])[0] - data = data[pad:] - ans = data[:len2] - elif len1 == 0x82: - pad = calcsize('H') - len2 = unpack('!H', data[:pad])[0] - data = data[pad:] - ans = data[:len2] - elif len1 == 0x83: - pad = calcsize('B') + calcsize('!H') - len2, len3 = unpack('!BH', data[:pad]) - data = data[pad:] - ans = data[:len2 << 16 + len3] - elif len1 == 0x84: - pad = calcsize('!L') - len2 = unpack('!L', data[:pad])[0] - data = data[pad:] - ans = data[:len2] - # 1 byte length, string <= 0x7F - else: - pad = 0 - ans = data[:len1] - return ans, len(ans)+pad+1 + len1 = unpack('B', data[:1])[0] + data = data[1:] + if len1 == 0x81: + pad = calcsize('B') + len2 = unpack('B',data[:pad])[0] + data = data[pad:] + ans = data[:len2] + elif len1 == 0x82: + pad = calcsize('H') + len2 = unpack('!H', data[:pad])[0] + data = data[pad:] + ans = data[:len2] + elif len1 == 0x83: + pad = calcsize('B') + calcsize('!H') + len2, len3 = unpack('!BH', data[:pad]) + data = data[pad:] + ans = data[:len2 << 16 + len3] + elif len1 == 0x84: + pad = calcsize('!L') + len2 = unpack('!L', data[:pad])[0] + data = data[pad:] + ans = data[:len2] + # 1 byte length, string <= 0x7F + else: + pad = 0 + ans = data[:len1] + return ans, len(ans)+pad+1 class GSSAPI: -# Generic GSSAPI Header Format +# Generic GSSAPI Header Format def __init__(self, data = None): self.fields = {} self['UUID'] = GSS_API_SPNEGO_UUID if data: - self.fromString(data) + self.fromString(data) pass def __setitem__(self,key,value): @@ -115,27 +116,27 @@ class GSSAPI: if next_byte != ASN1_AID: raise Exception('Unknown AID=%x' % next_byte) data = data[1:] - decode_data, total_bytes = asn1decode(data) + decode_data, total_bytes = asn1decode(data) # Now we should have a OID tag - next_byte = unpack('B',decode_data[:1])[0] + next_byte = unpack('B',decode_data[:1])[0] if next_byte != ASN1_OID: raise Exception('OID tag not found %x' % next_byte) decode_data = decode_data[1:] # Now the OID contents, should be SPNEGO UUID - uuid, total_bytes = asn1decode(decode_data) + uuid, total_bytes = asn1decode(decode_data) self['OID'] = uuid # the rest should be the data self['Payload'] = decode_data[total_bytes:] #pass - + def dump(self): for i in self.fields.keys(): - print "%s: {%r}" % (i,self[i]) + print("%s: {%r}" % (i,self[i])) def getData(self): ans = pack('B',ASN1_AID) ans += asn1encode( - pack('B',ASN1_OID) + + pack('B',ASN1_OID) + asn1encode(self['UUID']) + self['Payload'] ) return ans @@ -163,7 +164,7 @@ class SPNEGO_NegTokenResp: def __init__(self, data = None): self.fields = {} if data: - self.fromString(data) + self.fromString(data) pass def __setitem__(self,key,value): @@ -198,7 +199,7 @@ class SPNEGO_NegTokenResp: if next_byte != ASN1_MECH_TYPE: # MechType not found, could be an AUTH answer if next_byte != ASN1_RESPONSE_TOKEN: - raise Exception('MechType/ResponseToken tag not found %x' % next_byte) + raise Exception('MechType/ResponseToken tag not found %x' % next_byte) else: decode_data2 = decode_data[1:] decode_data2, total_bytes = asn1decode(decode_data2) @@ -245,30 +246,30 @@ class SPNEGO_NegTokenResp: def dump(self): for i in self.fields.keys(): - print "%s: {%r}" % (i,self[i]) - + print("%s: {%r}" % (i,self[i])) + def getData(self): ans = pack('B',SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP) - if self.fields.has_key('NegResult') and self.fields.has_key('SupportedMech'): + if 'NegResult' in self.fields and 'SupportedMech' in self.fields: # Server resp ans += asn1encode( pack('B', ASN1_SEQUENCE) + asn1encode( pack('B',SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_TARG) + asn1encode( - pack('B',ASN1_ENUMERATED) + + pack('B',ASN1_ENUMERATED) + asn1encode( self['NegResult'] )) + pack('B',ASN1_SUPPORTED_MECH) + - asn1encode( + asn1encode( pack('B',ASN1_OID) + asn1encode(self['SupportedMech'])) + pack('B',ASN1_RESPONSE_TOKEN ) + asn1encode( pack('B', ASN1_OCTET_STRING) + asn1encode(self['ResponseToken'])))) - elif self.fields.has_key('NegResult'): + elif 'NegResult' in self.fields: # Server resp ans += asn1encode( - pack('B', ASN1_SEQUENCE) + + pack('B', ASN1_SEQUENCE) + asn1encode( pack('B', SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_TARG) + asn1encode( @@ -285,24 +286,24 @@ class SPNEGO_NegTokenResp: return ans class SPNEGO_NegTokenInit(GSSAPI): - # http://tools.ietf.org/html/rfc4178#page-8 + # http://tools.ietf.org/html/rfc4178#page-8 # NegTokeInit :: = SEQUENCE { - # mechTypes [0] MechTypeList, + # mechTypes [0] MechTypeList, # reqFlags [1] ContextFlags OPTIONAL, - # mechToken [2] OCTET STRING OPTIONAL, + # mechToken [2] OCTET STRING OPTIONAL, # mechListMIC [3] OCTET STRING OPTIONAL, # } SPNEGO_NEG_TOKEN_INIT = 0xa0 def fromString(self, data = 0): GSSAPI.fromString(self, data) payload = self['Payload'] - next_byte = unpack('B', payload[:1])[0] + next_byte = unpack('B', payload[:1])[0] if next_byte != SPNEGO_NegTokenInit.SPNEGO_NEG_TOKEN_INIT: raise Exception('NegTokenInit not found %x' % next_byte) payload = payload[1:] decode_data, total_bytes = asn1decode(payload) # Now we should have a SEQUENCE Tag - next_byte = unpack('B', decode_data[:1])[0] + next_byte = unpack('B', decode_data[:1])[0] if next_byte != ASN1_SEQUENCE: raise Exception('SEQUENCE tag not found %x' % next_byte) decode_data = decode_data[1:] @@ -321,14 +322,14 @@ class SPNEGO_NegTokenInit(GSSAPI): # And finally we should have the MechTypes self['MechTypes'] = [] while decode_data: - next_byte = unpack('B', decode_data[:1])[0] - if next_byte != ASN1_OID: - # Not a valid OID, there must be something else we won't unpack - break - decode_data = decode_data[1:] - item, total_bytes = asn1decode(decode_data) - self['MechTypes'].append(item) - decode_data = decode_data[total_bytes:] + next_byte = unpack('B', decode_data[:1])[0] + if next_byte != ASN1_OID: + # Not a valid OID, there must be something else we won't unpack + break + decode_data = decode_data[1:] + item, total_bytes = asn1decode(decode_data) + self['MechTypes'].append(item) + decode_data = decode_data[total_bytes:] # Do we have MechTokens as well? decode_data = remaining_data[total_bytes3:] @@ -352,7 +353,7 @@ class SPNEGO_NegTokenInit(GSSAPI): mechToken = '' # Do we have tokens to send? - if self.fields.has_key('MechToken'): + if 'MechToken' in self.fields: mechToken = pack('B', ASN1_MECH_TOKEN) + asn1encode( pack('B', ASN1_OCTET_STRING) + asn1encode( self['MechToken'])) @@ -363,10 +364,9 @@ class SPNEGO_NegTokenInit(GSSAPI): asn1encode( pack('B', ASN1_MECH_TYPE) + asn1encode( - pack('B', ASN1_SEQUENCE) + + pack('B', ASN1_SEQUENCE) + asn1encode(mechTypes)) + mechToken )) self['Payload'] = ans return GSSAPI.getData(self) - diff --git a/tests/python_dependencies/impacket/structure.py b/tests/python_dependencies/impacket/structure.py index 7a04117ff..68066a61f 100644 --- a/tests/python_dependencies/impacket/structure.py +++ b/tests/python_dependencies/impacket/structure.py @@ -1,3 +1,4 @@ +from __future__ import print_function # Copyright (c) 2003-2016 CORE Security Technologies # # This software is provided under under a slightly modified version @@ -97,18 +98,18 @@ class Structure: def packField(self, fieldName, format = None): if self.debug: - print "packField( %s | %s )" % (fieldName, format) + print("packField( %s | %s )" % (fieldName, format)) if format is None: format = self.formatForField(fieldName) - if self.fields.has_key(fieldName): + if fieldName in self.fields: ans = self.pack(format, self.fields[fieldName], field = fieldName) else: ans = self.pack(format, None, field = fieldName) if self.debug: - print "\tanswer %r" % ans + print("\tanswer %r" % ans) return ans @@ -119,8 +120,8 @@ class Structure: for field in self.commonHdr+self.structure: try: data += self.packField(field[0], field[1]) - except Exception, e: - if self.fields.has_key(field[0]): + except Exception as e: + if field[0] in self.fields: e.args += ("When packing field '%s | %s | %r' in %s" % (field[0], field[1], self[field[0]], self.__class__),) else: e.args += ("When packing field '%s | %s' in %s" % (field[0], field[1], self.__class__),) @@ -136,16 +137,16 @@ class Structure: self.rawData = data for field in self.commonHdr+self.structure: if self.debug: - print "fromString( %s | %s | %r )" % (field[0], field[1], data) + print("fromString( %s | %s | %r )" % (field[0], field[1], data)) size = self.calcUnpackSize(field[1], data, field[0]) if self.debug: - print " size = %d" % size + print(" size = %d" % size) dataClassOrCode = str if len(field) > 2: dataClassOrCode = field[2] try: self[field[0]] = self.unpack(field[1], data[:size], dataClassOrCode = dataClassOrCode, field = field[0]) - except Exception,e: + except Exception as e: e.args += ("When unpacking field '%s | %s | %r[:%d]'" % (field[0], field[1], data, size),) raise @@ -175,7 +176,7 @@ class Structure: def pack(self, format, data, field = None): if self.debug: - print " pack( %s | %r | %s)" % (format, data, field) + print(" pack( %s | %r | %s)" % (format, data, field)) if field: addressField = self.findAddressFieldFor(field) @@ -206,7 +207,7 @@ class Structure: try: return self.pack(two[0], data) except: - if (self.fields.has_key(two[1])) and (self[two[1]] is not None): + if (two[1] in self.fields) and (self[two[1]] is not None): return self.pack(two[0], id(self[two[1]]) & ((1<<(calcsize(two[0])*8))-1) ) else: return self.pack(two[0], 0) @@ -228,7 +229,7 @@ class Structure: if two[0]: if two[0].isdigit(): if int(two[0]) != len(data): - raise Exception, "Array field has a constant size, and it doesn't match the actual value" + raise Exception("Array field has a constant size, and it doesn't match the actual value") else: return self.pack(two[0], len(data))+answer return answer @@ -256,7 +257,7 @@ class Structure: return '%s\0\0\0\0%s%s' % (l,l,data) if data is None: - raise Exception, "Trying to pack None" + raise Exception("Trying to pack None") # literal specifier if format[:1] == ':': @@ -267,7 +268,7 @@ class Structure: def unpack(self, format, data, dataClassOrCode = str, field = None): if self.debug: - print " unpack( %s | %r )" % (format, data) + print(" unpack( %s | %r )" % (format, data)) if field: addressField = self.findAddressFieldFor(field) @@ -288,7 +289,7 @@ class Structure: if format[:1] == "'" or format[:1] == '"': answer = format[1:] if answer != data: - raise Exception, "Unpacked data doesn't match constant value '%r' should be '%r'" % (data, answer) + raise Exception("Unpacked data doesn't match constant value '%r' should be '%r'" % (data, answer)) return answer # address specifier @@ -334,13 +335,13 @@ class Structure: # asciiz specifier if format == 'z': if data[-1] != '\x00': - raise Exception, ("%s 'z' field is not NUL terminated: %r" % (field, data)) + raise Exception("%s 'z' field is not NUL terminated: %r" % (field, data)) return data[:-1] # remove trailing NUL # unicode specifier if format == 'u': if data[-2:] != '\x00\x00': - raise Exception, ("%s 'u' field is not NUL-NUL terminated: %r" % (field, data)) + raise Exception("%s 'u' field is not NUL-NUL terminated: %r" % (field, data)) return data[:-2] # remove trailing NUL # DCE-RPC/NDR string specifier @@ -392,7 +393,7 @@ class Structure: answer = 0 if two[0].isdigit(): if int(two[0]) != len(data): - raise Exception, "Array field has a constant size, and it doesn't match the actual value" + raise Exception("Array field has a constant size, and it doesn't match the actual value") elif two[0]: answer += self.calcPackSize(two[0], len(data)) @@ -428,7 +429,7 @@ class Structure: def calcUnpackSize(self, format, data, field = None): if self.debug: - print " calcUnpackSize( %s | %s | %r)" % (field, format, data) + print(" calcUnpackSize( %s | %s | %r)" % (field, format, data)) # void specifier if format[:1] == '_': @@ -487,7 +488,7 @@ class Structure: # "printf" string specifier if format[:1] == '%': - raise Exception, "Can't guess the size of a printf like specifier for unpacking" + raise Exception("Can't guess the size of a printf like specifier for unpacking") # asciiz specifier if format[:1] == 'z': @@ -520,7 +521,7 @@ class Structure: for field in self.commonHdr+self.structure: if field[0] == fieldName: return field[1] - raise Exception, ("Field %s not found" % fieldName) + raise Exception("Field %s not found" % fieldName) def findAddressFieldFor(self, fieldName): descriptor = '&%s' % fieldName @@ -558,7 +559,7 @@ class Structure: def dump(self, msg = None, indent = 0): if msg is None: msg = self.__class__.__name__ ind = ' '*indent - print "\n%s" % msg + print("\n%s" % msg) fixedFields = [] for field in self.commonHdr+self.structure: i = field[0] @@ -566,18 +567,18 @@ class Structure: fixedFields.append(i) if isinstance(self[i], Structure): self[i].dump('%s%s:{' % (ind,i), indent = indent + 4) - print "%s}" % ind + print("%s}" % ind) else: - print "%s%s: {%r}" % (ind,i,self[i]) + print("%s%s: {%r}" % (ind,i,self[i])) # Do we have remaining fields not defined in the structures? let's # print them remainingFields = list(set(self.fields) - set(fixedFields)) for i in remainingFields: if isinstance(self[i], Structure): self[i].dump('%s%s:{' % (ind,i), indent = indent + 4) - print "%s}" % ind + print("%s}" % ind) else: - print "%s%s: {%r}" % (ind,i,self[i]) + print("%s%s: {%r}" % (ind,i,self[i])) class _StructureTest: @@ -589,23 +590,23 @@ class _StructureTest: return self.theClass(alignment = self.alignment) def run(self): - print - print "-"*70 + print() + print("-"*70) testName = self.__class__.__name__ - print "starting test: %s....." % testName + print("starting test: %s....." % testName) a = self.create() self.populate(a) a.dump("packing.....") a_str = str(a) - print "packed: %r" % a_str - print "unpacking....." + print("packed: %r" % a_str) + print("unpacking.....") b = self.create(a_str) b.dump("unpacked.....") - print "repacking....." + print("repacking.....") b_str = str(b) if b_str != a_str: - print "ERROR: original packed and repacked don't match" - print "packed: %r" % b_str + print("ERROR: original packed and repacked don't match") + print("packed: %r" % b_str) class _Test_simple(_StructureTest): class theClass(Structure): @@ -732,7 +733,7 @@ if __name__ == '__main__': try: _Test_fixedLength().run() except: - print "cannot repack because length is bogus" + print("cannot repack because length is bogus") _Test_simple_aligned4().run() _Test_nested().run() diff --git a/tests/python_dependencies/impacket/uuid.py b/tests/python_dependencies/impacket/uuid.py index fb4d7b3a0..750eba459 100644 --- a/tests/python_dependencies/impacket/uuid.py +++ b/tests/python_dependencies/impacket/uuid.py @@ -17,9 +17,14 @@ import re from random import randrange from struct import pack, unpack +try: + long # Python 2 +except NameError: + long = int # Python 3 + def generate(): # UHm... crappy Python has an maximum integer of 2**31-1. - top = (1L<<31)-1 + top = (1<<31)-1 return pack("IIII", randrange(top), randrange(top), randrange(top), randrange(top)) def bin_to_string(uuid): @@ -49,16 +54,16 @@ def bin_to_uuidtup(bin): return uuidstr, "%d.%d" % (maj, min) #input: string -#output: tuple (uuid,version) +#output: tuple (uuid,version) #if version is not found in the input string "1.0" is returned -#example: -# "00000000-0000-0000-0000-000000000000 3.0" returns ('00000000-0000-0000-0000-000000000000','3.0') -# "10000000-2000-3000-4000-500000000000 version 3.0" returns ('00000000-0000-0000-0000-000000000000','3.0') -# "10000000-2000-3000-4000-500000000000 v 3.0" returns ('00000000-0000-0000-0000-000000000000','3.0') -# "10000000-2000-3000-4000-500000000000" returns ('00000000-0000-0000-0000-000000000000','1.0') +#example: +# "00000000-0000-0000-0000-000000000000 3.0" returns ('00000000-0000-0000-0000-000000000000','3.0') +# "10000000-2000-3000-4000-500000000000 version 3.0" returns ('00000000-0000-0000-0000-000000000000','3.0') +# "10000000-2000-3000-4000-500000000000 v 3.0" returns ('00000000-0000-0000-0000-000000000000','3.0') +# "10000000-2000-3000-4000-500000000000" returns ('00000000-0000-0000-0000-000000000000','1.0') def string_to_uuidtup(s): g = re.search("([A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}).*?([0-9]{1,5}\.[0-9]{1,5})",s+" 1.0") - if g: + if g: (u,v) = g.groups() return (u,v) return |