コード例 #1
0
ファイル: ImplantHandler.py プロジェクト: Flangvik/PoshC2
def do_quit(user, command):
    ri = input("Are you sure you want to quit? (Y/n) ")
    if ri.lower() == "n":
        return
    if ri == "" or ri.lower() == "y":
        new_c2_message("%s logged off." % user)
        sys.exit(0)
コード例 #2
0
ファイル: ImplantHandler.py プロジェクト: Flangvik/PoshC2
def main(args):
    signal.signal(signal.SIGINT, catch_exit)
    user = None
    autohide = None
    if len(args) > 0:
        parser = argparse.ArgumentParser(
            description='The command line for handling implants in PoshC2')
        parser.add_argument('-u', '--user', help='the user for this session')
        parser.add_argument(
            '-a',
            '--autohide',
            help='to autohide implants after 30 inactive beacons',
            action='store_true')
        args = parser.parse_args(args)
        user = args.user
        autohide = args.autohide
    while not user:
        print(Colours.GREEN + "A username is required for logging")
        user = input("Enter your username: "******"The project database has not been created yet")
        sys.exit()
    database_connect()
    new_c2_message("%s logged on." % user)
    clear()
    implant_handler_command_loop(user, "", autohide)
コード例 #3
0
ファイル: ImplantHandler.py プロジェクト: Flangvik/PoshC2
def do_message(user, command):
    message = command[len("message "):]
    new_c2_message("Message from %s - %s" % (user, message))
    clear()
コード例 #4
0
ファイル: ImplantHandler.py プロジェクト: Flangvik/PoshC2
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()
コード例 #5
0
ファイル: ImplantHandler.py プロジェクト: Flangvik/PoshC2
def implant_command_loop(implant_id, user):
    while (True):
        try:
            style = Style.from_dict({
                '': '#80d130',
            })
            session = PromptSession(history=FileHistory('%s/.implant-history' %
                                                        PoshProjectDirectory),
                                    auto_suggest=AutoSuggestFromHistory(),
                                    style=style)
            implant_id_orig = implant_id
            if ("-" in implant_id) or ("all" in implant_id) or (","
                                                                in implant_id):
                print(Colours.GREEN)
                prompt_commands = POSH_COMMANDS
                command = session.prompt("%s> " % implant_id,
                                         completer=FirstWordFuzzyWordCompleter(
                                             prompt_commands, WORD=True))
                if command == "back" or command == 'clear':
                    do_back(user, command)
                    return
            else:
                implant = get_implantbyid(implant_id)
                if not implant:
                    print_bad("Unrecognised implant id or command: %s" %
                              implant_id)
                    input("Press Enter to continue...")
                    clear()
                    return
                prompt_commands = POSH_COMMANDS
                if implant.Pivot.startswith('Python'):
                    prompt_commands = PY_COMMANDS
                if implant.Pivot.startswith('C#'):
                    prompt_commands = SHARP_COMMANDS
                if 'PB' in implant.Pivot:
                    style = Style.from_dict({
                        '': '#008ECC',
                    })
                    session = PromptSession(
                        history=FileHistory('%s/.implant-history' %
                                            PoshProjectDirectory),
                        auto_suggest=AutoSuggestFromHistory(),
                        style=style)
                    prompt_commands = SHARP_COMMANDS
                    print(Colours.BLUE)
                else:
                    print(Colours.GREEN)
                print("%s\\%s @ %s (PID:%s)" % (implant.Domain, implant.User,
                                                implant.Hostname, implant.PID))
                command = session.prompt(
                    "%s %s> " %
                    (get_implant_type_prompt_prefix(implant_id), implant_id),
                    completer=FirstWordFuzzyWordCompleter(prompt_commands,
                                                          WORD=True))
                if command == "back" or command == 'clear':
                    do_back(user, command)
                    return

            # if "all" run through all implants get_implants()
            if implant_id == "all":
                if command == "back" or command == 'clear':
                    do_back(user, command)
                    return
                allcommands = command
                if "\n" in command:
                    ri = input(
                        "Do you want to run commands separately? (Y/n) ")
                implants_split = get_implants()
                if implants_split:
                    for implant_details in implants_split:
                        # if "\n" in command run each command individually or ask the question if that's what they want to do
                        if "\n" in allcommands:
                            if ri.lower() == "y" or ri == "":
                                commands = allcommands.split('\n')
                                for command in commands:
                                    run_implant_command(
                                        command, implant_details.RandomURI,
                                        implant_id_orig, user)
                            else:
                                run_implant_command(command,
                                                    implant_details.RandomURI,
                                                    implant_id_orig, user)
                        else:
                            run_implant_command(command,
                                                implant_details.RandomURI,
                                                implant_id_orig, user)

            # if "separated list" against single uri
            elif "," in implant_id:
                allcommands = command
                if "\n" in command:
                    ri = input(
                        "Do you want to run commands separately? (Y/n) ")
                implant_split = implant_id.split(",")
                for split_implant_id in implant_split:
                    implant_randomuri = get_randomuri(split_implant_id)
                    # if "\n" in command run each command individually or ask the question if that's what they want to do
                    if "\n" in allcommands:
                        if ri.lower() == "y" or ri == "":
                            commands = allcommands.split('\n')
                            for command in commands:
                                run_implant_command(command, implant_randomuri,
                                                    implant_id_orig, user)
                        else:
                            run_implant_command(command, implant_randomuri,
                                                implant_id_orig, user)
                    else:
                        run_implant_command(command, implant_randomuri,
                                            implant_id_orig, user)

            # if "range" against single uri
            elif "-" in implant_id:
                allcommands = command
                if "\n" in command:
                    ri = input(
                        "Do you want to run commands separately? (Y/n) ")
                implant_split = implant_id.split("-")
                for range_implant_id in range(int(implant_split[0]),
                                              int(implant_split[1]) + 1):
                    try:
                        implant_randomuri = get_randomuri(range_implant_id)
                        # if "\n" in command run each command individually or ask the question if that's what they want to do
                        if "\n" in allcommands:
                            if ri.lower() == "y" or ri == "":
                                commands = allcommands.split('\n')
                                for command in commands:
                                    run_implant_command(
                                        command, implant_randomuri,
                                        implant_id_orig, user)
                            else:
                                run_implant_command(command, implant_randomuri,
                                                    implant_id_orig, user)
                        else:
                            run_implant_command(command, implant_randomuri,
                                                implant_id_orig, user)
                    except Exception:
                        print_bad("Unknown ImplantID")

            # else run against single uri
            else:
                allcommands = command
                if "\n" in command:
                    ri = input(
                        "Do you want to run commands separately? (Y/n) ")
                implant_randomuri = get_randomuri(implant_id)
                # if "\n" in command run each command individually or ask the question if that's what they want to do
                if "\n" in allcommands:
                    if ri.lower() == "y" or ri == "":
                        commands = allcommands.split('\n')
                        for command in commands:
                            run_implant_command(command, implant_randomuri,
                                                implant_id_orig, user)
                    else:
                        run_implant_command(command, implant_randomuri,
                                            implant_id_orig, user)
                else:
                    run_implant_command(command, implant_randomuri,
                                        implant_id_orig, user)

        except KeyboardInterrupt:
            continue
        except EOFError:
            new_c2_message("%s logged off." % user)
            sys.exit(0)
        except Exception as e:
            traceback.print_exc()
            print_bad(
                f"Error running against the selected implant ID, ensure you have typed the correct information: {e}"
            )
            return