Coverage for /private/tmp/im/impacket/impacket/smb.py : 68%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# SECUREAUTH LABS. Copyright 2018 SecureAuth Corporation. All rights reserved. # # This software is provided under under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # Copyright (C) 2001 Michael Teo <michaelteo@bigfoot.com> # smb.py - SMB/CIFS library # # This software is provided 'as-is', without any express or implied warranty. # In no event will the author be held liable for any damages arising from the # use of this software. # # Permission is granted to anyone to use this software for any purpose, # including commercial applications, and to alter it and redistribute it # freely, subject to the following restrictions: # # 1. The origin of this software must not be misrepresented; you must not # claim that you wrote the original software. If you use this software # in a product, an acknowledgment in the product documentation would be # appreciated but is not required. # # 2. Altered source versions must be plainly marked as such, and must not be # misrepresented as being the original software. # # 3. This notice cannot be removed or altered from any source distribution. # # Altered source done by Alberto Solino (@agsolino)
# Todo: # [ ] Try [SMB]transport fragmentation using Transact requests # [ ] Try other methods of doing write (write_raw, transact2, write, write_and_unlock, write_and_close, write_mpx) # [-] Try replacements for SMB_COM_NT_CREATE_ANDX (CREATE, T_TRANSACT_CREATE, OPEN_ANDX works # [x] Fix forceWriteAndx, which needs to send a RecvRequest, because recv() will not send it # [x] Fix Recv() when using RecvAndx and the answer comes splet in several packets # [ ] Try [SMB]transport fragmentation with overlapping segments # [ ] Try [SMB]transport fragmentation with out of order segments # [x] Do chained AndX requests # [ ] Transform the rest of the calls to structure # [X] Implement TRANS/TRANS2 reassembly for list_path
# For signing
# Dialect for SMB1
# Shared Device Type
# Extended attributes mask
# Service Type
# Server Type (Can be used to mask with SMBMachine.get_type() or SMBDomain.get_type())
# Options values for SMB.stor_file and SMB.retr_file
# Share Access Mode
# SMB_FILE_ATTRIBUTES
# Session SetupAndX Action flags
# QUERY_INFORMATION levels
# SET_INFORMATION levels
# File System Attributes
# FIND_FIRST2 flags and levels
# DesiredAccess flags
# ShareAccess flags
# CreateDisposition flags
if errclass == 0x01: return 'OS error', ERRDOS.get(errcode, 'Unknown error') elif errclass == 0x02: return 'Server error', ERRSRV.get(errcode, 'Unknown error') elif errclass == 0x03: return 'Hardware error', ERRHRD.get(errcode, 'Unknown error') # This is not a standard error class for SMB #elif errclass == 0x80: # return 'Browse error', ERRBROWSE.get(errcode, 'Unknown error') elif errclass == 0xff: return 'Bad command', 'Bad command. Please file bug report' else: return 'Unknown error', 'Unknown error'
# Raised when an error has occurred during a session # SMB X/Open error codes for the ERRDOS error class
# here's a special one from observing NT
# These errors seem to be only returned by the NT printer driver system
# Error codes for the ERRSRV class
# Error codes for the ERRHRD class
19: ("ERRnowrite", "Attempt to write on write-protected diskette."), 20: ("ERRbadunit", "Unknown unit."), 21: ("ERRnotready", "Drive not ready."), 22: ("ERRbadcmd", "Unknown command."), 23: ("ERRdata", "Data error (CRC)."), 24: ("ERRbadreq", "Bad request structure length."), 25: ("ERRseek", "Seek error."), 26: ("ERRbadmedia", "Unknown media type."), 27: ("ERRbadsector", "Sector not found."), 28: ("ERRnopaper", "Printer out of paper."), 29: ("ERRwrite", "Write fault."), 30: ("ERRread", "Read fault."), 31: ("ERRgeneral", "General failure."), 32: ("ERRbadshare", "An open conflicts with an existing open."), 33: ("ERRlock", "A Lock request conflicted with an existing lock or specified an invalid mode, or an Unlock requested attempted to remove a lock held by another process."), 34: ("ERRwrongdisk", "The wrong disk was found in a drive."), 35: ("ERRFCBUnavail", "No FCBs are available to process request."), 36: ("ERRsharebufexc", "A sharing buffer has been exceeded.") }
ERRbadfunc: ("ERRbadfunc", "Invalid function."), ERRbadfile: ("ERRbadfile", "File not found."), ERRbadpath: ("ERRbadpath", "Directory invalid."), ERRnofids: ("ERRnofids", "No file descriptors available"), ERRnoaccess: ("ERRnoaccess", "Access denied."), ERRbadfid: ("ERRbadfid", "Invalid file handle."), ERRbadmcb: ("ERRbadmcb", "Memory control blocks destroyed."), ERRnomem: ("ERRnomem", "Insufficient server memory to perform the requested function."), ERRbadmem: ("ERRbadmem", "Invalid memory block address."), ERRbadenv: ("ERRbadenv", "Invalid environment."), 11: ("ERRbadformat", "Invalid format."), ERRbadaccess: ("ERRbadaccess", "Invalid open mode."), ERRbaddata: ("ERRbaddata", "Invalid data."), ERRres: ("ERRres", "reserved."), ERRbaddrive: ("ERRbaddrive", "Invalid drive specified."), ERRremcd: ("ERRremcd", "A Delete Directory request attempted to remove the server's current directory."), ERRdiffdevice: ("ERRdiffdevice", "Not same device."), ERRnofiles: ("ERRnofiles", "A File Search command can find no more files matching the specified criteria."), ERRbadshare: ("ERRbadshare", "The sharing mode specified for an Open conflicts with existing FIDs on the file."), ERRlock: ("ERRlock", "A Lock request conflicted with an existing lock or specified an invalid mode, or an Unlock requested attempted to remove a lock held by another process."), ERRunsup: ("ERRunsup", "The operation is unsupported"), ERRnosuchshare: ("ERRnosuchshare", "You specified an invalid share name"), ERRfilexists: ("ERRfilexists", "The file named in a Create Directory, Make New File or Link request already exists."), ERRinvalidname: ("ERRinvalidname", "Invalid name"), ERRbadpipe: ("ERRbadpipe", "Pipe invalid."), ERRpipebusy: ("ERRpipebusy", "All instances of the requested pipe are busy."), ERRpipeclosing: ("ERRpipeclosing", "Pipe close in progress."), ERRnotconnected: ("ERRnotconnected", "No process on other end of pipe."), ERRmoredata: ("ERRmoredata", "There is more data to be returned."), ERRinvgroup: ("ERRinvgroup", "Invalid workgroup (try the -W option)"), ERRlogonfailure: ("ERRlogonfailure", "Logon failure"), ERRdiskfull: ("ERRdiskfull", "Disk full"), ERRgeneral: ("ERRgeneral", "General failure"), ERRunknownlevel: ("ERRunknownlevel", "Unknown info level") }
1: ("ERRerror", "Non-specific error code."), 2: ("ERRbadpw", "Bad password - name/password pair in a Tree Connect or Session Setup are invalid."), 3: ("ERRbadtype", "reserved."), 4: ("ERRaccess", "The requester does not have the necessary access rights within the specified context for the requested function. The context is defined by the TID or the UID."), 5: ("ERRinvnid", "The tree ID (TID) specified in a command was invalid."), 6: ("ERRinvnetname", "Invalid network name in tree connect."), 7: ("ERRinvdevice", "Invalid device - printer request made to non-printer connection or non-printer request made to printer connection."), 49: ("ERRqfull", "Print queue full (files) -- returned by open print file."), 50: ("ERRqtoobig", "Print queue full -- no space."), 51: ("ERRqeof", "EOF on print queue dump."), 52: ("ERRinvpfid", "Invalid print file FID."), 64: ("ERRsmbcmd", "The server did not recognize the command received."), 65: ("ERRsrverror","The server encountered an internal error, e.g., system file unavailable."), 67: ("ERRfilespecs", "The file handle (FID) and pathname parameters contained an invalid combination of values."), 68: ("ERRreserved", "reserved."), 69: ("ERRbadpermits", "The access permissions specified for a file or directory are not a valid combination. The server cannot set the requested attribute."), 70: ("ERRreserved", "reserved."), 71: ("ERRsetattrmode", "The attribute mode in the Set File Attribute request is invalid."), 81: ("ERRpaused", "Server is paused."), 82: ("ERRmsgoff", "Not receiving messages."), 83: ("ERRnoroom", "No room to buffer message."), 87: ("ERRrmuns", "Too many remote user names."), 88: ("ERRtimeout", "Operation timed out."), 89: ("ERRnoresource", "No resources currently available for request."), 90: ("ERRtoomanyuids", "Too many UIDs active on this session."), 91: ("ERRbaduid", "The UID is not known as a valid ID on this session."), 250: ("ERRusempx","Temp unable to support Raw, use MPX mode."), 251: ("ERRusestd","Temp unable to support Raw, use standard read/write."), 252: ("ERRcontmpx", "Continue in MPX mode."), 253: ("ERRreserved", "reserved."), 254: ("ERRreserved", "reserved."), 0xFFFF: ("ERRnosupport", "Function not supported.") } # Error clases
ERRDOS: ("ERRDOS", dos_msgs), 0x02: ("ERRSRV",server_msgs), 0x03: ("ERRHRD",hard_msgs), 0x04: ("ERRXOS", {} ), 0xE1: ("ERRRMX1", {} ), 0xE2: ("ERRRMX2", {} ), 0xE3: ("ERRRMX3", {} ), 0xFF: ("ERRCMD", {} ) }
else: self.error_class = error_class self.error_code = error_code
return self.error_class
error_class = SessionError.error_classes.get( self.error_class, None ) if not error_class: error_code_str = self.error_code error_class_str = self.error_class else: error_class_str = error_class[0] error_code = error_class[1].get( self.error_code, None ) if not error_code: error_code_str = self.error_code else: error_code_str = '%s(%s)' % error_code
if self.nt_status: return 'SMB SessionError: %s(%s)' % nt_errors.ERROR_MESSAGES[self.error_code] else: # Fall back to the old format return 'SMB SessionError: class: %s, code: %s' % (error_class_str, error_code_str)
# Raised when an supported feature is present/required in the protocol but is not # currently supported by pysmb
# Contains information about a SMB shared device/service self.__name = name self.__type = share_type self.__comment = comment
return self.__name
return self.__type
return self.__comment
return '<SharedDevice instance: name=' + self.__name + ', type=' + str(self.__type) + ', comment="' + self.__comment + '">'
# Contains information about the shared file/directory self.__shortname = shortname[:shortname.index(b'\0')] else: self.__longname = longname[:longname.index(b'\0')] else:
return self.__ctime
return self.__convert_smbtime(self.__ctime)
return self.__mtime
return self.__convert_smbtime(self.__mtime)
return self.__atime
return self.__convert_smbtime(self.__atime)
return self.__filesize
return self.__allocsize
return self.__attribs
return self.__attribs & ATTR_ARCHIVE
return self.__attribs & ATTR_COMPRESSED
return self.__attribs & ATTR_NORMAL
return self.__attribs & ATTR_HIDDEN
return self.__attribs & ATTR_READONLY
return self.__attribs & ATTR_TEMPORARY
return self.__attribs & ATTR_DIRECTORY
return self.__attribs & ATTR_SYSTEM
return self.__shortname
return self.__longname
return '<SharedFile instance: shortname="' + self.__shortname + '", longname="' + self.__longname + '", filesize=' + str(self.__filesize) + '>'
def __convert_smbtime(t): x = t >> 32 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 & 0xfff00000)) * 1.0e-7 - geo_cal_offset
# Contain information about a SMB machine self.__nbname = nbname self.__type = nbt_type self.__comment = comment
return '<SMBMachine instance: nbname="' + self.__nbname + '", type=' + hex(self.__type) + ', comment="' + self.__comment + '">'
self.__nbgroup = nbgroup self.__type = domain_type self.__master_browser = master_browser
return '<SMBDomain instance: nbgroup="' + self.__nbgroup + '", type=' + hex(self.__type) + ', master browser="' + self.__master_browser + '">'
# Represents a SMB Packet ('Signature', '"\xffSMB'), ('Command','B=0'), ('ErrorClass','B=0'), ('_reserved','B=0'), ('ErrorCode','<H=0'), ('Flags1','B=0'), ('Flags2','<H=0'), ('PIDHigh','<H=0'), ('SecurityFeatures','8s=""'), ('Reserved','<H=0'), ('Tid','<H=0xffff'), ('Pid','<H=0'), ('Uid','<H=0'), ('Mid','<H=0'), ('Data','*:'), )
else: self['Data'][-1]['Parameters']['AndXCommand'] = command.command self['Data'][-1]['Parameters']['AndXOffset'] = len(self)
self['ErrorClass'] == 1 and self['ErrorCode'] == SessionError.ERRmoredata)
# this was inside a loop reading more from the net (with recv_packet(None)) return 1 else: raise UnsupportedFeature("Unexpected answer from server: Got %d, Expected %d" % (self['Command'], cmd))
('WordCount', 'B=len(Parameters)//2'), ('_ParametersLength','_-Parameters','WordCount*2'), ('Parameters',':'), # default set by constructor ('ByteCount','<H-Data'), ('Data',':'), # default set by constructor )
else:
else:
('AndXCommand','B=0xff'), ('_reserved','B=0'), ('AndXOffset','<H=0'), ) ('Data',':=""'), )
############# TRANSACTIONS RELATED # TRANS2_QUERY_FS_INFORMATION # QUERY_FS Information Levels # SMB_QUERY_FS_ATTRIBUTE_INFO ('FileSystemAttributes','<L'), ('MaxFilenNameLengthInBytes','<L'), ('LengthOfFileSystemName','<L-FileSystemName'), ('FileSystemName',':'), )
('ulVolSerialNbr','<L=0xABCDEFAA'), ('cCharCount','<B-VolumeLabel'), ) ('VolumeLabel','z'), ) ('VolumeLabel','u'), )
# FILE_FS_SIZE_INFORMATION ('TotalAllocationUnits','<q=148529400'), ('AvailableAllocationUnits','<q=14851044'), ('SectorsPerAllocationUnit','<L=2'), ('BytesPerSector','<L=512'), )
# SMB_QUERY_FS_SIZE_INFO ('TotalAllocationUnits','<q=148529400'), ('TotalFreeAllocationUnits','<q=14851044'), ('SectorsPerAllocationUnit','<L=2'), ('BytesPerSector','<L=512'), ) # FILE_FS_FULL_SIZE_INFORMATION ('TotalAllocationUnits','<q=148529400'), ('CallerAvailableAllocationUnits','<q=148529400'), ('ActualAvailableAllocationUnits','<q=148529400'), ('SectorsPerAllocationUnit','<L=15'), ('BytesPerSector','<L=512') ) # SMB_QUERY_FS_VOLUME_INFO ('VolumeCreationTime','<q'), ('SerialNumber','<L=0xABCDEFAA'), ('VolumeLabelSize','<L=len(VolumeLabel)'), ('Reserved','<H=0x10'), ('VolumeLabel',':') ) # SMB_FIND_FILE_BOTH_DIRECTORY_INFO level ('NextEntryOffset','<L=0'), ('FileIndex','<L=0'), ('CreationTime','<q'), ('LastAccessTime','<q'), ('LastWriteTime','<q'), ('LastChangeTime','<q'), ('EndOfFile','<q=0'), ('AllocationSize','<q=0'), ('ExtFileAttributes','<L=0'), ) ('FileNameLength','<L-FileName','len(FileName)'), ('EaSize','<L=0'), ('ShortNameLength','<B=0'), ('Reserved','<B=0'), ('ShortName','24s'), ('FileName',':'), ) ('FileNameLength','<L-FileName','len(FileName)*2'), ('EaSize','<L=0'), ('ShortNameLength','<B=0'), ('Reserved','<B=0'), ('ShortName','24s'), ('FileName',':'), )
# SMB_FIND_FILE_ID_FULL_DIRECTORY_INFO level ('NextEntryOffset','<L=0'), ('FileIndex','<L=0'), ('CreationTime','<q'), ('LastAccessTime','<q'), ('LastWriteTime','<q'), ('LastChangeTime','<q'), ('EndOfFile','<q=0'), ('AllocationSize','<q=0'), ('ExtFileAttributes','<L=0'), ) ('FileNameLength','<L-FileName','len(FileName)'), ('EaSize','<L=0'), ('FileID','<q=0'), ('FileName',':'), ) ('FileNameLength','<L-FileName','len(FileName)*2'), ('EaSize','<L=0'), ('FileID','<q=0'), ('FileName',':'), )
# SMB_FIND_FILE_ID_BOTH_DIRECTORY_INFO level ('NextEntryOffset','<L=0'), ('FileIndex','<L=0'), ('CreationTime','<q'), ('LastAccessTime','<q'), ('LastWriteTime','<q'), ('LastChangeTime','<q'), ('EndOfFile','<q=0'), ('AllocationSize','<q=0'), ('ExtFileAttributes','<L=0'), ) ('FileNameLength','<L-FileName','len(FileName)'), ('EaSize','<L=0'), ('ShortNameLength','<B=0'), ('Reserved','<B=0'), ('ShortName','24s'), ('Reserved','<H=0'), ('FileID','<q=0'), ('FileName','z'), ) ('FileNameLength','<L-FileName','len(FileName)*2'), ('EaSize','<L=0'), ('ShortNameLength','<B=0'), ('Reserved','<B=0'), ('ShortName','24s'), ('Reserved','<H=0'), ('FileID','<q=0'), ('FileName',':'), )
# SMB_FIND_FILE_DIRECTORY_INFO level ('NextEntryOffset','<L=0'), ('FileIndex','<L=0'), ('CreationTime','<q'), ('LastAccessTime','<q'), ('LastWriteTime','<q'), ('LastChangeTime','<q'), ('EndOfFile','<q=0'), ('AllocationSize','<q=1'), ('ExtFileAttributes','<L=0'), ) ('FileNameLength','<L-FileName','len(FileName)'), ('FileName','z'), ) ('FileNameLength','<L-FileName','len(FileName)*2'), ('FileName',':'), )
# SMB_FIND_FILE_NAMES_INFO level ('NextEntryOffset','<L=0'), ('FileIndex','<L=0'), ) ('FileNameLength','<L-FileName','len(FileName)'), ('FileName','z'), ) ('FileNameLength','<L-FileName','len(FileName)*2'), ('FileName',':'), )
# SMB_FIND_FILE_FULL_DIRECTORY_INFO level ('NextEntryOffset','<L=0'), ('FileIndex','<L=0'), ('CreationTime','<q'), ('LastAccessTime','<q'), ('LastWriteTime','<q'), ('LastChangeTime','<q'), ('EndOfFile','<q=0'), ('AllocationSize','<q=1'), ('ExtFileAttributes','<L=0'), ) ('FileNameLength','<L-FileName','len(FileName)'), ('EaSize','<L'), ('FileName','z'), ) ('FileNameLength','<L-FileName','len(FileName)*2'), ('EaSize','<L'), ('FileName',':'), )
# SMB_FIND_INFO_STANDARD level ('ResumeKey','<L=0xff'), ('CreationDate','<H=0'), ('CreationTime','<H=0'), ('LastAccessDate','<H=0'), ('LastAccessTime','<H=0'), ('LastWriteDate','<H=0'), ('LastWriteTime','<H=0'), ('EaSize','<L'), ('AllocationSize','<L=1'), ('ExtFileAttributes','<H=0'), ) ('FileNameLength','<B-FileName','len(FileName)'), ('FileName','z'), ) ('FileNameLength','<B-FileName','len(FileName)*2'), ('FileName',':'), )
# SET_FILE_INFORMATION structures # SMB_SET_FILE_DISPOSITION_INFO ('DeletePending','<B'), )
# SMB_SET_FILE_BASIC_INFO ('CreationTime','<q'), ('LastAccessTime','<q'), ('LastWriteTime','<q'), ('ChangeTime','<q'), ('ExtFileAttributes','<H'), ('Reserved','<L'), )
# FILE_STREAM_INFORMATION ('NextEntryOffset','<L=0'), ('StreamNameLength','<L=0'), ('StreamSize','<q=0'), ('StreamAllocationSize','<q=0'), ('StreamName',':=""'), )
# FILE_NETWORK_OPEN_INFORMATION ('CreationTime','<q=0'), ('LastAccessTime','<q=0'), ('LastWriteTime','<q=0'), ('ChangeTime','<q=0'), ('AllocationSize','<q=0'), ('EndOfFile','<q=0'), ('FileAttributes','<L=0'), ('Reserved','<L=0'), )
# SMB_SET_FILE_END_OF_FILE_INFO ('EndOfFile','<q'), )
# TRANS2_FIND_NEXT2 ('SID','<H'), ('SearchCount','<H'), ('InformationLevel','<H'), ('ResumeKey','<L'), ('Flags','<H'), ) ('FileName','z'), ) ('FileName','u'), )
('SearchCount','<H'), ('EndOfSearch','<H=1'), ('EaErrorOffset','<H=0'), ('LastNameOffset','<H=0'), )
('GetExtendedAttributesListLength','_-GetExtendedAttributesList', 'self["GetExtendedAttributesListLength"]'), ('GetExtendedAttributesList',':'), )
# TRANS2_FIND_FIRST2 ('SID','<H'), ('SearchCount','<H'), ('EndOfSearch','<H=1'), ('EaErrorOffset','<H=0'), ('LastNameOffset','<H=0'), )
('SearchAttributes','<H'), ('SearchCount','<H'), ('Flags','<H'), ('InformationLevel','<H'), ('SearchStorageType','<L'), ) ('FileName','z'), ) ('FileName','u'), )
('GetExtendedAttributesListLength','_-GetExtendedAttributesList', 'self["GetExtendedAttributesListLength"]'), ('GetExtendedAttributesList',':'), )
# TRANS2_SET_PATH_INFORMATION ('InformationLevel','<H'), ('Reserved','<L'), ) ('FileName','z'), ) ('FileName','u'), )
('EaErrorOffset','<H=0'), )
# TRANS2_SET_FILE_INFORMATION ('FID','<H'), ('InformationLevel','<H'), ('Reserved','<H'), )
('EaErrorOffset','<H=0'), )
# TRANS2_QUERY_FILE_INFORMATION ('FID','<H'), ('InformationLevel','<H'), )
('EaErrorOffset','<H=0'), )
('GetExtendedAttributeList',':'), )
# TRANS2_QUERY_PATH_INFORMATION ('EaErrorOffset','<H=0'), )
('InformationLevel','<H'), ('Reserved','<L=0'), ) ('FileName','z'), ) ('FileName','u'), )
('GetExtendedAttributeList',':'), )
# SMB_QUERY_FILE_EA_INFO ('EaSize','<L=0'), )
# SMB_QUERY_FILE_BASIC_INFO ('CreationTime','<q'), ('LastAccessTime','<q'), ('LastWriteTime','<q'), ('LastChangeTime','<q'), ('ExtFileAttributes','<L'), #('Reserved','<L=0'), )
# SMB_QUERY_FILE_STANDARD_INFO ('AllocationSize','<q'), ('EndOfFile','<q'), ('NumberOfLinks','<L=0'), ('DeletePending','<B=0'), ('Directory','<B'), )
# SMB_QUERY_FILE_ALL_INFO ('CreationTime','<q'), ('LastAccessTime','<q'), ('LastWriteTime','<q'), ('LastChangeTime','<q'), ('ExtFileAttributes','<L'), ('Reserved','<L=0'), ('AllocationSize','<q'), ('EndOfFile','<q'), ('NumberOfLinks','<L=0'), ('DeletePending','<B=0'), ('Directory','<B'), ('Reserved','<H=0'), ('EaSize','<L=0'), ('FileNameLength','<L-FileName','len(FileName)'), ('FileName',':'), )
# \PIPE\LANMAN NetShareEnum ('RAPOpcode','<H=0'), ('ParamDesc','z'), ('DataDesc','z'), ('InfoLevel','<H'), ('ReceiveBufferSize','<H'), )
('Status','<H=0'), ('Convert','<H=0'), ('EntriesReturned','<H'), ('EntriesAvailable','<H'), )
('NetworkName','13s'), ('Pad','<B=0'), ('Type','<H=0'), ('RemarkOffsetLow','<H=0'), ('RemarkOffsetHigh','<H=0'), )
# \PIPE\LANMAN NetServerGetInfo ('Status','<H=0'), ('Convert','<H=0'), ('TotalBytesAvailable','<H'), )
# Level 1 Response ('ServerName','16s'), ('MajorVersion','B=5'), ('MinorVersion','B=0'), ('ServerType','<L=3'), ('ServerCommentLow','<H=0'), ('ServerCommentHigh','<H=0'), )
# \PIPE\LANMAN NetShareGetInfo ('RAPOpcode','<H=0'), ('ParamDesc','z'), ('DataDesc','z'), ('ShareName','z'), ('InfoLevel','<H'), ('ReceiveBufferSize','<H'), )
('Status','<H=0'), ('Convert','<H=0'), ('TotalBytesAvailable','<H'), )
############# Security Features ('Key','<L=0'), ('CID','<H=0'), ('SequenceNumber','<H=0'), )
############# SMB_COM_QUERY_INFORMATION2 (0x23) ('Fid','<H'), )
('CreateDate','<H'), ('CreationTime','<H'), ('LastAccessDate','<H'), ('LastAccessTime','<H'), ('LastWriteDate','<H'), ('LastWriteTime','<H'), ('FileDataSize','<L'), ('FileAllocationSize','<L'), ('FileAttributes','<L'), )
############# SMB_COM_SESSION_SETUP_ANDX (0x73) ('MaxBuffer','<H'), ('MaxMpxCount','<H'), ('VCNumber','<H'), ('SessionKey','<L'), ('AnsiPwdLength','<H'), ('UnicodePwdLength','<H'), ('_reserved','<L=0'), ('Capabilities','<L'), )
('MaxBufferSize','<H'), ('MaxMpxCount','<H'), ('VcNumber','<H'), ('SessionKey','<L'), ('SecurityBlobLength','<H'), ('Reserved','<L=0'), ('Capabilities','<L'), )
('AnsiPwdLength','_-AnsiPwd','self["AnsiPwdLength"]'), ('UnicodePwdLength','_-UnicodePwd','self["UnicodePwdLength"]'), ('AnsiPwd',':=""'), ('UnicodePwd',':=""'), ('Account','z=""'), ('PrimaryDomain','z=""'), ('NativeOS','z=""'), ('NativeLanMan','z=""'), )
('AnsiPwdLength','_-AnsiPwd','self["AnsiPwdLength"]'), ('UnicodePwdLength','_-UnicodePwd','self["UnicodePwdLength"]'), ('AnsiPwd',':=""'), ('UnicodePwd',':=""'), ('Account','u=""'), ('PrimaryDomain','u=""'), ('NativeOS','u=""'), ('NativeLanMan','u=""'), )
('SecurityBlobLength','_-SecurityBlob','self["SecurityBlobLength"]'), ('SecurityBlob',':'), ('NativeOS','z=""'), ('NativeLanMan','z=""'), )
('SecurityBlobLength','_-SecurityBlob','self["SecurityBlobLength"]'), ('SecurityBlob',':'), ('NativeOS','u=""'), ('NativeLanMan','u=""'), )
('Action','<H'), )
('Action','<H=0'), ('SecurityBlobLength','<H'), )
('NativeOS','z=""'), ('NativeLanMan','z=""'), ('PrimaryDomain','z=""'), )
('NativeOS','u=""'), ('NativeLanMan','u=""'), ('PrimaryDomain','u=""'), )
('SecurityBlobLength','_-SecurityBlob','self["SecurityBlobLength"]'), ('SecurityBlob',':'), ('NativeOS','z=""'), ('NativeLanMan','z=""'), )
('SecurityBlobLength','_-SecurityBlob','self["SecurityBlobLength"]'), ('SecurityBlob',':'), ('PadLen','_-Pad','1 if (len(self["SecurityBlob"]) % 2 == 0) else 0'), ('Pad',':=""'), ('NativeOS','u=""'), ('NativeLanMan','u=""'), ) if self.structure == self.UnicodeStructure: if len(str(self['SecurityBlob'])) % 2 == 0: self['Pad'] = '\x00' return AsciiOrUnicodeStructure.getData(self)
############# SMB_COM_TREE_CONNECT (0x70) )
('PathFormat','"\x04'), ('Path','z'), ('PasswordFormat','"\x04'), ('Password','z'), ('ServiceFormat','"\x04'), ('Service','z'), )
############# SMB_COM_TREE_CONNECT_ANDX (0x75) ('Flags','<H=0'), ('PasswordLength','<H'), )
('OptionalSupport','<H=0'), )
('OptionalSupport','<H=1'), ('MaximalShareAccessRights','<L=0x1fffff'), ('GuestMaximalShareAccessRights','<L=0x1fffff'), )
('_PasswordLength','_-Password','self["_PasswordLength"]'), ('Password',':'), ('Path','z'), ('Service','z'), )
('_PasswordLength','_-Password','self["_PasswordLength"] if self["_PasswordLength"] > 0 else 1'), ('Password',':'), ('Path','u'), ('Service','z'), )
('Service','z'), ('PadLen','_-Pad','self["PadLen"]'), ('Pad',':=""'), ('NativeFileSystem','z'), ) ('Service','z'), ('PadLen','_-Pad','self["PadLen"]'), ('Pad',':=""'), ('NativeFileSystem','u'), )
############# SMB_COM_NT_CREATE_ANDX (0xA2) ('_reserved', 'B=0'), ('FileNameLength','<H'), # NameLength ('CreateFlags','<L'), # Flags ('RootFid','<L=0'), # RootDirectoryFID ('AccessMask','<L'), # DesiredAccess ('AllocationSizeLo','<L=0'), # AllocationSize ('AllocationSizeHi','<L=0'), ('FileAttributes','<L=0'), # ExtFileAttributes ('ShareAccess','<L=3'), # ('Disposition','<L=1'), # CreateDisposition ('CreateOptions','<L'), # CreateOptions ('Impersonation','<L=2'), ('SecurityFlags','B=3'), )
# XXX Is there a memory leak in the response for NTCreate (where the Data section would be) in Win 2000, Win XP, and Win 2003? ('OplockLevel', 'B=0'), ('Fid','<H'), ('CreateAction','<L'), ('CreateTime','<q=0'), ('LastAccessTime','<q=0'), ('LastWriteTime','<q=0'), ('LastChangeTime','<q=0'), ('FileAttributes','<L=0x80'), ('AllocationSize','<q=0'), ('EndOfFile','<q=0'), ('FileType','<H=0'), ('IPCState','<H=0'), ('IsDirectory','B'), )
# [MS-SMB] Extended response description ('OplockLevel', 'B=0'), ('Fid','<H'), ('CreateAction','<L'), ('CreateTime','<q=0'), ('LastAccessTime','<q=0'), ('LastWriteTime','<q=0'), ('LastChangeTime','<q=0'), ('FileAttributes','<L=0x80'), ('AllocationSize','<q=0'), ('EndOfFile','<q=0'), ('FileType','<H=0'), ('IPCState','<H=0'), ('IsDirectory','B'), ('VolumeGUID','16s'), ('FileIdLow','<L=0'), ('FileIdHigh','<L=0'), ('MaximalAccessRights','<L=0x12019b'), ('GuestMaximalAccessRights','<L=0x120089'), )
('FileName','z'), ) ('Pad','B'), ('FileName','u'), )
############# SMB_COM_OPEN_ANDX (0xD2) ('Flags','<H=0'), ('DesiredAccess','<H=0'), ('SearchAttributes','<H=0'), ('FileAttributes','<H=0'), ('CreationTime','<L=0'), ('OpenMode','<H=1'), # SMB_O_OPEN = 1 ('AllocationSize','<L=0'), ('Reserved','8s=""'), )
('Fid','<H=0'), ('FileAttributes','<H=0'), ('LastWriten','<L=0'), ('FileSize','<L=0'), ('GrantedAccess','<H=0'), ('FileType','<H=0'), ('IPCState','<H=0'), ('Action','<H=0'), ('ServerFid','<L=0'), ('_reserved','<H=0'), )
############# SMB_COM_WRITE (0x0B) ('Fid','<H'), ('Count','<H'), ('Offset','<L'), ('Remaining','<H'), )
('Count','<H'), )
('BufferFormat','<B=1'), ('DataLength','<H-Data'), ('Data',':'), )
############# SMB_COM_WRITE_ANDX (0x2F) ('Fid','<H=0'), ('Offset','<L=0'), ('_reserved','<L=0xff'), ('WriteMode','<H=8'), ('Remaining','<H=0'), ('DataLength_Hi','<H=0'), ('DataLength','<H=0'), ('DataOffset','<H=0'), ('HighOffset','<L=0'), )
('_PadLen','_-Pad','self["DataOffset"] - 59'), ('Pad',':'), #('Pad','<B=0'), ('DataLength','_-Data','self["DataLength"]'), ('Data',':'), )
('_PadLen','_-Pad','self["DataOffset"] - 63'), ('Pad',':'), #('Pad','<B=0'), ('DataLength','_-Data','self["DataLength"]'), ('Data',':'), )
('Fid','<H'), ('Offset','<L'), ('_reserved','<L=0xff'), ('WriteMode','<H=8'), ('Remaining','<H'), ('DataLength_Hi','<H=0'), ('DataLength','<H'), ('DataOffset','<H=0'), )
('Count','<H'), ('Available','<H'), ('Reserved','<L=0'), )
############# SMB_COM_WRITE_RAW (0x1D) ('Fid','<H'), ('Count','<H'), ('_reserved','<H=0'), ('Offset','<L'), ('Timeout','<L=0'), ('WriteMode','<H=0'), ('_reserved2','<L=0'), ('DataLength','<H'), ('DataOffset','<H=0'), )
############# SMB_COM_READ (0x0A) ('Fid','<H'), ('Count','<H'), ('Offset','<L'), ('Remaining','<H=Count'), )
('Count','<H=0'), ('_reserved','8s=""'), )
('BufferFormat','<B=0x1'), ('DataLength','<H-Data'), ('Data',':'), )
############# SMB_COM_READ_RAW (0x1A) ('Fid','<H'), ('Offset','<L'), ('MaxCount','<H'), ('MinCount','<H=MaxCount'), ('Timeout','<L=0'), ('_reserved','<H=0'), )
############# SMB_COM_NT_TRANSACT (0xA0) ('MaxSetupCount','<B=0'), ('Reserved1','<H=0'), ('TotalParameterCount','<L'), ('TotalDataCount','<L'), ('MaxParameterCount','<L=1024'), ('MaxDataCount','<L=65504'), ('ParameterCount','<L'), ('ParameterOffset','<L'), ('DataCount','<L'), ('DataOffset','<L'), ('SetupCount','<B=len(Setup)//2'), ('Function','<H=0'), ('SetupLength','_-Setup','SetupCount*2'), ('Setup',':'), )
('Reserved1','3s=""'), ('TotalParameterCount','<L'), ('TotalDataCount','<L'), ('ParameterCount','<L'), ('ParameterOffset','<L'), ('ParameterDisplacement','<L=0'), ('DataCount','<L'), ('DataOffset','<L'), ('DataDisplacement','<L=0'), ('SetupCount','<B=0'), ('SetupLength','_-Setup','SetupCount*2'), ('Setup',':'), )
('Pad1Length','_-Pad1','self["Pad1Length"]'), ('Pad1',':'), ('NT_Trans_ParametersLength','_-NT_Trans_Parameters','self["NT_Trans_ParametersLength"]'), ('NT_Trans_Parameters',':'), ('Pad2Length','_-Pad2','self["Pad2Length"]'), ('Pad2',':'), ('NT_Trans_DataLength','_-NT_Trans_Data','self["NT_Trans_DataLength"]'), ('NT_Trans_Data',':'), )
('Pad1Length','_-Pad1','self["Pad1Length"]'), ('Pad1',':'), ('Trans_ParametersLength','_-Trans_Parameters','self["Trans_ParametersLength"]'), ('Trans_Parameters',':'), ('Pad2Length','_-Pad2','self["Pad2Length"]'), ('Pad2',':'), ('Trans_DataLength','_-Trans_Data','self["Trans_DataLength"]'), ('Trans_Data',':'), )
############# SMB_COM_TRANSACTION2_SECONDARY (0x33) ('TotalParameterCount','<H'), ('TotalDataCount','<H'), ('ParameterCount','<H'), ('ParameterOffset','<H'), ('ParameterDisplacement','<H'), ('DataCount','<H'), ('DataOffset','<H'), ('DataDisplacement','<H=0'), ('FID','<H'), )
('Pad1Length','_-Pad1','self["Pad1Length"]'), ('Pad1',':'), ('Trans_ParametersLength','_-Trans_Parameters','self["Trans_ParametersLength"]'), ('Trans_Parameters',':'), ('Pad2Length','_-Pad2','self["Pad2Length"]'), ('Pad2',':'), ('Trans_DataLength','_-Trans_Data','self["Trans_DataLength"]'), ('Trans_Data',':'), )
############# SMB_COM_TRANSACTION2 (0x32)
('TotalParameterCount','<H'), ('TotalDataCount','<H'), ('MaxParameterCount','<H=1024'), ('MaxDataCount','<H=65504'), ('MaxSetupCount','<B=0'), ('Reserved1','<B=0'), ('Flags','<H=0'), ('Timeout','<L=0'), ('Reserved2','<H=0'), ('ParameterCount','<H'), ('ParameterOffset','<H'), ('DataCount','<H'), ('DataOffset','<H'), ('SetupCount','<B=len(Setup)//2'), ('Reserved3','<B=0'), ('SetupLength','_-Setup','SetupCount*2'), ('Setup',':'), )
('TotalParameterCount','<H'), ('TotalDataCount','<H'), ('Reserved1','<H=0'), ('ParameterCount','<H'), ('ParameterOffset','<H'), ('ParameterDisplacement','<H=0'), ('DataCount','<H'), ('DataOffset','<H'), ('DataDisplacement','<H=0'), ('SetupCount','<B=0'), ('Reserved2','<B=0'), ('SetupLength','_-Setup','SetupCount*2'), ('Setup',':'), )
# ('NameLength','_-Name','1'), # ('Name',':'), ('Pad1Length','_-Pad1','self["Pad1Length"]'), ('Pad1',':'), ('Trans_ParametersLength','_-Trans_Parameters','self["Trans_ParametersLength"]'), ('Trans_Parameters',':'), ('Pad2Length','_-Pad2','self["Pad2Length"]'), ('Pad2',':'), ('Trans_DataLength','_-Trans_Data','self["Trans_DataLength"]'), ('Trans_Data',':'), )
('Pad1Length','_-Pad1','self["Pad1Length"]'), ('Pad1',':'), ('Trans_ParametersLength','_-Trans_Parameters','self["Trans_ParametersLength"]'), ('Trans_Parameters',':'), ('Pad2Length','_-Pad2','self["Pad2Length"]'), ('Pad2',':'), ('Trans_DataLength','_-Trans_Data','self["Trans_DataLength"]'), ('Trans_Data',':'), )
############# SMB_COM_QUERY_INFORMATION (0x08)
('BufferFormat','B=4'), ('FileName','z'), ) ('BufferFormat','B=4'), ('FileName','u'), )
('FileAttributes','<H'), ('LastWriteTime','<L'), ('FileSize','<L'), ('Reserved','"0123456789'), )
############# SMB_COM_TRANSACTION (0x25) ('TotalParameterCount','<H'), ('TotalDataCount','<H'), ('MaxParameterCount','<H=1024'), ('MaxDataCount','<H=65504'), ('MaxSetupCount','<B=0'), ('Reserved1','<B=0'), ('Flags','<H=0'), ('Timeout','<L=0'), ('Reserved2','<H=0'), ('ParameterCount','<H'), ('ParameterOffset','<H'), ('DataCount','<H'), ('DataOffset','<H'), ('SetupCount','<B=len(Setup)//2'), ('Reserved3','<B=0'), ('SetupLength','_-Setup','SetupCount*2'), ('Setup',':'), )
('TotalParameterCount','<H'), ('TotalDataCount','<H'), ('Reserved1','<H=0'), ('ParameterCount','<H'), ('ParameterOffset','<H'), ('ParameterDisplacement','<H=0'), ('DataCount','<H'), ('DataOffset','<H'), ('DataDisplacement','<H=0'), ('SetupCount','<B'), ('Reserved2','<B=0'), ('SetupLength','_-Setup','SetupCount*2'), ('Setup',':'), )
# TODO: We should merge these both. But this will require fixing # the instances where this structure is used on the client side ('Name','z'), ('Trans_ParametersLength','_-Trans_Parameters'), ('Trans_Parameters',':'), ('Trans_DataLength','_-Trans_Data'), ('Trans_Data',':'), ) ('Pad','B'), ('Name','u'), ('Trans_ParametersLength','_-Trans_Parameters'), ('Trans_Parameters',':'), ('Trans_DataLength','_-Trans_Data'), ('Trans_Data',':'), )
('NameLength','_-Name'), ('Name',':'), ('Trans_ParametersLength','_-Trans_Parameters'), ('Trans_Parameters',':'), ('Trans_DataLength','_-Trans_Data'), ('Trans_Data',':'), )
('Trans_ParametersLength','_-Trans_Parameters'), ('Trans_Parameters',':'), ('Trans_DataLength','_-Trans_Data'), ('Trans_Data',':'), )
############# SMB_COM_READ_ANDX (0x2E) ('Fid','<H'), ('Offset','<L'), ('MaxCount','<H'), ('MinCount','<H=MaxCount'), ('_reserved','<L=0x0'), ('Remaining','<H=MaxCount'), ('HighOffset','<L=0'), )
('Fid','<H'), ('Offset','<L'), ('MaxCount','<H'), ('MinCount','<H=MaxCount'), ('_reserved','<L=0xffffffff'), ('Remaining','<H=MaxCount'), )
('Remaining','<H=0'), ('DataMode','<H=0'), ('_reserved','<H=0'), ('DataCount','<H'), ('DataOffset','<H'), ('DataCount_Hi','<L'), ('_reserved2','6s=""'), )
############# SMB_COM_ECHO (0x2B) ('Data',':'), )
('EchoCount','<H'), )
('Data',':'), )
('SequenceNumber','<H=1'), )
############# SMB_COM_QUERY_INFORMATION_DISK (0x80) ('TotalUnits','<H'), ('BlocksPerUnit','<H'), ('BlockSize','<H'), ('FreeUnits','<H'), ('Reserved','<H=0'), )
############# SMB_COM_LOGOFF_ANDX (0x74)
############# SMB_COM_CLOSE (0x04) ('FID','<H'), ('Time','<L=0'), )
############# SMB_COM_FLUSH (0x05) ('FID','<H'), )
############# SMB_COM_CREATE_DIRECTORY (0x00) ('BufferFormat','<B=4'), ('DirectoryName','z'), ) ('BufferFormat','<B=4'), ('DirectoryName','u'), )
############# SMB_COM_DELETE (0x06) ('BufferFormat','<B=4'), ('FileName','z'), ) ('BufferFormat','<B=4'), ('FileName','u'), )
('SearchAttributes','<H'), )
############# SMB_COM_DELETE_DIRECTORY (0x01) ('BufferFormat','<B=4'), ('DirectoryName','z'), ) ('BufferFormat','<B=4'), ('DirectoryName','u'), )
############# SMB_COM_CHECK_DIRECTORY (0x10) ('BufferFormat','<B=4'), ('DirectoryName','z'), ) ('BufferFormat','<B=4'), ('DirectoryName','u'), )
############# SMB_COM_RENAME (0x07) ('SearchAttributes','<H'), )
('BufferFormat1','<B=4'), ('OldFileName','z'), ('BufferFormat2','<B=4'), ('NewFileName','z'), ) ('BufferFormat1','<B=4'), ('OldFileName','u'), ('BufferFormat2','<B=4'), ('Pad','B=0'), ('NewFileName','u'), )
############# SMB_COM_OPEN (0x02) ('DesiredAccess','<H=0'), ('SearchAttributes','<H=0'), )
('FileNameFormat','"\x04'), ('FileName','z'), ) ('FileNameFormat','"\x04'), ('FileName','u'), )
('Fid','<H=0'), ('FileAttributes','<H=0'), ('LastWriten','<L=0'), ('FileSize','<L=0'), ('GrantedAccess','<H=0'), )
############# EXTENDED SECURITY CLASSES ('DialectIndex','<H'), ('SecurityMode','<B'), ('MaxMpxCount','<H'), ('MaxNumberVcs','<H'), ('MaxBufferSize','<L'), ('MaxRawSize','<L'), ('SessionKey','<L'), ('Capabilities','<L'), ('LowDateTime','<L'), ('HighDateTime','<L'), ('ServerTimeZone','<H'), ('ChallengeLength','<B'), )
('ServerGUID','16s'), ('SecurityBlob',':'), )
('DialectIndex','<H'), ('SecurityMode','<B'), ('MaxMpxCount','<H'), ('MaxNumberVcs','<H'), ('MaxBufferSize','<L'), ('MaxRawSize','<L'), ('SessionKey','<L'), ('Capabilities','<L'), ('LowDateTime','<L'), ('HighDateTime','<L'), ('ServerTimeZone','<H'), ('ChallengeLength','<B'), )
('ChallengeLength','_-Challenge','self["ChallengeLength"]'), ('Challenge',':'), ('Payload',':'), # For some reason on an old Linux this field is not present, we have to check this out. There must be a flag stating this. ('DomainName','_'), ('ServerName','_'), ) #self['ChallengeLength']=8
# SMB Command Codes # Used by Xenix/Unix 0x60 - 0x6E
# TRANSACT codes
# TRANSACT2 codes
# Security Share Mode (Used internally by SMB class)
# Security Auth Mode (Used internally by SMB class)
# Raw Mode Mask (Used internally by SMB class. Good for dialect up to and including LANMAN2.1)
# Capabilities Mask (Used internally by SMB class. Good for dialect NT LM 0.12)
# Flags1 Mask
# Flags2 Mask
# Dialect's Security Mode flags
# Tree Connect AndX Response optionalSuppor flags
UDP=0, session=None, negPacket=None): # The uid attribute will be set when the client calls the login() method
# Credentials
# Negotiate Protocol Result, used everywhere # Could be extended or not, flags should be checked before
# Signing stuff
# Base flags (default flags, can be overridden using set_flags())
self.__timeout = 60 else:
# If port 445 and the name sent is *SMBSERVER we're setting the name to the IP. # This is to help some old applications still believing # *SMSBSERVER will work against modern OSes. If port is NETBIOS_SESSION_PORT the user better # know about *SMBSERVER's limitations self.__remote_name = remote_host
# This is on purpose. I'm still not convinced to do a socket.gethostname() if not specified else: self.__client_name = my_name
# If destination port is 139 yes, there's some client disclosure
self._sess = nmb.NetBIOSUDPSession(my_name, remote_name, remote_host, host_type, sess_port, self.__timeout) else:
# Initialize session values (_dialect_data and _dialect_parameters)
# Call login() without any authentication information to # setup a session if the remote server # is in share mode. self.login('', '') else: self._sess = session self.neg_session(negPacket = negPacket) # Call login() without any authentication information to # setup a session if the remote server # is in share mode. if (self._dialects_parameters['SecurityMode'] & SMB.SECURITY_SHARE_MASK) == SMB.SECURITY_SHARE_SHARE: self.login('', '')
def ntlm_supported(): return False
return self._doKerberos
self.__remote_name = name return True
prev_timeout = self.__timeout self.__timeout = timeout return prev_timeout
return self.__timeout
def use_timeout(self, timeout): prev_timeout = self.set_timeout(timeout) try: yield finally: self.set_timeout(prev_timeout)
return self._sess
return self.tid
return self.fid
return self._action & SMB_SETUP_GUEST
def __decode_trans(params, data): totparamcnt, totdatacnt, _, paramcnt, paramoffset, paramds, datacnt, dataoffset, datads, setupcnt = unpack('<HHHHHHHHHB', params[:19]) if paramcnt + paramds < totparamcnt or datacnt + datads < totdatacnt: has_more = 1 else: has_more = 0 paramoffset = paramoffset - 55 - setupcnt * 2 dataoffset = dataoffset - 55 - setupcnt * 2 return has_more, params[20:20 + setupcnt * 2], data[paramoffset:paramoffset + paramcnt], data[dataoffset:dataoffset + datacnt]
# TODO: Move this to NewSMBPacket, it belongs there # This logic MUST be applied for messages sent in response to any of the higher-layer actions and in # compliance with the message sequencing rules. # * The client or server that sends the message MUST provide the 32-bit sequence number for this # message, as specified in sections 3.2.4.1 and 3.3.4.1. # * The SMB_FLAGS2_SMB_SECURITY_SIGNATURE flag in the header MUST be set. # * To generate the signature, a 32-bit sequence number is copied into the # least significant 32 bits of the SecuritySignature field and the remaining # 4 bytes are set to 0x00. # * The MD5 algorithm, as specified in [RFC1321], MUST be used to generate a hash of the SMB # message from the start of the SMB Header, which is defined as follows. # CALL MD5Init( md5context ) # CALL MD5Update( md5context, Connection.SigningSessionKey ) # CALL MD5Update( md5context, Connection.SigningChallengeResponse ) # CALL MD5Update( md5context, SMB message ) # CALL MD5Final( digest, md5context ) # SET signature TO the first 8 bytes of the digest # The resulting 8-byte signature MUST be copied into the SecuritySignature field of the SMB Header, # after which the message can be transmitted.
#print "seq(%d) signingSessionKey %r, signingChallengeResponse %r" % (self._SignSequenceNumber, signingSessionKey, signingChallengeResponse) # Sign with the sequence # Replace sequence with acual hash self._SignSequenceNumber +=1 else:
# Let's check signature = packet['SecurityFeatures'] #print "Signature received: %r " % signature self.signSMB(packet, signingSessionKey, signingChallengeResponse) #print "Signature calculated: %r" % packet['SecurityFeatures'] if self._SignatureVerificationEnabled is not True: self._SignSequenceNumber -= 1 return packet['SecurityFeatures'] == signature
#At least on AIX, PIDs can exceed 16 bits, so we mask them out # set flags
def isValidAnswer(s, cmd): while 1: if s.rawData(): if s.get_command() == cmd: 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) else: break return 0
# If server speaks Unicode, let's set that flag from now on self.__flags2 |= SMB.FLAGS2_UNICODE
# Whether we choose it or it is enforced by the server, we go for extended security # Let's setup some variable for later use
# Interestingly, the security Blob might be missing sometimes. #spnego = SPNEGO_NegTokenInit(self._dialects_data['SecurityBlob']) #for i in spnego['MechTypes']: # print "Mech Found: %s" % MechTypes[i]
# If not, let's try the old way else: if self._dialects_data['ServerName'] is not None: self.__server_name = self._dialects_data['ServerName']
if self._dialects_parameters['DialectIndex'] == 0xffff: raise UnsupportedFeature("Remote server does not know NT LM 0.12") return 1 else: return 0
else: self.set_flags(flags2=flags2 & (~SMB.FLAGS2_EXTENDED_SECURITY))
else:
return parsePacket( NewSMBPacket( data = negPacket))
LOG.warning("[MS-CIFS] This is an original Core Protocol command.This command has been deprecated.Client Implementations SHOULD use SMB_COM_TREE_CONNECT_ANDX")
# return 0x800 if password: # Password is only encrypted if the server passed us an "encryption" during protocol dialect if self._dialects_parameters['ChallengeLength'] > 0: # this code is untested password = self.get_ntlmv1_response(ntlm.compute_lmhash(password))
if not unicode_support: if unicode_convert: path = str(path) else: raise Exception('SMB: Can\t conver path from unicode!')
smb = NewSMBPacket() treeConnect = SMBCommand(SMB.SMB_COM_TREE_CONNECT) treeConnect['Parameters'] = SMBTreeConnect_Parameters() treeConnect['Data'] = SMBTreeConnect_Data() treeConnect['Data']['Path'] = path.upper() treeConnect['Data']['Password'] = password treeConnect['Data']['Service'] = service smb.addCommand(treeConnect) self.sendSMB(smb)
while 1: smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_TREE_CONNECT): # XXX Here we are ignoring the rest of the response return smb['Tid'] return smb['Tid']
return self._uid
self._uid = uid
# Password is only encrypted if the server passed us an "encryption" during protocol dialect if self._dialects_parameters['ChallengeLength'] > 0: # this code is untested password = self.get_ntlmv1_response(ntlm.compute_lmhash(password)) else:
else: raise Exception('SMB: Can\t convert path from unicode!')
else: smb = smb_packet
# Just in case this came with the full path ,let's just leave # the sharename, we'll take care of the rest
except Exception: remote_host = self.get_remote_host()
# filename = "\PIPE\epmapper"
# ntCreate = SMBCommand(SMB.SMB_COM_NT_CREATE_ANDX) # ntCreate['Parameters'] = SMBNtCreateAndX_Parameters() # ntCreate['Data'] = SMBNtCreateAndX_Data() # ntCreate['Parameters']['FileNameLength'] = len(filename) # ntCreate['Parameters']['CreateFlags'] = 0 # ntCreate['Parameters']['AccessMask'] = 0x3 # ntCreate['Parameters']['CreateOptions'] = 0x0 # ntCreate['Data']['FileName'] = filename
# smb.addCommand(ntCreate)
# XXX Here we are ignoring the rest of the response self.tid = smb['Tid'] return self.tid
# backwars compatibility
def getDialect():
#return self._dialects_data['ServerName']
self._SignatureEnabled = True self._SignSequenceNumber = 2 self._SigningSessionKey = key
if 'Challenge' in self._dialects_data.fields: return self._dialects_data['Challenge'] else: return None
timestamp = self._dialects_parameters['HighDateTime'] timestamp <<= 32 timestamp |= self._dialects_parameters['LowDateTime'] timestamp -= 116444736000000000 timestamp //= 10000000 d = datetime.datetime.utcfromtimestamp(timestamp) return d.strftime("%a, %d %b %Y %H:%M:%S GMT")
filename = filename.replace('/', '\\') filename = filename.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else filename
smb = NewSMBPacket() smb['Tid'] = tid
openFile = SMBCommand(SMB.SMB_COM_OPEN) openFile['Parameters'] = SMBOpen_Parameters() openFile['Parameters']['DesiredAccess'] = desired_access openFile['Parameters']['OpenMode'] = open_mode openFile['Parameters']['SearchAttributes'] = ATTR_READONLY | ATTR_HIDDEN | ATTR_ARCHIVE openFile['Data'] = SMBOpen_Data(flags=self.__flags2) openFile['Data']['FileName'] = filename
smb.addCommand(openFile)
self.sendSMB(smb)
smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_OPEN): # XXX Here we are ignoring the rest of the response openFileResponse = SMBCommand(smb['Data'][0]) openFileParameters = SMBOpenResponse_Parameters(openFileResponse['Parameters'])
return ( openFileParameters['Fid'], openFileParameters['FileAttributes'], openFileParameters['LastWriten'], openFileParameters['FileSize'], openFileParameters['GrantedAccess'], )
filename = filename.replace('/', '\\') filename = filename.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else filename
smb = NewSMBPacket() smb['Tid'] = tid
openFile = SMBCommand(SMB.SMB_COM_OPEN_ANDX) openFile['Parameters'] = SMBOpenAndX_Parameters() openFile['Parameters']['DesiredAccess'] = desired_access openFile['Parameters']['OpenMode'] = open_mode openFile['Parameters']['SearchAttributes'] = ATTR_READONLY | ATTR_HIDDEN | ATTR_ARCHIVE openFile['Data'] = SMBOpenAndX_Data(flags=self.__flags2) openFile['Data']['FileName'] = filename
if self.__flags2 & SMB.FLAGS2_UNICODE: openFile['Data']['Pad'] = 0x0
smb.addCommand(openFile)
self.sendSMB(smb)
smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_OPEN_ANDX): # XXX Here we are ignoring the rest of the response openFileResponse = SMBCommand(smb['Data'][0]) openFileParameters = SMBOpenAndXResponse_Parameters(openFileResponse['Parameters'])
return ( openFileParameters['Fid'], openFileParameters['FileAttributes'], openFileParameters['LastWriten'], openFileParameters['FileSize'], openFileParameters['GrantedAccess'], openFileParameters['FileType'], openFileParameters['IPCState'], openFileParameters['Action'], openFileParameters['ServerFid'], )
return 0
smb = NewSMBPacket() smb['Tid'] = tid
transCommand = SMBCommand(SMB.SMB_COM_TRANSACTION) transCommand['Parameters'] = SMBTransaction_Parameters() transCommand['Data'] = SMBTransaction_Data()
transCommand['Parameters']['Setup'] = setup transCommand['Parameters']['TotalParameterCount'] = len(param) transCommand['Parameters']['TotalDataCount'] = len(data)
transCommand['Parameters']['ParameterCount'] = len(param) transCommand['Parameters']['ParameterOffset'] = 32+3+28+len(setup)+len(name)
transCommand['Parameters']['DataCount'] = len(data) transCommand['Parameters']['DataOffset'] = transCommand['Parameters']['ParameterOffset'] + len(param)
transCommand['Data']['Name'] = name transCommand['Data']['Trans_Parameters'] = param transCommand['Data']['Trans_Data'] = data
if noAnswer: transCommand['Parameters']['Flags'] = TRANS_NO_RESPONSE
smb.addCommand(transCommand)
self.sendSMB(smb)
else: transCommand['Data']['Pad1'] = '' padLen = 0
pad2Len = (4 - (32+2+28 + len(command) + padLen + len(param)) % 4) % 4 transCommand['Data']['Pad2'] = '\xFF' * pad2Len else:
# Remove Potential Prefix Padding
max_buf_size = 65000 else:
max_buf_size = 65000 else:
return self.__server_os_major
return self.__server_os_minor
return self.__server_os_build
self.__server_os = os
return self.__server_lanman
# Login is required if share mode is user. # Otherwise only public services or services in share mode # are allowed.
return self._SignatureRequired
challenge = self._dialects_data['Challenge'] return ntlm.get_ntlmv1_response(key, challenge)
# Importing down here so pyasn1 is not required if kerberos is not used.
# login feature does not support unicode # disable it if enabled
# If TGT or TGS are specified, they are in the form of: # TGS['KDC_REP'] = the response from the server # TGS['cipher'] = the cipher used # TGS['sessionKey'] = the sessionKey # If we have hashes, normalize them lmhash = '0%s' % lmhash nthash = '0%s' % nthash except: pass
# First of all, we need to get a TGT for the user else: tgt = TGT['KDC_REP'] cipher = TGT['cipher'] sessionKey = TGT['sessionKey']
# Now that we have the TGT, we should ask for a TGS for cifs
else: tgs = TGS['KDC_REP'] cipher = TGS['cipher'] sessionKey = TGS['sessionKey']
# Are we required to sign SMB? If so we do it, if not we skip it
# Let's build a NegTokenInit with the NTLMSSP # TODO: In the future we should be able to choose different providers
# Kerberos v5 mech
# Let's extract the ticket from the TGS
# Now let's build the AP_REQ
# Key Usage 11 # AP-REQ Authenticator (includes application authenticator # subkey), encrypted with the application session key # (Section 5.5.1)
TypesMech['KRB5 - Kerberos 5']) + KRB5_AP_REQ + encoder.encode(apReq))
# Fake Data here, don't want to get us fingerprinted
# We will need to use this uid field for all future requests/responses
# Now we have to extract the blob to continue the auth process
# If smb sign required, let's enable it for the rest of the connection
# restore unicode flag if needed
else: raise Exception('Error: Could not login successfully')
# login feature does not support unicode # disable it if enabled
# Once everything's working we should join login methods into a single one # Are we required to sign SMB? If so we do it, if not we skip it
# Let's build a NegTokenInit with the NTLMSSP # TODO: In the future we should be able to choose different providers
# NTLMSSP
# Fake Data here, don't want to get us fingerprinted
# We will need to use this uid field for all future requests/responses
# Now we have to extract the blob to continue the auth process
# Let's parse some data and keep it to ourselves in case it is asked except UnicodeDecodeError: # For some reason, we couldn't decode Unicode here.. silently discard the operation pass except UnicodeDecodeError: # For some reason, we couldn't decode Unicode here.. silently discard the operation pass except UnicodeDecodeError: # For some reason, we couldn't decode Unicode here.. silently discard the operation pass
# Parse Version to know the target Operating system name. Not provided elsewhere anymore
# Are we required to sign SMB? If so we do it, if not we skip it
# Reusing the previous structure
# Storing some info for later use
# If smb sign required, let's enable it for the rest of the connection
# restore unicode flag if needed
else: raise Exception('Error: Could not login successfully')
self.__userName, self.__password, self.__domain, self.__lmhash, self.__nthash, self.__aesKey, self.__TGT, self.__TGS)
max_size = 65000 else:
# If we have hashes, normalize them lmhash = '0%s' % lmhash nthash = '0%s' % nthash
except: # If the target OS is Windows 5.0 or Samba, let's try using NTLMv1 if ntlm_fallback and ((self.get_server_lanman().find('Windows 2000') != -1) or (self.get_server_lanman().find('Samba') != -1)): self.login_extended(user, password, domain, lmhash, nthash, use_ntlmv2 = False) self.__isNTLMv2 = False else: raise elif ntlm_fallback: self.login_standard(user, password, domain, lmhash, nthash) self.__isNTLMv2 = False else: raise SessionError('Cannot authenticate against target, enable ntlm_fallback')
# login feature does not support unicode # disable it if enabled flags2 = self.__flags2 if flags2 & SMB.FLAGS2_UNICODE: self.__flags2 = flags2 & (flags2 ^ SMB.FLAGS2_UNICODE)
# Only supports NTLMv1 # Password is only encrypted if the server passed us an "encryption key" during protocol dialect negotiation if self._dialects_parameters['ChallengeLength'] > 0: if lmhash != '' or nthash != '': pwd_ansi = self.get_ntlmv1_response(lmhash) pwd_unicode = self.get_ntlmv1_response(nthash) elif password: lmhash = ntlm.compute_lmhash(password) nthash = ntlm.compute_nthash(password) pwd_ansi = self.get_ntlmv1_response(lmhash) pwd_unicode = self.get_ntlmv1_response(nthash) else: # NULL SESSION pwd_ansi = '' pwd_unicode = '' else: pwd_ansi = password pwd_unicode = ''
smb = NewSMBPacket()
sessionSetup = SMBCommand(SMB.SMB_COM_SESSION_SETUP_ANDX) sessionSetup['Parameters'] = SMBSessionSetupAndX_Parameters() sessionSetup['Data'] = SMBSessionSetupAndX_Data()
sessionSetup['Parameters']['MaxBuffer'] = 61440 sessionSetup['Parameters']['MaxMpxCount'] = 2 sessionSetup['Parameters']['VCNumber'] = os.getpid() & 0xFFFF # Value has to be expressed in 2 bytes sessionSetup['Parameters']['SessionKey'] = self._dialects_parameters['SessionKey'] sessionSetup['Parameters']['AnsiPwdLength'] = len(pwd_ansi) sessionSetup['Parameters']['UnicodePwdLength'] = len(pwd_unicode) sessionSetup['Parameters']['Capabilities'] = SMB.CAP_RAW_MODE | SMB.CAP_USE_NT_ERRORS | SMB.CAP_LARGE_READX | SMB.CAP_LARGE_WRITEX
sessionSetup['Data']['AnsiPwd'] = pwd_ansi sessionSetup['Data']['UnicodePwd'] = pwd_unicode sessionSetup['Data']['Account'] = str(user) sessionSetup['Data']['PrimaryDomain'] = str(domain) sessionSetup['Data']['NativeOS'] = str(os.name) sessionSetup['Data']['NativeLanMan'] = 'pysmb' smb.addCommand(sessionSetup)
self.sendSMB(smb)
smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_SESSION_SETUP_ANDX): # We will need to use this uid field for all future requests/responses self._uid = smb['Uid'] sessionResponse = SMBCommand(smb['Data'][0]) sessionParameters = SMBSessionSetupAndXResponse_Parameters(sessionResponse['Parameters']) sessionData = SMBSessionSetupAndXResponse_Data(flags = smb['Flags2'], data = sessionResponse['Data'])
self._action = sessionParameters['Action']
# Still gotta figure out how to do this with no EXTENDED_SECURITY if sessionParameters['Action'] & SMB_SETUP_USE_LANMAN_KEY == 0: self._SigningChallengeResponse = sessionSetup['Data']['UnicodePwd'] self._SigningSessionKey = nthash else: self._SigningChallengeResponse = sessionSetup['Data']['AnsiPwd'] self._SigningSessionKey = lmhash
#self._SignSequenceNumber = 1 #self.checkSignSMB(smb, self._SigningSessionKey ,self._SigningChallengeResponse) #self._SignatureEnabled = True self.__server_os = sessionData['NativeOS'] self.__server_lanman = sessionData['NativeLanMan'] self.__server_domain = sessionData['PrimaryDomain']
# restore unicode flag if needed if flags2 & SMB.FLAGS2_UNICODE: self.__flags2 |= SMB.FLAGS2_UNICODE
return 1 else: raise Exception('Error: Could not login successfully')
smb = NewSMBPacket() smb['Tid'] = tid
transCommand = SMBCommand(SMB.SMB_COM_TRANSACTION) transCommand['Parameters'] = SMBTransaction_Parameters() transCommand['Data'] = SMBTransaction_Data()
setup = '\x53\x00\x00\x00' name = '\\PIPE%s\x00' % pipe transCommand['Parameters']['Setup'] = setup transCommand['Parameters']['TotalParameterCount'] = 0 transCommand['Parameters']['TotalDataCount'] = 0 transCommand['Parameters']['MaxParameterCount'] = 0 transCommand['Parameters']['MaxDataCount'] = 0 transCommand['Parameters']['Timeout'] = timeout * 1000
transCommand['Parameters']['ParameterCount'] = 0 transCommand['Parameters']['ParameterOffset'] = 32+3+28+len(setup)+len(name)
transCommand['Parameters']['DataCount'] = 0 transCommand['Parameters']['DataOffset'] = 0
transCommand['Data']['Name'] = name transCommand['Data']['Trans_Parameters'] = '' transCommand['Data']['Trans_Data'] = ''
if noAnswer: transCommand['Parameters']['Flags'] = TRANS_NO_RESPONSE
smb.addCommand(transCommand) self.sendSMB(smb)
smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_TRANSACTION): return 1 return 0
if not max_size: max_size = self._dialects_parameters['MaxBufferSize'] # Read in multiple KB blocks
# max_size is not working, because although it would, the server returns an error (More data avail)
smb = NewSMBPacket() smb['Tid'] = tid
read = SMBCommand(SMB.SMB_COM_READ) read['Parameters'] = SMBRead_Parameters() read['Parameters']['Fid'] = fid read['Parameters']['Offset'] = offset read['Parameters']['Count'] = max_size smb.addCommand(read)
if wait_answer: while 1: self.sendSMB(smb) ans = self.recvSMB()
if ans.isValidAnswer(SMB.SMB_COM_READ): readResponse = SMBCommand(ans['Data'][0]) readData = SMBReadResponse_Data(readResponse['Data'])
return readData['Data']
return None
if (self._dialects_parameters['Capabilities'] & SMB.CAP_LARGE_READX) and self._SignatureEnabled is False: max_size = 65000 else: max_size = self._dialects_parameters['MaxBufferSize'] # Read in multiple KB blocks
# max_size is not working, because although it would, the server returns an error (More data avail)
else: smb = smb_packet
# XXX Here we are only using a few fields from the response
max_size = min(max_size, readAndXParameters['Remaining']) readAndX['Parameters']['Offset'] += count # XXX Offset is not important (apparently) else: self.sendSMB(smb) ans = self.recvSMB()
try: if ans.isValidAnswer(SMB.SMB_COM_READ_ANDX): return ans else: return None except: return ans
return None
if not max_size: max_size = self._dialects_parameters['MaxBufferSize'] # Read in multiple KB blocks
# max_size is not working, because although it would, the server returns an error (More data avail) smb = NewSMBPacket() smb['Tid'] = tid
readRaw = SMBCommand(SMB.SMB_COM_READ_RAW) readRaw['Parameters'] = SMBReadRaw_Parameters() readRaw['Parameters']['Fid'] = fid readRaw['Parameters']['Offset'] = offset readRaw['Parameters']['MaxCount'] = max_size smb.addCommand(readRaw)
self.sendSMB(smb) if wait_answer: data = self._sess.recv_packet(self.__timeout).get_trailer() if not data: # If there is no data it means there was an error data = self.read_andx(tid, fid, offset, max_size) return data
return None
smb = NewSMBPacket() smb['Tid'] = tid
write = SMBCommand(SMB.SMB_COM_WRITE) write['Parameters'] = SMBWrite_Parameters() write['Data'] = SMBWrite_Data() write['Parameters']['Fid'] = fid write['Parameters']['Count'] = len(data) write['Parameters']['Offset'] = offset write['Parameters']['Remaining'] = len(data) write['Data']['Data'] = data smb.addCommand(write)
self.sendSMB(smb)
if wait_answer: smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_WRITE): return smb return None
# First of all we gotta know what the MaxBuffSize is maxBuffSize = self._dialects_parameters['MaxBufferSize'] if len(data) > maxBuffSize: chunks_size = maxBuffSize - 60 writeAndX['Parameters']['WriteMode'] = 0x0c sendData = b'\xff\xff' + data totalLen = len(sendData) writeAndX['Parameters']['DataLength'] = chunks_size writeAndX['Parameters']['Remaining'] = totalLen-2 writeAndX['Data'] = sendData[:chunks_size]
self.sendSMB(smb) if wait_answer: smbResp = self.recvSMB() smbResp.isValidAnswer(SMB.SMB_COM_WRITE_ANDX)
alreadySent = chunks_size sendData = sendData[chunks_size:]
while alreadySent < totalLen: writeAndX['Parameters']['WriteMode'] = 0x04 writeAndX['Parameters']['DataLength'] = len(sendData[:chunks_size]) writeAndX['Data'] = sendData[:chunks_size] self.sendSMB(smb) if wait_answer: smbResp = self.recvSMB() smbResp.isValidAnswer(SMB.SMB_COM_WRITE_ANDX) alreadySent += writeAndX['Parameters']['DataLength'] sendData = sendData[chunks_size:]
return smbResp
else: smb = smb_packet
return None
LOG.warning("[MS-CIFS] This command was introduced in the CorePlus dialect, but is often listed as part of the LAN Manager 1.0 dialect.This command has been deprecated.Clients SHOULD use SMB_COM_WRITE_ANDX") smb = NewSMBPacket() smb['Tid'] = tid
writeRaw = SMBCommand(SMB.SMB_COM_WRITE_RAW) writeRaw['Parameters'] = SMBWriteRaw_Parameters() writeRaw['Parameters']['Fid'] = fid writeRaw['Parameters']['Offset'] = offset writeRaw['Parameters']['Count'] = len(data) writeRaw['Parameters']['DataLength'] = 0 writeRaw['Parameters']['DataOffset'] = 0 smb.addCommand(writeRaw)
self.sendSMB(smb) self._sess.send_packet(data)
if wait_answer: smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_WRITE_RAW): return smb return None
self.send_trans(tid,pack('<HH', 0x26, fid),'\\PIPE\\\x00','',data, noAnswer = noAnswer)
if noAnswer or not waitAnswer: return smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_TRANSACTION): transResponse = SMBCommand(smb['Data'][0]) transParameters = SMBTransactionResponse_Parameters(transResponse['Parameters']) return transResponse['Data'][-transParameters['TotalDataCount']:] # Remove Potential Prefix Padding return None
s = self.recvSMB() if s.isValidAnswer(SMB.SMB_COM_TRANSACTION): transResponse = SMBCommand(s['Data'][0]) transParameters = SMBTransactionResponse_Parameters(transResponse['Parameters']) return transResponse['Data'][-transParameters['TotalDataCount']:] # Remove Potential Prefix Padding return None
else: smb = smb_packet
else:
# XXX Here we are ignoring the rest of the response
# Let's clear some fields so you can login again under the same session
SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_READONLY | \ SMB_FILE_ATTRIBUTE_ARCHIVE else:
# Save the SID for resume operations
record['ShortName'].decode('latin-1') record['FileName'].decode('latin-1')
record['EndOfFile'], record['AllocationSize'], record['ExtFileAttributes'], shortname, filename) else: # More data to search? resume_filename = record['FileName'] findNextParameter = SMBFindNext2_Parameters() findNextParameter['SID'] = sid findNextParameter['SearchCount'] = 1024 findNextParameter['InformationLevel'] = SMB_FIND_FILE_BOTH_DIRECTORY_INFO findNextParameter['ResumeKey'] = 0 findNextParameter['Flags'] = SMB_FIND_RETURN_RESUME_KEYS | SMB_FIND_CLOSE_AT_EOS if self.__flags2 & SMB.FLAGS2_UNICODE: findNextParameter['FileName'] = resume_filename + b'\x00\x00' else: findNextParameter['FileName'] = resume_filename + '\x00' self.send_trans2(tid, SMB.TRANS2_FIND_NEXT2, '\x00', findNextParameter, '') findData = b'' findNext2ParameterBlock = b'' totalDataCount = 1 while len(findData) < totalDataCount: resp = self.recvSMB()
if resp.isValidAnswer(SMB.SMB_COM_TRANSACTION2): trans2Response = SMBCommand(resp['Data'][0]) trans2Parameters = SMBTransaction2Response_Parameters(trans2Response['Parameters']) totalDataCount = trans2Parameters['TotalDataCount'] findNext2ParameterBlock += trans2Response['Data'][trans2Parameters['ParameterOffset']-55:][:trans2Parameters['ParameterCount']] findData += trans2Response['Data'][trans2Parameters['DataOffset']-55:] findParameterBlock = SMBFindNext2Response_Parameters(findNext2ParameterBlock) else: finally:
finally:
finally:
filename = filename.replace('/', '\\')
fid = -1 tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password) try: fid = self.nt_create_andx(tid, filename, shareAccessMode = shareAccessMode, disposition = mode) self.__nonraw_stor_file(tid, fid, offset, 0, callback) finally: if fid >= 0: self.close(tid, fid) self.disconnect_tree(tid)
finally:
# Perform a list to ensure the path exists
finally:
# Check that the directory exists
finally:
return 0 finally:
return 0 finally:
max_buf_size = 65000 else:
""" [MS-CIFS]: 2.2.4.62.1 SMB_COM_NT_TRANSACT request. :param tid: :param subcommand: The transaction subcommand code :param max_param_count: This field MUST be set as specified in the subsections of Transaction subcommands. :param setup: Transaction context to the server, depends on transaction subcommand. :param param: Subcommand parameter bytes if any, depends on transaction subcommand. :param data: Subcommand data bytes if any, depends on transaction subcommand. :return: Buffer relative to requested subcommand. """ smb_packet = NewSMBPacket() smb_packet['Tid'] = tid # setup depends on NT_TRANSACT subcommands so it may be 0. setup_bytes = pack('<H', setup) if setup != '' else ''
transCommand = SMBCommand(SMB.SMB_COM_NT_TRANSACT) transCommand['Parameters'] = SMBNTTransaction_Parameters() transCommand['Parameters']['MaxDataCount'] = self._dialects_parameters['MaxBufferSize'] transCommand['Parameters']['Setup'] = setup_bytes transCommand['Parameters']['Function'] = subcommand transCommand['Parameters']['TotalParameterCount'] = len(param) transCommand['Parameters']['TotalDataCount'] = len(data) transCommand['Parameters']['MaxParameterCount'] = max_param_count transCommand['Parameters']['MaxSetupCount'] = 0
transCommand['Data'] = SMBNTTransaction_Data()
# SMB header size + SMB_COM_NT_TRANSACT parameters size + length of setup bytes. offset = 32 + 3 + 38 + len(setup_bytes) transCommand['Data']['Pad1'] = '' if offset % 4 != 0: transCommand['Data']['Pad1'] = '\0' * (4 - offset % 4) offset += (4 - offset % 4) # pad1 length
if len(param) > 0: transCommand['Parameters']['ParameterOffset'] = offset else: transCommand['Parameters']['ParameterOffset'] = 0
offset += len(param) transCommand['Data']['Pad2'] = '' if offset % 4 != 0: transCommand['Data']['Pad2'] = '\0' * (4 - offset % 4) offset += (4 - offset % 4)
if len(data) > 0: transCommand['Parameters']['DataOffset'] = offset else: transCommand['Parameters']['DataOffset'] = 0
transCommand['Parameters']['DataCount'] = len(data) transCommand['Parameters']['ParameterCount'] = len(param) transCommand['Data']['NT_Trans_Parameters'] = param transCommand['Data']['NT_Trans_Data'] = data smb_packet.addCommand(transCommand)
self.sendSMB(smb_packet)
""" [MS-CIFS]: 2.2.7.6.1 NT_TRANSACT_QUERY_SECURITY_DESC 0x0006 :param tid: valid tree id. :param fid: valid file handle. :param additional_information: SecurityInfoFields. default = owner + group + dacl ie. 7 :return: security descriptor buffer """ self.send_nt_trans(tid, subcommand=0x0006, max_param_count=4, param=pack('<HHL', fid, 0x0000, additional_information)) resp = self.recvSMB() if resp.isValidAnswer(SMB.SMB_COM_NT_TRANSACT): nt_trans_response = SMBCommand(resp['Data'][0]) nt_trans_parameters = SMBNTTransactionResponse_Parameters(nt_trans_response['Parameters']) # Remove Potential Prefix Padding return nt_trans_response['Data'][-nt_trans_parameters['TotalDataCount']:]
smb = NewSMBPacket() comEcho = SMBCommand(SMB.SMB_COM_ECHO) comEcho['Parameters'] = SMBEcho_Parameters() comEcho['Data'] = SMBEcho_Data() comEcho['Parameters']['EchoCount'] = count comEcho['Data']['Data'] = text smb.addCommand(comEcho)
self.sendSMB(smb)
for i in range(count): resp = self.recvSMB() resp.isValidAnswer(SMB.SMB_COM_ECHO) return True
2: 'File not found', 3: 'Invalid directory', 4: 'Too many open files', 5: 'Access denied', 6: 'Invalid file handle. Please file a bug report.', 7: 'Memory control blocks destroyed', 8: 'Out of memory', 9: 'Invalid memory block address', 10: 'Invalid environment', 11: 'Invalid format', 12: 'Invalid open mode', 13: 'Invalid data', 15: 'Invalid drive', 16: 'Attempt to remove server\'s current directory', 17: 'Not the same device', 18: 'No files found', 32: 'Sharing mode conflicts detected', 33: 'Lock request conflicts detected', 80: 'File already exists' }
2: 'Bad password', 4: 'Access denied', 5: 'Invalid tid. Please file a bug report.', 6: 'Invalid network name', 7: 'Invalid device', 49: 'Print queue full', 50: 'Print queue full', 51: 'EOF on print queue dump', 52: 'Invalid print file handle', 64: 'Command not recognized. Please file a bug report.', 65: 'Internal server error', 67: 'Invalid path', 69: 'Invalid access permissions', 71: 'Invalid attribute mode', 81: 'Server is paused', 82: 'Not receiving messages', 83: 'No room to buffer messages', 87: 'Too many remote user names', 88: 'Operation timeout', 89: 'Out of resources', 91: 'Invalid user handle. Please file a bug report.', 250: 'Temporarily unable to support raw mode for transfer', 251: 'Temporarily unable to support raw mode for transfer', 252: 'Continue in MPX mode', 65535: 'Unsupported function' }
20: 'Unknown unit', 21: 'Drive not ready', 22: 'Unknown command', 23: 'CRC error', 24: 'Bad request', 25: 'Seek error', 26: 'Unknown media type', 27: 'Sector not found', 28: 'Printer out of paper', 29: 'Write fault', 30: 'Read fault', 31: 'General failure', 32: 'Open conflicts with an existing open', 33: 'Invalid lock request', 34: 'Wrong disk in drive', 35: 'FCBs not available', 36: 'Sharing buffer exceeded' } |