# Impacket - Collection of Python classes for working with network protocols. # # Copyright Fortra, LLC and its affiliated companies # # All rights reserved. # # This software is provided under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # Author: # Altered source done by Alberto Solino (@agsolino) # # Contributors: # Raz Kissos (@covertivy) # # Copyright and license note from Pysmb: # # Copyright (C) 2001 Michael Teo # 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. # # 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 # from __future__ import division from __future__ import print_function import os import socket from binascii import a2b_hex import datetime from struct import pack, unpack, pack_into from ctypes import BigEndianStructure, c_uint32 from contextlib import contextmanager from pyasn1.type.univ import noValue from impacket import nmb, ntlm, nt_errors, LOG from impacket.structure import Structure from impacket.spnego import SPNEGO_NegTokenInit, TypesMech, SPNEGO_NegTokenResp, ASN1_OID, asn1encode, ASN1_AID from impacket.krb5.gssapi import KRB5_AP_REQ import six # For signing import hashlib unicode_support = 0 unicode_convert = 1 # Dialect for SMB1 SMB_DIALECT = 'NT LM 0.12' # Shared Device Type SHARED_DISK = 0x00 SHARED_DISK_HIDDEN = 0x80000000 SHARED_PRINT_QUEUE = 0x01 SHARED_DEVICE = 0x02 SHARED_IPC = 0x03 # Extended attributes mask ATTR_ARCHIVE = 0x020 ATTR_COMPRESSED = 0x800 ATTR_NORMAL = 0x080 ATTR_HIDDEN = 0x002 ATTR_READONLY = 0x001 ATTR_TEMPORARY = 0x100 ATTR_DIRECTORY = 0x010 ATTR_SYSTEM = 0x004 # Service Type SERVICE_DISK = 'A:' SERVICE_PRINTER = 'LPT1:' SERVICE_IPC = 'IPC' SERVICE_COMM = 'COMM' SERVICE_ANY = '?????' # Server Type (Can be used to mask with SMBMachine.get_type() or SMBDomain.get_type()) SV_TYPE_WORKSTATION = 0x00000001 SV_TYPE_SERVER = 0x00000002 SV_TYPE_SQLSERVER = 0x00000004 SV_TYPE_DOMAIN_CTRL = 0x00000008 SV_TYPE_DOMAIN_BAKCTRL = 0x00000010 SV_TYPE_TIME_SOURCE = 0x00000020 SV_TYPE_AFP = 0x00000040 SV_TYPE_NOVELL = 0x00000080 SV_TYPE_DOMAIN_MEMBER = 0x00000100 SV_TYPE_PRINTQ_SERVER = 0x00000200 SV_TYPE_DIALIN_SERVER = 0x00000400 SV_TYPE_XENIX_SERVER = 0x00000800 SV_TYPE_NT = 0x00001000 SV_TYPE_WFW = 0x00002000 SV_TYPE_SERVER_NT = 0x00004000 SV_TYPE_POTENTIAL_BROWSER = 0x00010000 SV_TYPE_BACKUP_BROWSER = 0x00020000 SV_TYPE_MASTER_BROWSER = 0x00040000 SV_TYPE_DOMAIN_MASTER = 0x00080000 SV_TYPE_LOCAL_LIST_ONLY = 0x40000000 SV_TYPE_DOMAIN_ENUM = 0x80000000 # Options values for SMB.stor_file and SMB.retr_file SMB_O_CREAT = 0x10 # Create the file if file does not exists. Otherwise, operation fails. SMB_O_EXCL = 0x00 # When used with SMB_O_CREAT, operation fails if file exists. Cannot be used with SMB_O_OPEN. SMB_O_OPEN = 0x01 # Open the file if the file exists SMB_O_TRUNC = 0x02 # Truncate the file if the file exists # Share Access Mode SMB_SHARE_COMPAT = 0x00 SMB_SHARE_DENY_EXCL = 0x10 SMB_SHARE_DENY_WRITE = 0x20 SMB_SHARE_DENY_READEXEC = 0x30 SMB_SHARE_DENY_NONE = 0x40 SMB_ACCESS_READ = 0x00 SMB_ACCESS_WRITE = 0x01 SMB_ACCESS_READWRITE = 0x02 SMB_ACCESS_EXEC = 0x03 TRANS_DISCONNECT_TID = 1 TRANS_NO_RESPONSE = 2 STATUS_SUCCESS = 0x00000000 STATUS_LOGON_FAILURE = 0xC000006D STATUS_LOGON_TYPE_NOT_GRANTED = 0xC000015B MAX_TFRAG_SIZE = 5840 EVASION_NONE = 0 EVASION_LOW = 1 EVASION_HIGH = 2 EVASION_MAX = 3 RPC_X_BAD_STUB_DATA = 0x6F7 # SMB_FILE_ATTRIBUTES SMB_FILE_ATTRIBUTE_NORMAL = 0x0000 SMB_FILE_ATTRIBUTE_READONLY = 0x0001 SMB_FILE_ATTRIBUTE_HIDDEN = 0x0002 SMB_FILE_ATTRIBUTE_SYSTEM = 0x0004 SMB_FILE_ATTRIBUTE_VOLUME = 0x0008 SMB_FILE_ATTRIBUTE_DIRECTORY = 0x0010 SMB_FILE_ATTRIBUTE_ARCHIVE = 0x0020 SMB_SEARCH_ATTRIBUTE_READONLY = 0x0100 SMB_SEARCH_ATTRIBUTE_HIDDEN = 0x0200 SMB_SEARCH_ATTRIBUTE_SYSTEM = 0x0400 SMB_SEARCH_ATTRIBUTE_DIRECTORY = 0x1000 SMB_SEARCH_ATTRIBUTE_ARCHIVE = 0x2000 # Session SetupAndX Action flags SMB_SETUP_GUEST = 0x01 SMB_SETUP_USE_LANMAN_KEY = 0x02 # QUERY_INFORMATION levels SMB_INFO_ALLOCATION = 0x0001 SMB_INFO_VOLUME = 0x0002 FILE_FS_SIZE_INFORMATION = 0x0003 SMB_QUERY_FS_VOLUME_INFO = 0x0102 SMB_QUERY_FS_SIZE_INFO = 0x0103 SMB_QUERY_FILE_EA_INFO = 0x0103 SMB_QUERY_FS_DEVICE_INFO = 0x0104 SMB_QUERY_FS_ATTRIBUTE_INFO = 0x0105 SMB_QUERY_FILE_BASIC_INFO = 0x0101 SMB_QUERY_FILE_STANDARD_INFO = 0x0102 SMB_QUERY_FILE_ALL_INFO = 0x0107 SMB_QUERY_FILE_STREAM_INFO = 0x0109 FILE_FS_FULL_SIZE_INFORMATION = 0x03EF # SET_INFORMATION levels SMB_INFO_STANDARD = 0x0001 SMB_INFO_SET_EAS = 0x0002 SMB_SET_FILE_BASIC_INFO = 0x0101 SMB_SET_FILE_DISPOSITION_INFO = 0x0102 SMB_SET_FILE_ALLOCATION_INFO = 0x0103 SMB_SET_FILE_END_OF_FILE_INFO = 0x0104 # Device Type [MS-CIFS] 2.2.8.2.5 FILE_DEVICE_BEEP = 0x0001 FILE_DEVICE_CD_ROM = 0x0002 FILE_DEVICE_CD_ROM_FILE_SYSTEM = 0x0003 FILE_DEVICE_CONTROLLER = 0x0004 FILE_DEVICE_DATALINK = 0x0005 FILE_DEVICE_DFS = 0x0006 FILE_DEVICE_DISK = 0x0007 FILE_DEVICE_DISK_FILE_SYSTEM = 0x0008 FILE_DEVICE_FILE_SYSTEM = 0x0009 FILE_DEVICE_INPORT_PORT = 0x000a FILE_DEVICE_KEYBOARD = 0x000b FILE_DEVICE_MAILSLOT = 0x000c FILE_DEVICE_MIDI_IN = 0x000d FILE_DEVICE_MIDI_OUT = 0x000e FILE_DEVICE_MOUSE = 0x000f FILE_DEVICE_MULTI_UNC_PROVIDER = 0x0010 FILE_DEVICE_NAMED_PIPE = 0x0011 FILE_DEVICE_NETWORK = 0x0012 FILE_DEVICE_NETWORK_BROWSER = 0x0013 FILE_DEVICE_NETWORK_FILE_SYSTEM = 0x0014 FILE_DEVICE_NULL = 0x0015 FILE_DEVICE_PARALLEL_PORT = 0x0016 FILE_DEVICE_PHYSICAL_NETCARD = 0x0017 FILE_DEVICE_PRINTER = 0x0018 FILE_DEVICE_SCANNER = 0x0019 FILE_DEVICE_SERIAL_MOUSE_PORT = 0x001a FILE_DEVICE_SERIAL_PORT = 0x001b FILE_DEVICE_SCREEN = 0x001c FILE_DEVICE_SOUND = 0x001d FILE_DEVICE_STREAMS = 0x001e FILE_DEVICE_TAPE = 0x001f FILE_DEVICE_TAPE_FILE_SYSTEM = 0x0020 FILE_DEVICE_TRANSPORT = 0x0021 FILE_DEVICE_UNKNOWN = 0x0022 FILE_DEVICE_VIDEO = 0x0023 FILE_DEVICE_VIRTUAL_DISK = 0x0024 FILE_DEVICE_WAVE_IN = 0x0025 FILE_DEVICE_WAVE_OUT = 0x0026 FILE_DEVICE_8042_PORT = 0x0027 FILE_DEVICE_NETWORK_REDIRECTOR = 0x0028 FILE_DEVICE_BATTERY = 0x0029 FILE_DEVICE_BUS_EXTENDER = 0x002a FILE_DEVICE_MODEM = 0x002b FILE_DEVICE_VDM = 0x002c # Device Characteristics [MS-CIFS] 2.2.8.2.5 FILE_REMOVABLE_MEDIA = 0x0001 FILE_READ_ONLY_DEVICE = 0x0002 FILE_FLOPPY_DISKETTE = 0x0004 FILE_WRITE_ONCE_MEDIA = 0x0008 FILE_REMOTE_DEVICE = 0x0010 FILE_DEVICE_IS_MOUNTED = 0x0020 FILE_VIRTUAL_VOLUME = 0x0040 # File System Attributes FILE_CASE_SENSITIVE_SEARCH = 0x00000001 FILE_CASE_PRESERVED_NAMES = 0x00000002 FILE_UNICODE_ON_DISK = 0x00000004 FILE_PERSISTENT_ACLS = 0x00000008 FILE_FILE_COMPRESSION = 0x00000010 FILE_VOLUME_IS_COMPRESSED = 0x00008000 # FIND_FIRST2 flags and levels SMB_FIND_CLOSE_AFTER_REQUEST = 0x0001 SMB_FIND_CLOSE_AT_EOS = 0x0002 SMB_FIND_RETURN_RESUME_KEYS = 0x0004 SMB_FIND_CONTINUE_FROM_LAST = 0x0008 SMB_FIND_WITH_BACKUP_INTENT = 0x0010 FILE_DIRECTORY_FILE = 0x00000001 FILE_DELETE_ON_CLOSE = 0x00001000 FILE_NON_DIRECTORY_FILE = 0x00000040 SMB_FIND_INFO_STANDARD = 0x0001 SMB_FIND_FILE_DIRECTORY_INFO = 0x0101 SMB_FIND_FILE_FULL_DIRECTORY_INFO= 0x0102 SMB_FIND_FILE_NAMES_INFO = 0x0103 SMB_FIND_FILE_BOTH_DIRECTORY_INFO= 0x0104 SMB_FIND_FILE_ID_FULL_DIRECTORY_INFO = 0x105 SMB_FIND_FILE_ID_BOTH_DIRECTORY_INFO = 0x106 # AccessMask (DesiredAccess) flags # A 32-bit field of flags that indicate standard, specific, and generic access rights. # These rights are used in access-control entries (ACEs) and are the primary means of specifying the requested or granted access to an object. # As Specified in section 2.2.4.64.1 SMB_COM_NT_CREATE_ANDX (0xA2) Request FILE_READ_DATA = 0x00000001 # Indicates the right to read data from the file. FILE_WRITE_DATA = 0x00000002 # Indicates the right to write data into the file beyond the end of the file. FILE_APPEND_DATA = 0x00000004 # Indicates the right to append data to the file beyond the end of the file only. FILE_READ_EA = 0x00000008 # Indicates the right to read the extended attributes (EAs) of the file. FILE_WRITE_EA = 0x00000010 # Indicates the right to write or change the extended attributes (EAs) of the file. FILE_EXECUTE = 0x00000020 # Indicates the right to execute the file. FILE_READ_ATTRIBUTES = 0x00000080 # Indicates the right to read the attributes of the file. FILE_WRITE_ATTRIBUTES = 0x00000100 # Indicates the right to change the attributes of the file. DELETE = 0x00010000 # Indicates the right to delete or to rename the file. READ_CONTROL = 0x00020000 # Indicates the right to read the security descriptor of the file. WRITE_DAC = 0x00040000 # Indicates the right to change the discretionary access control list (DACL) in the security descriptor of the file. WRITE_OWNER = 0x00080000 # Indicates the right to change the owner in the security descriptor of the file. SYNCHRONIZE = 0x00100000 # SHOULD NOT be used by the sender and MUST be ignored by the receiver. ACCESS_SYSTEM_SECURITY = 0x01000000 # Indicates the right to read or change the system access control list (SACL) in the security descriptor for the file. If the SE_SECURITY_NAME privilege is not set in the access token, the server MUST fail the open request and return STATUS_PRIVILEGE_NOT_HELD. MAXIMUM_ALLOWED = 0x02000000 # Indicates that the client requests an open to the file with the highest level of access that the client has on this file. If no access is granted for the client on this file, the server MUST fail the open and return a STATUS_ACCESS_DENIED. GENERIC_ALL = 0x10000000 # Indicates a request for all of the access flags that are previously listed except MAXIMUM_ALLOWED and ACCESS_SYSTEM_SECURITY. GENERIC_EXECUTE = 0x20000000 # Indicates a request for the following combination of access flags listed previously in this table: FILE_READ_ATTRIBUTES, FILE_EXECUTE, SYNCHRONIZE, and READ_CONTROL. GENERIC_WRITE = 0x40000000 # Indicates a request for the following combination of access flags listed previously in this table: FILE_WRITE_DATA, FILE_APPEND_DATA, SYNCHRONIZE, FILE_WRITE_ATTRIBUTES, and FILE_WRITE_EA. GENERIC_READ = 0x80000000 # Indicates a request for the following combination of access flags listed previously in this table: FILE_READ_DATA, FILE_READ_ATTRIBUTES, FILE_READ_EA, and SYNCHRONIZE. # ShareAccess flags # A 32-bit field that specifies how the file SHOULD be shared with other processes. # As Specified in section 2.2.4.64.1 SMB_COM_NT_CREATE_ANDX (0xA2) Request FILE_SHARE_NONE = 0x00000000 # No bits set - Prevents the file from being shared. FILE_SHARE_READ = 0x00000001 # Other open operations can be performed on the file for read access. FILE_SHARE_WRITE = 0x00000002 # Other open operations can be performed on the file for write access. FILE_SHARE_DELETE = 0x00000004 # Other open operations can be performed on the file for delete access. # CreateDisposition flags # A 32-bit value that represents the action to take if the file already exists or if the file is a new file and does not already exist. # As Specified in section 2.2.4.64.1 SMB_COM_NT_CREATE_ANDX (0xA2) Request FILE_SUPERSEDE = 0x00000000 # No bits set - If the file already exists, it SHOULD be superseded (overwritten). If it does not already exist, then it SHOULD be created. FILE_OPEN = 0x00000001 # If the file already exists, it SHOULD be opened rather than created. If the file does not already exist, the operation MUST fail. FILE_CREATE = 0x00000002 # If the file already exists, the operation MUST fail. If the file does not already exist, it SHOULD be created. FILE_OPEN_IF = 0x00000003 # If the file already exists, it SHOULD be opened. If the file does not already exist, then it SHOULD be created. This value is equivalent to (FILE_OPEN | FILE_CREATE). FILE_OVERWRITE = 0x00000004 # If the file already exists, it SHOULD be opened and truncated. If the file does not already exist, the operation MUST fail. FILE_OVERWRITE_IF = 0x00000005 # If the file already exists, it SHOULD be opened and truncated. If the file does not already exist, it SHOULD be created. def strerror(errclass, errcode): 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 class SessionError(Exception): # SMB X/Open error codes for the ERRDOS error class ERRsuccess = 0 ERRbadfunc = 1 ERRbadfile = 2 ERRbadpath = 3 ERRnofids = 4 ERRnoaccess = 5 ERRbadfid = 6 ERRbadmcb = 7 ERRnomem = 8 ERRbadmem = 9 ERRbadenv = 10 ERRbadaccess = 12 ERRbaddata = 13 ERRres = 14 ERRbaddrive = 15 ERRremcd = 16 ERRdiffdevice = 17 ERRnofiles = 18 ERRgeneral = 31 ERRbadshare = 32 ERRlock = 33 ERRunsup = 50 ERRnetnamedel = 64 ERRnosuchshare = 67 ERRfilexists = 80 ERRinvalidparam = 87 ERRcannotopen = 110 ERRinsufficientbuffer = 122 ERRinvalidname = 123 ERRunknownlevel = 124 ERRnotlocked = 158 ERRrename = 183 ERRbadpipe = 230 ERRpipebusy = 231 ERRpipeclosing = 232 ERRnotconnected = 233 ERRmoredata = 234 ERRnomoreitems = 259 ERRbaddirectory = 267 ERReasnotsupported = 282 ERRlogonfailure = 1326 ERRbuftoosmall = 2123 ERRunknownipc = 2142 ERRnosuchprintjob = 2151 ERRinvgroup = 2455 # here's a special one from observing NT ERRnoipc = 66 # These errors seem to be only returned by the NT printer driver system ERRdriveralreadyinstalled = 1795 ERRunknownprinterport = 1796 ERRunknownprinterdriver = 1797 ERRunknownprintprocessor = 1798 ERRinvalidseparatorfile = 1799 ERRinvalidjobpriority = 1800 ERRinvalidprintername = 1801 ERRprinteralreadyexists = 1802 ERRinvalidprintercommand = 1803 ERRinvaliddatatype = 1804 ERRinvalidenvironment = 1805 ERRunknownprintmonitor = 3000 ERRprinterdriverinuse = 3001 ERRspoolfilenotfound = 3002 ERRnostartdoc = 3003 ERRnoaddjob = 3004 ERRprintprocessoralreadyinstalled = 3005 ERRprintmonitoralreadyinstalled = 3006 ERRinvalidprintmonitor = 3007 ERRprintmonitorinuse = 3008 ERRprinterhasjobsqueued = 3009 # Error codes for the ERRSRV class ERRerror = 1 ERRbadpw = 2 ERRbadtype = 3 ERRaccess = 4 ERRinvnid = 5 ERRinvnetname = 6 ERRinvdevice = 7 ERRqfull = 49 ERRqtoobig = 50 ERRinvpfid = 52 ERRsmbcmd = 64 ERRsrverror = 65 ERRfilespecs = 67 ERRbadlink = 68 ERRbadpermits = 69 ERRbadpid = 70 ERRsetattrmode = 71 ERRpaused = 81 ERRmsgoff = 82 ERRnoroom = 83 ERRrmuns = 87 ERRtimeout = 88 ERRnoresource = 89 ERRtoomanyuids = 90 ERRbaduid = 91 ERRuseMPX = 250 ERRuseSTD = 251 ERRcontMPX = 252 ERRbadPW = None ERRnosupport = 0 ERRunknownsmb = 22 # Error codes for the ERRHRD class ERRnowrite = 19 ERRbadunit = 20 ERRnotready = 21 ERRbadcmd = 22 ERRdata = 23 ERRbadreq = 24 ERRseek = 25 ERRbadmedia = 26 ERRbadsector = 27 ERRnopaper = 28 ERRwrite = 29 ERRread = 30 ERRwrongdisk = 34 ERRFCBunavail = 35 ERRsharebufexc = 36 ERRdiskfull = 39 hard_msgs = { 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.") } dos_msgs = { 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") } server_msgs = { 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 = 0x1 error_classes = { 0: ("SUCCESS", {}), ERRDOS: ("ERRDOS", dos_msgs), 0x02: ("ERRSRV",server_msgs), 0x03: ("ERRHRD",hard_msgs), 0x04: ("ERRXOS", {} ), 0xE1: ("ERRRMX1", {} ), 0xE2: ("ERRRMX2", {} ), 0xE3: ("ERRRMX3", {} ), 0xFF: ("ERRCMD", {} ) } def __init__( self, error_string, error_class, error_code, nt_status = 0, packet=0): Exception.__init__(self, error_string) self.nt_status = nt_status self._args = error_string if nt_status: self.error_class = 0 self.error_code = (error_code << 16) + error_class else: self.error_class = error_class self.error_code = error_code self.packet = packet def get_error_class( self ): return self.error_class def get_error_code( self ): return self.error_code def get_error_packet(self): return self.packet def __str__( self ): 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: key = self.error_code if key in nt_errors.ERROR_MESSAGES: error_msg_short = nt_errors.ERROR_MESSAGES[key][0] error_msg_verbose = nt_errors.ERROR_MESSAGES[key][1] return 'SMB SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose) else: return 'SMB SessionError: unknown error code: 0x%x' % 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 class UnsupportedFeature(Exception): pass # Add basic filetime conversion helper methods. def POSIXtoFT(t): """ Helper method that converts POSIX timestamps to FILETIME timestamps. :param int t: POSIX timestamp - can be retrieved from datetime library. :return int: FILETIME timestamp representing the given POSIX timestamp. """ t *= 10000000 t += 116444736000000000 return int(t) def FTtoPOSIX(t): """ Helper method that converts FILETIME timestamps to POSIX timestamps. :param int t: FILETIME timestamp. :return int: POSIX timestamp representing the given FILETIME timestamp. """ t -= 116444736000000000 t //= 10000000 return int(t) # Define SMB Standard DateTime Data according to (2.2.1.4 Time) class SMBDateStruct(BigEndianStructure): _fields_ = [ ("y", c_uint32, 7), ("m", c_uint32, 4), ("d", c_uint32, 5), ] class SMB_DATE: """ 2.2.1.4.1 SMB_DATE Class representing an SMB Date value. https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-cifs/31b65222-4171-49b4-aeed-7d3f38ecf68b """ def __init__(self, year, month, day): """ :param int year: An integer representing the valid year part of the date. :param int month: An integer representing the valid month part of the date. :param int day: An integer representing the valid day part of the date. """ self.year = year self.month = month self.day = day @property def year(self): return self._year + 1980 @year.setter def year(self, value): value = value - 1980 if value < 0 or value > 119: raise ValueError("Invalid year component.") self._year = value @property def month(self): return self._month @month.setter def month(self, value): if value < 0 or value > 12: raise ValueError("Invalid month component.") self._month = value @property def day(self): return self._day @day.setter def day(self, value): if value < 0 or value > 31: raise ValueError("Invalid day component.") self._day = value def pack(self): return ((self._year << 9) & 0xFE00) + ((self._month << 5) & 0x01E0) + (self._day & 0x001F) def pack_into(self): """ Helper method to easily access the data as a struct. :return SMBDateStruct: The structure representation of the object. """ res = SMBDateStruct() pack_into(">H", res, 0, self.pack()) return res @classmethod def from_int(cls, data): """ Helper method to easily convert packed bytes value to class object. :param bytes data: Packed bytes to be converted to a class object. :return SMB_DATE: The class representation of the packed data bytes. """ s = SMBDateStruct() pack_into(">H", s, 0, data) return cls.from_struct(s) @classmethod def from_struct(cls, s): """ Helper method to easily convert struct to class object. :param SMBDateStruct s: The struct object to be converted to a class object. :return SMB_DATE: The class representation of the struct object. """ return cls(s.y + 1980, s.m, s.d) class SMBTimeStruct(BigEndianStructure): _fields_ = [ ("h", c_uint32, 5), ("m", c_uint32, 6), ("s", c_uint32, 5), ] class SMB_TIME: """ 2.2.1.4.2 SMB_TIME Class representing an SMB Time value. https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-cifs/401749d1-ee41-4273-9dcb-698180e68745 """ def __init__(self, hour, minutes, seconds): """ :param int hour: An integer representing the valid hour part of the time. :param int minutes: An integer representing the valid minutes part of the time. :param int seconds: An integer representing the valid seconds part of the time. """ self.hour = hour self.minutes = minutes self.seconds = seconds @property def hour(self): return self._hour @hour.setter def hour(self, value): if value < 0 or value > 23: raise ValueError("Invalid hour component.") self._hour = value @property def minutes(self): return self._minutes @minutes.setter def minutes(self, value): if value < 0 or value > 59: raise ValueError("Invalid minutes component.") self._minutes = value @property def seconds(self): return self._seconds @seconds.setter def seconds(self, value): if value < 0 or value > 59: raise ValueError("Invalid seconds component.") self._seconds = value def pack(self): return ((self._hour << 11) & 0xF800) + ((self._minutes << 5) & 0x07E0) + (self._seconds & 0x001F) def pack_into(self): """ Helper method to easily access the data as a struct. :return SMBTimeStruct: The structure representation of the object. """ res = SMBTimeStruct() pack_into(">H", res, 0, self.pack()) return res @classmethod def from_int(cls, data): """ Helper method to easily convert packed bytes value to class object. :param bytes data: Packed bytes to be converted to a class object. :return SMB_TIME: The class representation of the packed data bytes. """ s = SMBTimeStruct() pack_into(">H", s, 0, data) return cls.from_struct(s) @classmethod def from_struct(cls, s): """ Helper method to easily convert struct to class object. :param SMBTimeStruct s: The struct object to be converted to a class object. :return SMB_TIME: The class representation of the struct object. """ return cls(s.h, s.m, s.s) # Contains information about a SMB shared device/service class SharedDevice: def __init__(self, name, share_type, comment): self.__name = name self.__type = share_type self.__comment = comment def get_name(self): return self.__name def get_type(self): return self.__type def get_comment(self): return self.__comment def __repr__(self): return '' # Contains information about the shared file/directory class SharedFile: def __init__(self, ctime, atime, wtime, mtime, filesize, allocsize, attribs, shortname, longname): self.__ctime = ctime # CreateTime ([MS-CIFS] 2.2.8.1.4 SMB_FIND_FILE_DIRECTORY_INFO) self.__atime = atime # LastAccessTime ([MS-CIFS] 2.2.8.1.4 SMB_FIND_FILE_DIRECTORY_INFO) self.__wtime = wtime # LastWriteTime ([MS-CIFS] 2.2.8.1.4 SMB_FIND_FILE_DIRECTORY_INFO) self.__mtime = mtime # LastAttrChangeTime ([MS-CIFS] 2.2.8.1.4 SMB_FIND_FILE_DIRECTORY_INFO) self.__filesize = filesize self.__allocsize = allocsize self.__attribs = attribs try: if isinstance(shortname,bytes): self.__shortname = shortname[:shortname.index(b'\0')] else: self.__shortname = shortname[:shortname.index('\0')] except (ValueError, TypeError): self.__shortname = shortname try: if isinstance(shortname,bytes): self.__longname = longname[:longname.index(b'\0')] else: self.__longname = longname[:longname.index('\0')] except (ValueError, TypeError): self.__longname = longname def get_ctime(self): return self.__ctime def get_ctime_epoch(self): return self.__convert_smbtime(self.__ctime) def get_wtime(self): return self.__wtime def get_wtime_epoch(self): return self.__convert_smbtime(self.__wtime) def get_mtime(self): return self.__mtime def get_mtime_epoch(self): return self.__convert_smbtime(self.__mtime) def get_atime(self): return self.__atime def get_atime_epoch(self): return self.__convert_smbtime(self.__atime) def get_filesize(self): return self.__filesize def get_allocsize(self): return self.__allocsize def get_attributes(self): return self.__attribs def is_archive(self): return self.__attribs & ATTR_ARCHIVE def is_compressed(self): return self.__attribs & ATTR_COMPRESSED def is_normal(self): return self.__attribs & ATTR_NORMAL def is_hidden(self): return self.__attribs & ATTR_HIDDEN def is_readonly(self): return self.__attribs & ATTR_READONLY def is_temporary(self): return self.__attribs & ATTR_TEMPORARY def is_directory(self): return self.__attribs & ATTR_DIRECTORY def is_system(self): return self.__attribs & ATTR_SYSTEM def get_shortname(self): return self.__shortname def get_longname(self): return self.__longname def __repr__(self): return '' @staticmethod 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 class SMBMachine: def __init__(self, nbname, nbt_type, comment): self.__nbname = nbname self.__type = nbt_type self.__comment = comment def __repr__(self): return '' class SMBDomain: def __init__(self, nbgroup, domain_type, master_browser): self.__nbgroup = nbgroup self.__type = domain_type self.__master_browser = master_browser def __repr__(self): return '' # Represents a SMB Packet class NewSMBPacket(Structure): structure = ( ('Signature', '"\xffSMB'), ('Command','B=0'), ('ErrorClass','B=0'), ('_reserved','B=0'), ('ErrorCode',' 0 else 1'), ('Password',':'), ('Path','u'), ('Service','z'), ) class SMBTreeConnectAndXResponse_Data(AsciiOrUnicodeStructure): AsciiStructure = ( ('Service','z'), ('PadLen','_-Pad','self["PadLen"]'), ('Pad',':=""'), ('NativeFileSystem','z'), ) UnicodeStructure = ( ('Service','z'), ('PadLen','_-Pad','self["PadLen"]'), ('Pad',':=""'), ('NativeFileSystem','u'), ) ############# SMB_COM_NT_CREATE_ANDX (0xA2) class SMBNtCreateAndX_Parameters(SMBAndXCommand_Parameters): structure = ( ('_reserved', 'B=0'), ('FileNameLength',' -1: my_name = my_name[:i] if UDP: self._sess = nmb.NetBIOSUDPSession(my_name, remote_name, remote_host, host_type, sess_port, self.__timeout) else: self._sess = nmb.NetBIOSTCPSession(my_name, remote_name, remote_host, host_type, sess_port, self.__timeout) # Initialize session values (_dialect_data and _dialect_parameters) self.neg_session() # 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('', '') 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('', '') @staticmethod def ntlm_supported(): return False def getKerberos(self): return self._doKerberos def get_remote_name(self): return self.__remote_name def set_remote_name(self, name): self.__remote_name = name return True def set_hostname_validation(self, validate, accept_empty, hostname): self._strict_hostname_validation = validate self._validation_allow_absent = accept_empty self._accepted_hostname = hostname def get_remote_host(self): return self.__remote_host def get_flags(self): return self.__flags1, self.__flags2 def set_flags(self, flags1=None, flags2=None): if flags1 is not None: self.__flags1 = flags1 if flags2 is not None: self.__flags2 = flags2 def set_timeout(self, timeout): prev_timeout = self.__timeout self.__timeout = timeout return prev_timeout def get_timeout(self): return self.__timeout @contextmanager def use_timeout(self, timeout): prev_timeout = self.set_timeout(timeout) try: yield finally: self.set_timeout(prev_timeout) def get_session(self): return self._sess def get_tid(self): return self.tid def get_fid(self): return self.fid def isGuestSession(self): return self._action & SMB_SETUP_GUEST def doesSupportNTLMv2(self): return self.__isNTLMv2 def close_session(self): if self._sess: self._sess.close() self._sess = None def recvSMB(self): r = self._sess.recv_packet(self.__timeout) return NewSMBPacket(data = r.get_trailer()) @staticmethod def __decode_trans(params, data): totparamcnt, totdatacnt, _, paramcnt, paramoffset, paramds, datacnt, dataoffset, datads, setupcnt = unpack(' 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'] def get_uid(self): return self._uid def set_uid(self, uid): self._uid = uid def tree_connect_andx(self, path, password = None, service = SERVICE_ANY, smb_packet=None): 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)) else: password = '\x00' if not unicode_support: if unicode_convert: path = str(path) else: raise Exception('SMB: Can\t convert path from unicode!') if smb_packet is None: smb = NewSMBPacket() 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 share = path.split('\\')[-1] try: _, _, _, _, sockaddr = socket.getaddrinfo(self.get_remote_host(), 80, 0, 0, socket.IPPROTO_TCP)[0] remote_host = sockaddr[0] except Exception: remote_host = self.get_remote_host() path = '\\\\' + remote_host + '\\' +share path = path.upper().encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else path treeConnect = SMBCommand(SMB.SMB_COM_TREE_CONNECT_ANDX) treeConnect['Parameters'] = SMBTreeConnectAndX_Parameters() treeConnect['Data'] = SMBTreeConnectAndX_Data(flags=self.__flags2) treeConnect['Parameters']['PasswordLength'] = len(password) treeConnect['Data']['Password'] = password treeConnect['Data']['Path'] = path treeConnect['Data']['Service'] = service if self.__flags2 & SMB.FLAGS2_UNICODE: treeConnect['Data']['Pad'] = 0x0 smb.addCommand(treeConnect) # 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) self.sendSMB(smb) while 1: smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_TREE_CONNECT_ANDX): # XXX Here we are ignoring the rest of the response self.tid = smb['Tid'] return self.tid self.tid = smb['Tid'] return self.tid # backwars compatibility connect_tree = tree_connect_andx @staticmethod def getDialect(): return SMB_DIALECT def get_server_name(self): #return self._dialects_data['ServerName'] return self.__server_name def get_client_name(self): return self.__client_name def get_session_key(self): return self._SigningSessionKey def set_session_key(self, key): self._SignatureEnabled = True self._SignSequenceNumber = 2 self._SigningSessionKey = key def get_encryption_key(self): if 'Challenge' in self._dialects_data.fields: return self._dialects_data['Challenge'] else: return None def get_server_time(self): timestamp = self._dialects_parameters['HighDateTime'] timestamp <<= 32 timestamp |= self._dialects_parameters['LowDateTime'] timestamp -= 116444736000000000 timestamp //= 10000000 d = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc) return d.strftime("%a, %d %b %Y %H:%M:%S GMT") def disconnect_tree(self, tid): smb = NewSMBPacket() smb['Tid'] = tid smb.addCommand(SMBCommand(SMB.SMB_COM_TREE_DISCONNECT)) self.sendSMB(smb) self.recvSMB() def open(self, tid, filename, open_mode, desired_access): 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'], ) def open_andx(self, tid, filename, open_mode, desired_access): 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'], ) def close(self, tid, fid): smb = NewSMBPacket() smb['Tid'] = tid closeFile = SMBCommand(SMB.SMB_COM_CLOSE) closeFile['Parameters'] = SMBClose_Parameters() closeFile['Parameters']['FID'] = fid smb.addCommand(closeFile) self.sendSMB(smb) smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_CLOSE): return 1 return 0 def send_trans(self, tid, setup, name, param, data, noAnswer = 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) def send_trans2(self, tid, setup, name, param, data): smb = NewSMBPacket() smb['Tid'] = tid command = pack(' 0: padLen = (4 - (32+2+28 + len(command)) % 4 ) % 4 padBytes = '\xFF' * padLen transCommand['Data']['Pad1'] = padBytes else: transCommand['Data']['Pad1'] = '' padLen = 0 transCommand['Parameters']['ParameterCount'] = len(param) transCommand['Parameters']['ParameterOffset'] = 32+2+28+len(command)+len(name) + padLen if len(data) > 0: pad2Len = (4 - (32+2+28 + len(command) + padLen + len(param)) % 4) % 4 transCommand['Data']['Pad2'] = '\xFF' * pad2Len else: transCommand['Data']['Pad2'] = '' pad2Len = 0 transCommand['Parameters']['DataCount'] = len(data) transCommand['Parameters']['DataOffset'] = transCommand['Parameters']['ParameterOffset'] + len(param) + pad2Len transCommand['Data']['Name'] = name transCommand['Data']['Trans_Parameters'] = param transCommand['Data']['Trans_Data'] = data smb.addCommand(transCommand) self.sendSMB(smb) def query_file_info(self, tid, fid, fileInfoClass = SMB_QUERY_FILE_STANDARD_INFO): self.send_trans2(tid, SMB.TRANS2_QUERY_FILE_INFORMATION, '\x00', pack(' 0: av_pairs = ntlm.AV_PAIRS(ntlmChallenge['TargetInfoFields'][:ntlmChallenge['TargetInfoFields_len']]) if av_pairs[ntlm.NTLMSSP_AV_HOSTNAME] is not None: try: self.__server_name = av_pairs[ntlm.NTLMSSP_AV_HOSTNAME][1].decode('utf-16le') except UnicodeDecodeError: # For some reason, we couldn't decode Unicode here.. silently discard the operation pass if av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME] is not None: try: if self.__server_name != av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME][1].decode('utf-16le'): self.__server_domain = av_pairs[ntlm.NTLMSSP_AV_DOMAINNAME][1].decode('utf-16le') except UnicodeDecodeError: # For some reason, we couldn't decode Unicode here.. silently discard the operation pass if av_pairs[ntlm.NTLMSSP_AV_DNS_DOMAINNAME] is not None: try: self.__server_dns_domain_name = av_pairs[ntlm.NTLMSSP_AV_DNS_DOMAINNAME][1].decode('utf-16le') except UnicodeDecodeError: # For some reason, we couldn't decode Unicode here.. silently discard the operation pass if av_pairs[ntlm.NTLMSSP_AV_DNS_HOSTNAME] is not None: try: self.__server_dns_host_name = av_pairs[ntlm.NTLMSSP_AV_DNS_HOSTNAME][1].decode('utf-16le') except UnicodeDecodeError: # For some reason, we couldn't decode Unicode here.. silently discard the operation pass if self._strict_hostname_validation: self.perform_hostname_validation() # Parse Version to know the target Operating system name. Not provided elsewhere anymore if 'Version' in ntlmChallenge.fields: version = ntlmChallenge['Version'] if len(version) >= 4: self.__server_os_major, self.__server_os_minor, self.__server_os_build = unpack(' 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') def waitNamedPipe(self, tid, pipe, timeout = 5, noAnswer = 0): 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 if self.__flags2 & SMB.FLAGS2_UNICODE: start_of_name = 32+3+28+len(setup)#32 is smb_header,28 is parameter,3 is wordcount and bytecount start_pad = 2-(start_of_name%2) name = start_pad*b'\x00' + name.encode('utf-16le') end_of_name = start_of_name+len(name) pad_len = 4-(end_of_name%4) name += pad_len*b'\x00' else: name = name.encode('utf-8') 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 def read(self, tid, fid, offset=0, max_size = None, wait_answer=1): 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 def read_andx(self, tid, fid, offset=0, max_size = None, wait_answer=1, smb_packet=None): if not max_size: 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) if smb_packet is None: smb = NewSMBPacket() smb['Tid'] = tid readAndX = SMBCommand(SMB.SMB_COM_READ_ANDX) readAndX['Parameters'] = SMBReadAndX_Parameters() readAndX['Parameters']['Fid'] = fid readAndX['Parameters']['Offset'] = offset readAndX['Parameters']['MaxCount'] = max_size smb.addCommand(readAndX) else: smb = smb_packet if wait_answer: answer = b'' while 1: self.sendSMB(smb) ans = self.recvSMB() if ans.isValidAnswer(SMB.SMB_COM_READ_ANDX): # XXX Here we are only using a few fields from the response readAndXResponse = SMBCommand(ans['Data'][0]) readAndXParameters = SMBReadAndXResponse_Parameters(readAndXResponse['Parameters']) offset = readAndXParameters['DataOffset'] count = readAndXParameters['DataCount']+0x10000*readAndXParameters['DataCount_Hi'] answer += ans.getData()[offset:offset+count] if not ans.isMoreData(): return answer 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 def read_raw(self, tid, fid, offset=0, max_size = None, wait_answer=1): 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 def write(self,tid,fid,data, offset = 0, wait_answer=1): 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 def write_andx(self,tid,fid,data, offset = 0, wait_answer=1, write_pipe_mode = False, smb_packet=None): if smb_packet is None: smb = NewSMBPacket() smb['Tid'] = tid writeAndX = SMBCommand(SMB.SMB_COM_WRITE_ANDX) smb.addCommand(writeAndX) writeAndX['Parameters'] = SMBWriteAndX_Parameters() writeAndX['Parameters']['Fid'] = fid writeAndX['Parameters']['Offset'] = offset writeAndX['Parameters']['WriteMode'] = 8 writeAndX['Parameters']['Remaining'] = len(data) writeAndX['Parameters']['DataLength'] = len(data) writeAndX['Parameters']['DataOffset'] = len(smb) # this length already includes the parameter writeAndX['Data'] = data if write_pipe_mode is True: # 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 self.sendSMB(smb) if wait_answer: smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_WRITE_ANDX): return smb return None def write_raw(self,tid,fid,data, offset = 0, wait_answer=1): 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 def TransactNamedPipe(self, tid, fid, data = '', noAnswer = 0, waitAnswer = 1, offset = 0): self.send_trans(tid,pack(' 0: record = SMBFindFileBothDirectoryInfo(data = findData) shortname = record['ShortName'].decode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else \ record['ShortName'].decode('cp437') filename = record['FileName'].decode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else \ record['FileName'].decode('cp437') fileRecord = SharedFile(record['CreationTime'], record['LastAccessTime'], record['LastWriteTime'], record['LastChangeTime'], record['EndOfFile'], record['AllocationSize'], record['ExtFileAttributes'], shortname, filename) files.append(fileRecord) if record['NextEntryOffset'] > 0 and len(findData[record['NextEntryOffset']:]) > 0: findData = findData[record['NextEntryOffset']:] else: # More data to search? if findParameterBlock['EndOfSearch'] == 0: resume_filename = record['FileName'] findNextParameter = SMBFindNext2_Parameters() findNextParameter['SID'] = sid findNextParameter['SearchCount'] = 1024 findNextParameter['InformationLevel'] = SMB_FIND_FILE_BOTH_DIRECTORY_INFO findNextParameter['ResumeKey'] = record["FileIndex"] 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 + b'\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: break finally: self.disconnect_tree(tid) return files def retr_file(self, service, filename, callback, mode = FILE_OPEN, offset = 0, password = None, shareAccessMode = FILE_SHARE_READ): 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, accessMask = READ_CONTROL | FILE_READ_ATTRIBUTES | FILE_READ_EA | FILE_READ_DATA) res = self.query_file_info(tid, fid) datasize = SMBQueryFileStandardInfo(res)['EndOfFile'] self.__nonraw_retr_file(tid, fid, offset, datasize, callback) finally: if fid >= 0: self.close(tid, fid) self.disconnect_tree(tid) def stor_file(self, service, filename, callback, mode = FILE_OVERWRITE_IF, offset = 0, password = None, shareAccessMode = FILE_SHARE_READ): 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) def stor_file_nonraw(self, service, filename, callback, mode = FILE_OVERWRITE_IF, offset = 0, password = None, shareAccessMode = FILE_SHARE_READ): 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) def check_dir(self, service, path, password = None): path = path.replace('/', '\\') tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password) try: smb = NewSMBPacket() smb['Tid'] = tid smb['Mid'] = 0 cmd = SMBCommand(SMB.SMB_COM_CHECK_DIRECTORY) cmd['Parameters'] = '' cmd['Data'] = SMBCheckDirectory_Data(flags = self.__flags2) cmd['Data']['DirectoryName'] = path.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else path smb.addCommand(cmd) self.sendSMB(smb) while 1: s = self.recvSMB() if s.isValidAnswer(SMB.SMB_COM_CHECK_DIRECTORY): return finally: self.disconnect_tree(tid) def remove(self, service, path, password = None): path = path.replace('/', '\\') # Perform a list to ensure the path exists self.list_path(service, path, password) tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password) try: smb = NewSMBPacket() smb['Tid'] = tid smb['Mid'] = 0 cmd = SMBCommand(SMB.SMB_COM_DELETE) cmd['Parameters'] = SMBDelete_Parameters() cmd['Parameters']['SearchAttributes'] = ATTR_HIDDEN | ATTR_SYSTEM | ATTR_ARCHIVE cmd['Data'] = SMBDelete_Data(flags = self.__flags2) cmd['Data']['FileName'] = (path + '\x00').encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else (path + '\x00') smb.addCommand(cmd) self.sendSMB(smb) while 1: s = self.recvSMB() if s.isValidAnswer(SMB.SMB_COM_DELETE): return finally: self.disconnect_tree(tid) def rmdir(self, service, path, password = None): path = path.replace('/', '\\') # Check that the directory exists self.check_dir(service, path, password) tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password) try: path = path.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else path smb = NewSMBPacket() smb['Tid'] = tid createDir = SMBCommand(SMB.SMB_COM_DELETE_DIRECTORY) createDir['Data'] = SMBDeleteDirectory_Data(flags=self.__flags2) createDir['Data']['DirectoryName'] = path smb.addCommand(createDir) self.sendSMB(smb) while 1: s = self.recvSMB() if s.isValidAnswer(SMB.SMB_COM_DELETE_DIRECTORY): return finally: self.disconnect_tree(tid) def mkdir(self, service, path, password = None): path = path.replace('/', '\\') tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password) try: path = path.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else path smb = NewSMBPacket() smb['Tid'] = tid smb['Mid'] = 0 createDir = SMBCommand(SMB.SMB_COM_CREATE_DIRECTORY) createDir['Data'] = SMBCreateDirectory_Data(flags=self.__flags2) createDir['Data']['DirectoryName'] = path smb.addCommand(createDir) self.sendSMB(smb) smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_CREATE_DIRECTORY): return 1 return 0 finally: self.disconnect_tree(tid) def rename(self, service, old_path, new_path, password = None): old_path = old_path.replace('/', '\\') new_path = new_path.replace('/', '\\') tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password) try: smb = NewSMBPacket() smb['Tid'] = tid smb['Mid'] = 0 renameCmd = SMBCommand(SMB.SMB_COM_RENAME) renameCmd['Parameters'] = SMBRename_Parameters() renameCmd['Parameters']['SearchAttributes'] = ATTR_SYSTEM | ATTR_HIDDEN | ATTR_DIRECTORY renameCmd['Data'] = SMBRename_Data(flags = self.__flags2) renameCmd['Data']['OldFileName'] = old_path.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else old_path renameCmd['Data']['NewFileName'] = new_path.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else new_path smb.addCommand(renameCmd) self.sendSMB(smb) smb = self.recvSMB() if smb.isValidAnswer(SMB.SMB_COM_RENAME): return 1 return 0 finally: self.disconnect_tree(tid) def writeFile(self, treeId, fileId, data, offset = 0): if (self._dialects_parameters['Capabilities'] & SMB.CAP_LARGE_WRITEX) and self._SignatureEnabled is False: max_buf_size = 65000 else: max_buf_size = self._dialects_parameters['MaxBufferSize'] & ~0x3ff # Write in multiple KB blocks write_offset = offset while 1: if len(data) == 0: break writeData = data[:max_buf_size] data = data[max_buf_size:] smb = self.write_andx(treeId,fileId,writeData, write_offset) writeResponse = SMBCommand(smb['Data'][0]) writeResponseParameters = SMBWriteAndXResponse_Parameters(writeResponse['Parameters']) write_offset += writeResponseParameters['Count'] return write_offset def get_socket(self): return self._sess.get_socket() def send_nt_trans(self, tid, subcommand, max_param_count, setup='', param='', data=''): """ [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(' 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) def query_sec_info(self, tid, fid, additional_information=7): """ [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('