Ejemplo n.º 1
0
def helpModule(module):
    """
    Print the first text chunk for each established method in a module.

    module: module to write output from, format "folder.folder.module"
    """

    # split module.x.y into "from module.x import y" 
    t = module.split(".")
    importName = "from " + ".".join(t[:-1]) + " import " + t[-1]

    # dynamically do the import
    exec(importName)
    moduleName = t[-1]

    # extract all local functions from the imported module, 
    # referenced here by locals()[moduleName]
    functions = [locals()[moduleName].__dict__.get(a) for a in dir(locals()[moduleName]) if isinstance(locals()[moduleName].__dict__.get(a), types.FunctionType)]

    # pull all the doc strings out from said functions and print the top chunk
    for function in functions:
        base = function.func_doc
        base = base.replace("\t", " ")
        doc = "".join(base.split("\n\n")[0].strip().split("\n"))
        # print function.func_name + " : " + doc
        print helpers.formatLong(function.func_name, doc)
Ejemplo n.º 2
0
    def PayloadInfo(self, payload, showTitle=True, showInfo=True):
        """
        Print out information about a specified payload.

        payload = the payload object to print information on
        showTitle = whether to show the Veil title
        showInfo = whether to show the payload information bit

        """
        if showTitle:
            if settings.TERMINAL_CLEAR != "false":
                messages.title()

        if showInfo:
            # extract the payload class name from the instantiated object, then chop off the load folder prefix
            payloadname = "/".join(
                str(str(payload.__class__)[str(payload.__class__).find("payloads") :]).split(".")[0].split("/")[1:]
            )

            print helpers.color(" Payload information:\n")
            print "\tName:\t\t" + payloadname
            print "\tLanguage:\t" + payload.language
            print "\tRating:\t\t" + payload.rating

            if hasattr(payload, "shellcode"):
                if self.payload.shellcode.customshellcode:
                    print "\tShellcode:\t\tused"

            # format this all nice-like
            print helpers.formatLong("Description:", payload.description)

        # if required options were specified, output them
        if hasattr(self.payload, "required_options"):
            self.PayloadOptions(self.payload)
Ejemplo n.º 3
0
    def PayloadInfo(self, payload, showTitle=True, showInfo=True):
        """
        Print out information about a specified payload.

        payload = the payload object to print information on
        showTitle = whether to show the Veil title
        showInfo = whether to show the payload information bit

        """
        if showTitle:
            if settings.TERMINAL_CLEAR != "false": messages.title()

        if showInfo:
            # extract the payload class name from the instantiated object, then chop off the load folder prefix
            payloadname = "/".join(
                str(
                    str(payload.__class__)
                    [str(payload.__class__).find("payloads"):]).split(".")
                [0].split("/")[1:])

            print helpers.color(" Payload information:\n")
            print "\tName:\t\t" + payloadname
            print "\tLanguage:\t" + payload.language
            print "\tRating:\t\t" + payload.rating

            if hasattr(payload, 'shellcode'):
                if self.payload.shellcode.customshellcode:
                    print "\tShellcode:\t\tused"

            # format this all nice-like
            print helpers.formatLong("Description:", payload.description)

        # if required options were specified, output them
        if hasattr(self.payload, 'required_options'):
            self.PayloadOptions(self.payload)
Ejemplo n.º 4
0
def helpModule(module):
    """
    Print the first text chunk for each established method in a module.

    module: module to write output from, format "folder.folder.module"
    """

    # split module.x.y into "from module.x import y"
    t = module.split(".")
    importName = "from " + ".".join(t[:-1]) + " import " + t[-1]

    # dynamically do the import
    exec(importName)
    moduleName = t[-1]

    # extract all local functions from the imported module,
    # referenced here by locals()[moduleName]
    functions = [
        locals()[moduleName].__dict__.get(a) for a in dir(locals()[moduleName])
        if isinstance(locals()[moduleName].__dict__.get(a), types.FunctionType)
    ]

    # pull all the doc strings out from said functions and print the top chunk
    for function in functions:
        base = function.func_doc
        base = base.replace("\t", " ")
        doc = "".join(base.split("\n\n")[0].strip().split("\n"))
        # print function.func_name + " : " + doc
        print helpers.formatLong(function.func_name, doc)
Ejemplo n.º 5
0
    def PayloadInfo(self, payload, showTitle=True, showInfo=True):
        """
        Print out information about a specified payload.

        payload = the payload object to print information on
        showTitle = whether to show the Veil title
        showInfo = whether to show the payload information bit

        """
        if showTitle:
            messages.title()

        if showInfo:
            # extract the payload class name from the instantiated object, then chop off the load folder prefix
            payloadname = "/".join(
                str(
                    str(payload.__class__)
                    [str(payload.__class__).find("payloads"):]).split(".")
                [0].split("/")[1:])

            print helpers.color(" Payload information:\n")
            print "\tName:\t\t" + payloadname
            print "\tLanguage:\t" + payload.language
            print "\tRating:\t\t" + payload.rating

            if hasattr(payload, 'shellcode'):
                if self.payload.shellcode.customshellcode:
                    print "\tShellcode:\t\tused"

            # format this all nice-like
            print helpers.formatLong("Description:", payload.description)

        # if required options were specified, output them
        if hasattr(self.payload, 'required_options'):
            print helpers.color("\n Required Options:\n")

            print " Name\t\t\tCurrent Value\tDescription"
            print " ----\t\t\t-------------\t-----------"

            # sort the dictionary by key before we output, so it looks nice
            for key in sorted(self.payload.required_options.iterkeys()):
                print " %s\t%s\t%s" % ('{0: <16}'.format(key),
                                       '{0: <8}'.format(
                                           payload.required_options[key][0]),
                                       payload.required_options[key][1])

            print ""
Ejemplo n.º 6
0
    def PayloadInfo(self, payload, showTitle=True, showInfo=True):
        """
        Print out information about a specified payload.

        payload = the payload object to print information on
        showTitle = whether to show the Veil title
        showInfo = whether to show the payload information bit

        """
        if showTitle:
            messages.title()

        if showInfo:
            # extract the payload class name from the instantiated object, then chop off the load folder prefix
            payloadname = "/".join(str(str(payload.__class__)[str(payload.__class__).find("payloads"):]).split(".")[0].split("/")[1:])

            print helpers.color(" Payload information:\n")
            print "\tName:\t\t" + payloadname
            print "\tLanguage:\t" + payload.language
            print "\tRating:\t\t" + payload.rating

            if hasattr(payload, 'shellcode'):
                if self.payload.shellcode.customshellcode:
                    print "\tShellcode:\t\tused"

            # format this all nice-like
            print helpers.formatLong("Description:", payload.description)

        # if required options were specified, output them
        if hasattr(self.payload, 'required_options'):
            print helpers.color("\n Required Options:\n")

            print " Name\t\t\tCurrent Value\tDescription"
            print " ----\t\t\t-------------\t-----------"

            # sort the dictionary by key before we output, so it looks nice
            for key in sorted(self.payload.required_options.iterkeys()):
                print " %s\t%s\t%s" % ('{0: <16}'.format(key), '{0: <8}'.format(payload.required_options[key][0]), payload.required_options[key][1])

            print ""
Ejemplo n.º 7
0
    def PayloadInfo(self, payload, showTitle=True, showInfo=True):
        """
        Print out information about a specified payload.

        payload = the payload object to print information on

        """
        if showTitle:
            messages.title()

        if showInfo:
            print " Payload information:\n"

            print "\tName:\t\t" + payload.shortname
            print "\tLanguage:\t" + payload.language
            print "\tRating:\t\t" + payload.rating

            if hasattr(payload, 'shellcode'):
                if self.payload.shellcode.customshellcode:
                    print "\tShellcode:\t\tused"

            # format this all nice-like
            print helpers.formatLong("Description:", payload.description)

        # if required options were specified, output them
        if hasattr(self.payload, 'required_options'):
            print "\n Required Options:\n"

            print " Name\t\t\tCurrent Value\tDescription"
            print " ----\t\t\t-------------\t-----------"

            # sort the dictionary by key before we output, so it looks nice
            for key in sorted(self.payload.required_options.iterkeys()):
                print " %s\t%s\t%s" % ('{0: <16}'.format(key),
                                       '{0: <8}'.format(
                                           payload.required_options[key][0]),
                                       payload.required_options[key][1])

            print ""
Ejemplo n.º 8
0
    def PayloadInfo(self, payload, showTitle=True, showInfo=True):
        """
        Print out information about a specified payload.

        payload = the payload object to print information on

        """
        if showTitle:
            messages.title()

        if showInfo:
            print " Payload information:\n"

            print "\tName:\t\t" + payload.shortname
            print "\tLanguage:\t" + payload.language
            print "\tRating:\t\t" + payload.rating

            if hasattr(payload, 'shellcode'):
                if self.payload.shellcode.customshellcode:
                    print "\tShellcode:\t\tused"

            # format this all nice-like
            print helpers.formatLong("Description:", payload.description)

        # if required options were specified, output them
        if hasattr(self.payload, 'required_options'):
            print "\n Required Options:\n"

            print " Name\t\t\tCurrent Value\tDescription"
            print " ----\t\t\t-------------\t-----------"

            # sort the dictionary by key before we output, so it looks nice
            for key in sorted(self.payload.required_options.iterkeys()):
                print " %s\t%s\t%s" % ('{0: <16}'.format(key), '{0: <8}'.format(payload.required_options[key][0]), payload.required_options[key][1])

            print ""
Ejemplo n.º 9
0
    def OutputMenu(self, payload, code, showTitle=True, interactive=True, args=None):
        """
        Write a chunk of payload code to a specified ouput file base.
        Also outputs a handler script if required from the options.

        code = the source code to write
        OutputBaseChoice = "payload" or user specified string

        Returns the full name the source was written to.
        """

        OutputBaseChoice = ""
        overwrite = False

        # if we have arguments passed, extract out the values we want
        if args:
            OutputBaseChoice = args.o
            overwrite = args.overwrite

        # if we get .exe or ELF (with no base) code back, output to the compiled folder, otherwise write to the source folder
        if payload.extension == "exe" or payload.extension == "war":
            outputFolder = settings.PAYLOAD_COMPILED_PATH
        # Check for ELF binary
        elif hasattr(payload, "type") and payload.type == "ELF":
            outputFolder = settings.PAYLOAD_COMPILED_PATH
        else:
            outputFolder = settings.PAYLOAD_SOURCE_PATH

        # only show get input if we're doing the interactive menu
        if interactive:
            if showTitle:
                if settings.TERMINAL_CLEAR != "false":
                    messages.title()

            # Get the base install name for the payloads (i.e. OutputBaseChoice.py/OutputBaseChoice.exe)
            OutputBaseChoice = raw_input("\n [>] Please enter the base name for output files (default is 'payload'): ")

            # ensure we get a base name and not a full path
            while OutputBaseChoice != "" and "/" in OutputBaseChoice:
                print helpers.color(" [!] Please provide a base name, not a path, for the output base", warning=True)
                OutputBaseChoice = raw_input(
                    "\n [>] Please enter the base name for output files (default is 'payload'): "
                )

        # for invalid output base choices that are passed by arguments
        else:
            if "/" in OutputBaseChoice:
                print helpers.color(" [!] Please provide a base name, not a path, for the output base", warning=True)
                print helpers.color(" [!] Defaulting to 'payload' for output base...", warning=True)
                OutputBaseChoice = "payload"

        if OutputBaseChoice == "":
            OutputBaseChoice = "payload"

        # if we are overwriting, this is the base choice used
        FinalBaseChoice = OutputBaseChoice

        # if we're not overwriting output files, walk the existing and increment
        if not overwrite:
            # walk the output path and grab all the file bases, disregarding extensions
            fileBases = []
            for (dirpath, dirnames, filenames) in os.walk(outputFolder):
                fileBases.extend(list(set([x.split(".")[0] for x in filenames if x.split(".")[0] != ""])))
                break

            # as long as the file exists, increment a counter to add to the filename
            # i.e. "payload3.py", to make sure we don't overwrite anything
            FinalBaseChoice = OutputBaseChoice
            x = 1
            while FinalBaseChoice in fileBases:
                FinalBaseChoice = OutputBaseChoice + str(x)
                x += 1

        # set the output name to /outout/source/BASENAME.EXT unless it is an ELF then no extension
        if hasattr(payload, "type") and payload.type == "ELF":
            OutputFileName = outputFolder + FinalBaseChoice + payload.extension
        else:
            OutputFileName = outputFolder + FinalBaseChoice + "." + payload.extension

        OutputFile = open(OutputFileName, "w")
        OutputFile.write(code)
        OutputFile.close()

        # start building the information string for the generated payload
        # extract the payload class name from the instantiated object, then chop off the load folder prefix
        payloadname = "/".join(
            str(str(payload.__class__)[str(payload.__class__).find("payloads") :]).split(".")[0].split("/")[1:]
        )
        message = "\n Language:\t\t" + helpers.color(payload.language) + "\n Payload:\t\t" + payloadname
        handler = ""

        if hasattr(payload, "shellcode"):
            # check if msfvenom was used or something custom, print appropriately
            if payload.shellcode.customshellcode != "":
                message += "\n Shellcode:\t\tcustom"
            else:
                message += "\n Shellcode:\t\t" + payload.shellcode.msfvenompayload

                # if the shellcode wasn't custom, build out a handler script
                handler = "use exploit/multi/handler\n"
                handler += "set PAYLOAD " + payload.shellcode.msfvenompayload + "\n"

                # extract LHOST if it's there
                p = re.compile("LHOST=(.*?) ")
                parts = p.findall(payload.shellcode.msfvenomCommand)
                if len(parts) > 0:
                    handler += "set LHOST " + parts[0] + "\n"
                else:
                    # try to extract this local IP
                    handler += "set LHOST " + helpers.LHOST() + "\n"

                # extract LPORT if it's there
                p = re.compile("LPORT=(.*?) ")
                parts = p.findall(payload.shellcode.msfvenomCommand)
                if len(parts) > 0:
                    handler += "set LPORT " + parts[0] + "\n"

                # Removed autoscript smart migrate due to users on forum saying that migrate itself caused detection
                # in an otherwise undetectable (at the time) payload
                handler += "set ExitOnSession false\n"
                handler += "exploit -j\n"

            # print out any msfvenom options we used in shellcode generation if specified
            if len(payload.shellcode.options) > 0:
                message += "\n Options:\t\t"
                parts = ""
                for option in payload.shellcode.options:
                    parts += " " + option + " "
                message += parts.strip()

            # reset the internal shellcode state the options don't persist
            payload.shellcode.Reset()

        # if required options were specified, output them
        if hasattr(payload, "required_options"):
            t = ""
            # sort the dictionary by key before we output, so it looks nice
            for key in sorted(payload.required_options.iterkeys()):
                t += " " + key + "=" + payload.required_options[key][0] + " "
            message += "\n" + helpers.formatLong("Required Options:", t.strip(), frontTab=False, spacing=24)

            # check if any options specify that we should build a handler out
            keys = payload.required_options.keys()

            # assuming if LHOST is set, we need a handler script
            if "LHOST" in keys or "RHOST" in keys:

                handler = "use exploit/multi/handler\n"
                # do our best to determine the payload type

                architecture = ""
                if hasattr(payload, "architecture") and payload.architecture == "64":
                    architecture = "x64/"

                # handle options from the backdoor factory
                if "payload" in keys:
                    p = payload.required_options["payload"][0]

                    if "rev_tcp" in p:
                        handler += "set PAYLOAD windows/%smeterpreter/reverse_tcp\n" % architecture
                    elif "bind_tcp" in p:
                        handler += "set PAYLOAD windows/%smeterpreter/bind_tcp\n" % architecture
                    elif "https" in p:
                        handler += "set PAYLOAD windows/%smeterpreter/reverse_https\n" % architecture
                    elif "shell" in p:
                        handler += "set PAYLOAD windows/%sshell_reverse_tcp\n" % architecture
                    else:
                        pass

                # if not BDF, try to extract the handler type from the payload name
                else:
                    # extract the payload class name from the instantiated object, then chop off the load folder prefix
                    payloadname = "/".join(
                        str(str(payload.__class__)[str(payload.__class__).find("payloads") :])
                        .split(".")[0]
                        .split("/")[1:]
                    )

                    # pure rev_tcp stager
                    if "rev_tcp" in payloadname.lower():
                        handler += "set PAYLOAD windows/%smeterpreter/reverse_tcp\n" % architecture
                    # pure bind_tcp stager
                    elif "bind_tcp" in payloadname.lower():
                        handler += "set PAYLOAD windows/%smeterpreter/bind_tcp\n" % architecture
                    # pure rev_https stager
                    elif "https" in payloadname.lower():
                        handler += "set PAYLOAD windows/%smeterpreter/reverse_https\n" % architecture
                    # pure rev_http stager
                    elif "http" in payloadname.lower():
                        handler += "set PAYLOAD windows/%smeterpreter/reverse_http\n" % architecture
                    else:
                        pass

                # grab the LHOST value
                if "LHOST" in keys:
                    handler += "set LHOST " + payload.required_options["LHOST"][0] + "\n"
                if "RHOST" in keys:
                    handler += "set RHOST " + payload.required_options["RHOST"][0] + "\n"

                # grab the LPORT value if it was set
                if "LPORT" in keys:
                    handler += "set LPORT " + payload.required_options["LPORT"][0] + "\n"

                # grab the LURI value if it was set. ignore the / as that is the default
                if "LURI" in keys and payload.required_options["LURI"][0] != "/":
                    handler += "set LURI " + payload.required_options["LURI"][0] + "\n"

                handler += "set ExitOnSession false\n"
                handler += "exploit -j\n"

        message += "\n Payload File:\t\t" + OutputFileName + "\n"

        # if we're generating the handler script, write it out
        try:
            if settings.GENERATE_HANDLER_SCRIPT.lower() == "true":
                if handler != "":
                    handlerFileName = settings.HANDLER_PATH + FinalBaseChoice + "_handler.rc"
                    handlerFile = open(handlerFileName, "w")
                    handlerFile.write(handler)
                    handlerFile.close()
                    message += " Handler File:\t\t" + handlerFileName + "\n"
        except:
            # is that option fails, it probably means that the /etc/veil/settings.py file hasn't been updated
            print helpers.color(
                "\n [!] Internal error #1. Please run %s manually\n" % (os.path.abspath("./config/update.py")),
                warning=True,
            )

        # print out notes if set
        if hasattr(payload, "notes"):
            # message += " Notes:\t\t\t" + payload.notes
            message += helpers.formatLong("Notes:", payload.notes, frontTab=False, spacing=24)

        # check if compile_to_exe is in the required options, if so,
        # call supportfiles.supportingFiles() to compile appropriately
        if hasattr(self.payload, "required_options") and self.payload.language.lower() != "powershell":
            if "COMPILE_TO_EXE" in self.payload.required_options:
                value = self.payload.required_options["COMPILE_TO_EXE"][0].lower()[0]

                if value == "y" or value == True:

                    # check if the --pwnstaller flag was passed
                    if args and args.pwnstaller:
                        supportfiles.supportingFiles(self.payload, OutputFileName, {"method": "pwnstaller"})
                    else:
                        # if interactive, allow the user to choose the method
                        if interactive:
                            supportfiles.supportingFiles(self.payload, OutputFileName, {})
                        # otherwise specify the default, pyinstaller
                        else:
                            supportfiles.supportingFiles(self.payload, OutputFileName, {"method": "pyinstaller"})

                    # if we're compiling, set the returned file name to the output .exe
                    # so we can return this for external calls to the framework
                    OutputFileName = settings.PAYLOAD_COMPILED_PATH + FinalBaseChoice + ".exe"

        # This block of code is going to be used to SHA1 hash our compiled payloads to potentially submit the
        # hash with VTNotify to detect if it's been flagged
        try:
            CompiledHashFile = settings.HASH_LIST
            HashFile = open(CompiledHashFile, "a")
            OutputFile = open(OutputFileName, "rb")
            Sha1Hasher = hashlib.sha1()
            Sha1Hasher.update(OutputFile.read())
            SHA1Hash = Sha1Hasher.hexdigest()
            OutputFile.close()
            HashFile.write(SHA1Hash + ":" + FinalBaseChoice + "\n")
            HashFile.close()

            # print the full message containing generation notes
            print message

            # print the end message
            messages.endmsg()
        except:
            # if that option fails, it probably means that the /etc/veil/settings.py file hasn't been updated
            print helpers.color(
                "\n [!] Internal error #2. Unable to generate output. Please run %s manually\n"
                % (os.path.abspath("./config/update.py")),
                warning=True,
            )

        if interactive:
            raw_input(" [>] Press any key to return to the main menu.")
            print ""
            self.MainMenu(showMessage=True)

        return OutputFileName
Ejemplo n.º 10
0
    def OutputMenu(self, payload, code, showTitle=True, interactive=True, OutputBaseChoice=""):
        """
        Write a chunk of payload code to a specified ouput file base.
        Also outputs a handler script if required from the options.

        code = the source code to write
        OutputBaseChoice = "payload" or user specified string

        Returns the full name the source was written to.
        """

        # if we get .exe code back, output to the compiled folder, otherwise write to the source folder
        if payload.extension == "exe":
            outputFolder = settings.PAYLOAD_COMPILED_PATH
        else:
            outputFolder = settings.PAYLOAD_SOURCE_PATH

        # only show get input if we're doing the interactive menu
        if interactive:
            if showTitle:
                messages.title()

            # Get the base install name for the payloads (i.e. OutputBaseChoice.py/OutputBaseChoice.exe)
            print " [*] Press [enter] for 'payload'"
            OutputBaseChoice = raw_input(" [>] Please enter the base name for output files: ")

        if OutputBaseChoice == "": OutputBaseChoice = "payload"

        # walk the output path and grab all the file bases, disregarding extensions
        fileBases = []
        for (dirpath, dirnames, filenames) in os.walk(outputFolder):
            fileBases.extend(list(set([x.split(".")[0] for x in filenames if x.split(".")[0] != ''])))
            break

        # as long as the file exists, increment a counter to add to the filename
        # i.e. "payload3.py", to make sure we don't overwrite anything
        FinalBaseChoice = OutputBaseChoice
        x = 1
        while FinalBaseChoice in fileBases:
            FinalBaseChoice = OutputBaseChoice + str(x)
            x += 1

        # set the output name to /outout/source/BASENAME.EXT
        OutputFileName = outputFolder + FinalBaseChoice + "." + payload.extension

        OutputFile = open(OutputFileName, 'w')
        OutputFile.write(code)
        OutputFile.close()

        # start building the information string for the generated payload
        message = "\n Language:\t\t"+helpers.color(payload.language)+"\n Payload:\t\t"+payload.shortname

        if hasattr(payload, 'shellcode'):
            # check if msfvenom was used or something custom, print appropriately
            if payload.shellcode.customshellcode != "":
                message += "\n Shellcode:\t\tcustom"
            else:
                message += "\n Shellcode:\t\t" + payload.shellcode.msfvenompayload

                # if the shellcode wasn't custom, build out a handler script
                handler = "use exploit/multi/handler\n"
                handler += "set PAYLOAD " + payload.shellcode.msfvenompayload + "\n"
                handler += "set LHOST 0.0.0.0\n"
                
                # extract LPORT if it's there
                p = re.compile('LPORT=(.*?) ')
                parts = p.findall(payload.shellcode.msfvenomCommand)
                if len(parts) > 0:
                    handler += "set LPORT " + parts[0] + "\n"

                handler += "set ExitOnSession false\n"
                handler += "set AutoRunScript post/windows/manage/migrate\n"
                handler += "exploit -j\n"

            # print out any msfvenom options we used in shellcode generation if specified
            if len(payload.shellcode.options) > 0:
                message += "\n Options:\t\t"
                parts = ""
                for option in payload.shellcode.options:
                    parts += ' ' + option + ' '
                message += parts.strip()

            # reset the internal shellcode state the options don't persist
            payload.shellcode.Reset()

        # if required options were specified, output them
        if hasattr(payload, 'required_options'):
            message += "\n Required Options:\t"
            t = ""
            # sort the dictionary by key before we output, so it looks nice
            for key in sorted(payload.required_options.iterkeys()):
                t += " " + key + "=" + payload.required_options[key][0] + " "
            message += t.strip()

            # check if any options specify that we should build a handler out
            keys = payload.required_options.keys()

            if "LHOST" in keys:

                handler = "use exploit/multi/handler\n"
                # do our best to determine the payload type

                # handle options from the backdoor factory
                if "payload" in keys:
                    p = payload.required_options["payload"][0]
                    if "tcp" in p:
                        handler += "set PAYLOAD windows/meterpreter/reverse_tcp\n"
                    elif "https" in p:
                        handler += "set PAYLOAD windows/meterpreter/reverse_https\n"
                    elif "shell" in  p:
                        handler += "set PAYLOAD windows/shell_reverse_tcp\n"
                    else: pass

                # if not BDF, try to extract the handler type from the payload name
                else:
                    if "tcp" in payload.shortname.lower():
                        handler += "set PAYLOAD windows/meterpreter/reverse_tcp\n"
                    elif "https" in payload.shortname.lower():
                        handler += "set PAYLOAD windows/meterpreter/reverse_https\n"
                    elif "http" in payload.shortname.lower():
                        handler += "set PAYLOAD windows/meterpreter/reverse_https\n"
                    else: pass

                handler += "set LHOST 0.0.0.0\n"

                if "LPORT" in keys:
                    handler += "set LPORT " + payload.required_options["LPORT"][0] + "\n"

                handler += "set ExitOnSession false\n"
                handler += "set AutoRunScript post/windows/manage/migrate\n"
                handler += "exploit -j\n"


        message += "\n Payload File:\t\t"+OutputFileName + "\n"

        # if we're generating the handler script, write it out
        try:
            if settings.GENERATE_HANDLER_SCRIPT.lower() == "true":
                handlerFileName = settings.HANDLER_PATH + FinalBaseChoice + "_handler.rc"
                handlerFile = open(handlerFileName, 'w')
                handlerFile.write(handler)
                handlerFile.close()
                message += " Handler File:\t\t"+handlerFileName + "\n"
        except:
            # is that option fails, it probably means that the /etc/veil/settings.py file hasn't been updated
            print helpers.color("\n [!] Please run ./config/update.py !", warning=True)

        # print out notes if set
        if hasattr(payload, 'notes'):
            #message += " Notes:\t\t\t" + payload.notes
            message += helpers.formatLong("Notes:", payload.notes, frontTab=False, spacing=24)

        message += "\n"

        # check if compile_to_exe is in the required options, if so,
        # call supportfiles.supportingFiles() to compile appropriately
        if hasattr(self.payload, 'required_options'):
            if "compile_to_exe" in self.payload.required_options:
                value = self.payload.required_options['compile_to_exe'][0].lower()[0]
                if value == "y" or value==True:
                    if interactive:
                        supportfiles.supportingFiles(self.payload.language, OutputFileName, {})
                    else:
                        supportfiles.supportingFiles(self.payload.language, OutputFileName, {'method':'pyinstaller'})

                    # if we're compiling, set the returned file name to the output .exe
                    # so we can return this for external calls to the framework
                    OutputFileName = settings.PAYLOAD_COMPILED_PATH + FinalBaseChoice + ".exe"

        # print the full message containing generation notes
        print message

        # print the end message
        messages.endmsg()

        if interactive:
            raw_input(" [>] press any key to return to the main menu: ")
            #self.MainMenu(showMessage=True)

        return OutputFileName
Ejemplo n.º 11
0
    def OutputMenu(self,
                   payload,
                   code,
                   showTitle=True,
                   interactive=True,
                   OutputBaseChoice=""):
        """
        Write a chunk of payload code to a specified ouput file base.
        Also outputs a handler script if required from the options.

        code = the source code to write
        OutputBaseChoice = "payload" or user specified string

        Returns the full name the source was written to.
        """

        # if we get .exe code back, output to the compiled folder, otherwise write to the source folder
        if payload.extension == "exe":
            outputFolder = settings.PAYLOAD_COMPILED_PATH
        else:
            outputFolder = settings.PAYLOAD_SOURCE_PATH

        # only show get input if we're doing the interactive menu
        if interactive:
            if showTitle:
                messages.title()

            # Get the base install name for the payloads (i.e. OutputBaseChoice.py/OutputBaseChoice.exe)
            print " [*] Press [enter] for 'payload'"
            OutputBaseChoice = raw_input(
                " [>] Please enter the base name for output files: ")

        if OutputBaseChoice == "": OutputBaseChoice = "payload"

        # walk the output path and grab all the file bases, disregarding extensions
        fileBases = []
        for (dirpath, dirnames, filenames) in os.walk(outputFolder):
            fileBases.extend(
                list(
                    set([
                        x.split(".")[0] for x in filenames
                        if x.split(".")[0] != ''
                    ])))
            break

        # as long as the file exists, increment a counter to add to the filename
        # i.e. "payload3.py", to make sure we don't overwrite anything
        FinalBaseChoice = OutputBaseChoice
        x = 1
        while FinalBaseChoice in fileBases:
            FinalBaseChoice = OutputBaseChoice + str(x)
            x += 1

        # set the output name to /outout/source/BASENAME.EXT
        OutputFileName = outputFolder + FinalBaseChoice + "." + payload.extension

        OutputFile = open(OutputFileName, 'w')
        OutputFile.write(code)
        OutputFile.close()

        # start building the information string for the generated payload
        message = "\n Language:\t\t" + helpers.color(
            payload.language) + "\n Payload:\t\t" + payload.shortname

        if hasattr(payload, 'shellcode'):
            # check if msfvenom was used or something custom, print appropriately
            if payload.shellcode.customshellcode != "":
                message += "\n Shellcode:\t\tcustom"
            else:
                message += "\n Shellcode:\t\t" + payload.shellcode.msfvenompayload

                # if the shellcode wasn't custom, build out a handler script
                handler = "use exploit/multi/handler\n"
                handler += "set PAYLOAD " + payload.shellcode.msfvenompayload + "\n"
                handler += "set LHOST 0.0.0.0\n"

                # extract LPORT if it's there
                p = re.compile('LPORT=(.*?) ')
                parts = p.findall(payload.shellcode.msfvenomCommand)
                if len(parts) > 0:
                    handler += "set LPORT " + parts[0] + "\n"

                handler += "set ExitOnSession false\n"
                handler += "set AutoRunScript post/windows/manage/migrate\n"
                handler += "exploit -j\n"

            # print out any msfvenom options we used in shellcode generation if specified
            if len(payload.shellcode.options) > 0:
                message += "\n Options:\t\t"
                parts = ""
                for option in payload.shellcode.options:
                    parts += ' ' + option + ' '
                message += parts.strip()

            # reset the internal shellcode state the options don't persist
            payload.shellcode.Reset()

        # if required options were specified, output them
        if hasattr(payload, 'required_options'):
            message += "\n Required Options:\t"
            t = ""
            # sort the dictionary by key before we output, so it looks nice
            for key in sorted(payload.required_options.iterkeys()):
                t += " " + key + "=" + payload.required_options[key][0] + " "
            message += t.strip()

            # check if any options specify that we should build a handler out
            keys = payload.required_options.keys()

            if "LHOST" in keys:

                handler = "use exploit/multi/handler\n"
                # do our best to determine the payload type

                # handle options from the backdoor factory
                if "payload" in keys:
                    p = payload.required_options["payload"][0]
                    if "tcp" in p:
                        handler += "set PAYLOAD windows/meterpreter/reverse_tcp\n"
                    elif "https" in p:
                        handler += "set PAYLOAD windows/meterpreter/reverse_https\n"
                    elif "shell" in p:
                        handler += "set PAYLOAD windows/shell_reverse_tcp\n"
                    else:
                        pass

                # if not BDF, try to extract the handler type from the payload name
                else:
                    if "tcp" in payload.shortname.lower():
                        handler += "set PAYLOAD windows/meterpreter/reverse_tcp\n"
                    elif "https" in payload.shortname.lower():
                        handler += "set PAYLOAD windows/meterpreter/reverse_https\n"
                    elif "http" in payload.shortname.lower():
                        handler += "set PAYLOAD windows/meterpreter/reverse_https\n"
                    else:
                        pass

                handler += "set LHOST 0.0.0.0\n"

                if "LPORT" in keys:
                    handler += "set LPORT " + payload.required_options[
                        "LPORT"][0] + "\n"

                handler += "set ExitOnSession false\n"
                handler += "set AutoRunScript post/windows/manage/migrate\n"
                handler += "exploit -j\n"

        message += "\n Payload File:\t\t" + OutputFileName + "\n"

        # if we're generating the handler script, write it out
        try:
            if settings.GENERATE_HANDLER_SCRIPT.lower() == "true":
                handlerFileName = settings.HANDLER_PATH + FinalBaseChoice + "_handler.rc"
                handlerFile = open(handlerFileName, 'w')
                handlerFile.write(handler)
                handlerFile.close()
                message += " Handler File:\t\t" + handlerFileName + "\n"
        except:
            # is that option fails, it probably means that the /etc/veil/settings.py file hasn't been updated
            print helpers.color("\n [!] Please run ./config/update.py !",
                                warning=True)

        # print out notes if set
        if hasattr(payload, 'notes'):
            #message += " Notes:\t\t\t" + payload.notes
            message += helpers.formatLong("Notes:",
                                          payload.notes,
                                          frontTab=False,
                                          spacing=24)

        message += "\n"

        # check if compile_to_exe is in the required options, if so,
        # call supportfiles.supportingFiles() to compile appropriately
        if hasattr(self.payload, 'required_options'):
            if "compile_to_exe" in self.payload.required_options:
                value = self.payload.required_options['compile_to_exe'][
                    0].lower()[0]
                if value == "y" or value == True:
                    if interactive:
                        supportfiles.supportingFiles(self.payload.language,
                                                     OutputFileName, {})
                    else:
                        supportfiles.supportingFiles(self.payload.language,
                                                     OutputFileName,
                                                     {'method': 'pyinstaller'})

                    # if we're compiling, set the returned file name to the output .exe
                    # so we can return this for external calls to the framework
                    OutputFileName = settings.PAYLOAD_COMPILED_PATH + FinalBaseChoice + ".exe"

        # print the full message containing generation notes
        print message

        # print the end message
        messages.endmsg()

        if interactive:
            raw_input(" [>] press any key to return to the main menu: ")
            #self.MainMenu(showMessage=True)

        return OutputFileName
Ejemplo n.º 12
0
    def OutputMenu(self,
                   payload,
                   code,
                   showTitle=True,
                   interactive=True,
                   args=None):
        """
        Write a chunk of payload code to a specified ouput file base.
        Also outputs a handler script if required from the options.

        code = the source code to write
        OutputBaseChoice = "payload" or user specified string

        Returns the full name the source was written to.
        """

        OutputBaseChoice = ""
        overwrite = False

        # if we have arguments passed, extract out the values we want
        if args:
            OutputBaseChoice = args.o
            overwrite = args.overwrite

        # if we get .exe or ELF (with no base) code back, output to the compiled folder, otherwise write to the source folder
        if payload.extension == "exe" or payload.extension == "war":
            outputFolder = settings.PAYLOAD_COMPILED_PATH
        # Check for ELF binary
        elif hasattr(payload, 'type') and payload.type == "ELF":
            outputFolder = settings.PAYLOAD_COMPILED_PATH
        else:
            outputFolder = settings.PAYLOAD_SOURCE_PATH

        # only show get input if we're doing the interactive menu
        if interactive:
            if showTitle:
                if settings.TERMINAL_CLEAR != "false": messages.title()

            # Get the base install name for the payloads (i.e. OutputBaseChoice.py/OutputBaseChoice.exe)
            OutputBaseChoice = raw_input(
                "\n [>] Please enter the base name for output files (default is 'payload'): "
            )

            # ensure we get a base name and not a full path
            while OutputBaseChoice != "" and "/" in OutputBaseChoice:
                print helpers.color(
                    " [!] Please provide a base name, not a path, for the output base",
                    warning=True)
                OutputBaseChoice = raw_input(
                    "\n [>] Please enter the base name for output files (default is 'payload'): "
                )

        # for invalid output base choices that are passed by arguments
        else:
            if "/" in OutputBaseChoice:
                print helpers.color(
                    " [!] Please provide a base name, not a path, for the output base",
                    warning=True)
                print helpers.color(
                    " [!] Defaulting to 'payload' for output base...",
                    warning=True)
                OutputBaseChoice = "payload"

        if OutputBaseChoice == "": OutputBaseChoice = "payload"

        # if we are overwriting, this is the base choice used
        FinalBaseChoice = OutputBaseChoice

        # if we're not overwriting output files, walk the existing and increment
        if not overwrite:
            # walk the output path and grab all the file bases, disregarding extensions
            fileBases = []
            for (dirpath, dirnames, filenames) in os.walk(outputFolder):
                fileBases.extend(
                    list(
                        set([
                            x.split(".")[0] for x in filenames
                            if x.split(".")[0] != ''
                        ])))
                break

            # as long as the file exists, increment a counter to add to the filename
            # i.e. "payload3.py", to make sure we don't overwrite anything
            FinalBaseChoice = OutputBaseChoice
            x = 1
            while FinalBaseChoice in fileBases:
                FinalBaseChoice = OutputBaseChoice + str(x)
                x += 1

        # set the output name to /outout/source/BASENAME.EXT unless it is an ELF then no extension
        if hasattr(payload, 'type') and payload.type == "ELF":
            OutputFileName = outputFolder + FinalBaseChoice + payload.extension
        else:
            OutputFileName = outputFolder + FinalBaseChoice + "." + payload.extension

        OutputFile = open(OutputFileName, 'w')
        OutputFile.write(code)
        OutputFile.close()

        # start building the information string for the generated payload
        # extract the payload class name from the instantiated object, then chop off the load folder prefix
        payloadname = "/".join(
            str(
                str(payload.__class__)
                [str(payload.__class__).find("payloads"):]).split(".")
            [0].split("/")[1:])
        message = "\n Language:\t\t" + helpers.color(
            payload.language) + "\n Payload:\t\t" + payloadname
        handler = ""

        if hasattr(payload, 'shellcode'):
            # check if msfvenom was used or something custom, print appropriately
            if payload.shellcode.customshellcode != "":
                message += "\n Shellcode:\t\tcustom"
            else:
                message += "\n Shellcode:\t\t" + payload.shellcode.msfvenompayload

                # if the shellcode wasn't custom, build out a handler script
                handler = "use exploit/multi/handler\n"
                handler += "set PAYLOAD " + payload.shellcode.msfvenompayload + "\n"

                # extract LHOST if it's there
                p = re.compile('LHOST=(.*?) ')
                parts = p.findall(payload.shellcode.msfvenomCommand)
                if len(parts) > 0:
                    handler += "set LHOST " + parts[0] + "\n"
                else:
                    # try to extract this local IP
                    handler += "set LHOST " + helpers.LHOST() + "\n"

                # extract LPORT if it's there
                p = re.compile('LPORT=(.*?) ')
                parts = p.findall(payload.shellcode.msfvenomCommand)
                if len(parts) > 0:
                    handler += "set LPORT " + parts[0] + "\n"

                # Removed autoscript smart migrate due to users on forum saying that migrate itself caused detection
                # in an otherwise undetectable (at the time) payload
                handler += "set ExitOnSession false\n"
                handler += "exploit -j\n"

            # print out any msfvenom options we used in shellcode generation if specified
            if len(payload.shellcode.options) > 0:
                message += "\n Options:\t\t"
                parts = ""
                for option in payload.shellcode.options:
                    parts += ' ' + option + ' '
                message += parts.strip()

            # reset the internal shellcode state the options don't persist
            payload.shellcode.Reset()

        # if required options were specified, output them
        if hasattr(payload, 'required_options'):
            t = ""
            # sort the dictionary by key before we output, so it looks nice
            for key in sorted(payload.required_options.iterkeys()):
                t += " " + key + "=" + payload.required_options[key][0] + " "
            message += "\n" + helpers.formatLong(
                "Required Options:", t.strip(), frontTab=False, spacing=24)

            # check if any options specify that we should build a handler out
            keys = payload.required_options.keys()

            # assuming if LHOST is set, we need a handler script
            if "LHOST" in keys or "RHOST" in keys:

                handler = "use exploit/multi/handler\n"
                # do our best to determine the payload type

                architecture = ""
                if hasattr(payload,
                           "architecture") and payload.architecture == "64":
                    architecture = "x64/"

                # handle options from the backdoor factory
                if "payload" in keys:
                    p = payload.required_options["payload"][0]

                    if "rev_tcp" in p:
                        handler += "set PAYLOAD windows/%smeterpreter/reverse_tcp\n" % architecture
                    elif "bind_tcp" in p:
                        handler += "set PAYLOAD windows/%smeterpreter/bind_tcp\n" % architecture
                    elif "https" in p:
                        handler += "set PAYLOAD windows/%smeterpreter/reverse_https\n" % architecture
                    elif "shell" in p:
                        handler += "set PAYLOAD windows/%sshell_reverse_tcp\n" % architecture
                    else:
                        pass

                # if not BDF, try to extract the handler type from the payload name
                else:
                    # extract the payload class name from the instantiated object, then chop off the load folder prefix
                    payloadname = "/".join(
                        str(
                            str(payload.__class__)
                            [str(payload.__class__).find("payloads"):]).split(
                                ".")[0].split("/")[1:])

                    # pure rev_tcp stager
                    if "rev_tcp" in payloadname.lower():
                        handler += "set PAYLOAD windows/%smeterpreter/reverse_tcp\n" % architecture
                    # pure bind_tcp stager
                    elif "bind_tcp" in payloadname.lower():
                        handler += "set PAYLOAD windows/%smeterpreter/bind_tcp\n" % architecture
                    # pure rev_https stager
                    elif "https" in payloadname.lower():
                        handler += "set PAYLOAD windows/%smeterpreter/reverse_https\n" % architecture
                    # pure rev_http stager
                    elif "http" in payloadname.lower():
                        handler += "set PAYLOAD windows/%smeterpreter/reverse_http\n" % architecture
                    else:
                        pass

                # grab the LHOST value
                if "LHOST" in keys:
                    handler += "set LHOST " + payload.required_options[
                        "LHOST"][0] + "\n"
                if "RHOST" in keys:
                    handler += "set RHOST " + payload.required_options[
                        "RHOST"][0] + "\n"

                # grab the LPORT value if it was set
                if "LPORT" in keys:
                    handler += "set LPORT " + payload.required_options[
                        "LPORT"][0] + "\n"

                handler += "set ExitOnSession false\n"
                handler += "exploit -j\n"

        message += "\n Payload File:\t\t" + OutputFileName + "\n"

        # if we're generating the handler script, write it out
        try:
            if settings.GENERATE_HANDLER_SCRIPT.lower() == "true":
                if handler != "":
                    handlerFileName = settings.HANDLER_PATH + FinalBaseChoice + "_handler.rc"
                    handlerFile = open(handlerFileName, 'w')
                    handlerFile.write(handler)
                    handlerFile.close()
                    message += " Handler File:\t\t" + handlerFileName + "\n"
        except:
            # is that option fails, it probably means that the /etc/veil/settings.py file hasn't been updated
            print helpers.color(
                "\n [!] Internal error #1. Please run %s manually\n" %
                (os.path.abspath("./config/update.py")),
                warning=True)

        # print out notes if set
        if hasattr(payload, 'notes'):
            #message += " Notes:\t\t\t" + payload.notes
            message += helpers.formatLong("Notes:",
                                          payload.notes,
                                          frontTab=False,
                                          spacing=24)

        # check if compile_to_exe is in the required options, if so,
        # call supportfiles.supportingFiles() to compile appropriately
        if hasattr(self.payload, 'required_options'
                   ) and self.payload.language.lower() != "powershell":
            if "COMPILE_TO_EXE" in self.payload.required_options:
                value = self.payload.required_options['COMPILE_TO_EXE'][
                    0].lower()[0]

                if value == "y" or value == True:

                    # check if the --pwnstaller flag was passed
                    if args and args.pwnstaller:
                        supportfiles.supportingFiles(self.payload,
                                                     OutputFileName,
                                                     {'method': 'pwnstaller'})
                    else:
                        # if interactive, allow the user to choose the method
                        if interactive:
                            supportfiles.supportingFiles(
                                self.payload, OutputFileName, {})
                        # otherwise specify the default, pyinstaller
                        else:
                            supportfiles.supportingFiles(
                                self.payload, OutputFileName,
                                {'method': 'pyinstaller'})

                    # if we're compiling, set the returned file name to the output .exe
                    # so we can return this for external calls to the framework
                    OutputFileName = settings.PAYLOAD_COMPILED_PATH + FinalBaseChoice + ".exe"

        # This block of code is going to be used to SHA1 hash our compiled payloads to potentially submit the
        # hash with VTNotify to detect if it's been flagged
        try:
            CompiledHashFile = settings.HASH_LIST
            HashFile = open(CompiledHashFile, 'a')
            OutputFile = open(OutputFileName, 'rb')
            Sha1Hasher = hashlib.sha1()
            Sha1Hasher.update(OutputFile.read())
            SHA1Hash = Sha1Hasher.hexdigest()
            OutputFile.close()
            HashFile.write(SHA1Hash + ":" + FinalBaseChoice + "\n")
            HashFile.close()

            # print the full message containing generation notes
            print message

            # print the end message
            messages.endmsg()
        except:
            # if that option fails, it probably means that the /etc/veil/settings.py file hasn't been updated
            print helpers.color(
                "\n [!] Internal error #2. Unable to generate output. Please run %s manually\n"
                % (os.path.abspath("./config/update.py")),
                warning=True)

        if interactive:
            raw_input(" [>] Press any key to return to the main menu.")
            print ""
            self.MainMenu(showMessage=True)

        return OutputFileName
Ejemplo n.º 13
0
    def OutputMenu(self, payload, code, showTitle=True, interactive=True, OutputBaseChoice=""):
        """
        Write a chunk of payload code to a specified ouput file base.

        code = the source code to write
        OutputBaseChoice = "payload" or user specified string

        Returns the full name the source was written to.
        """

        # if we get .exe code back, output to the compiled folder, otherwise write to the source folder
        if payload.extension == "exe":
            outputFolder = settings.PAYLOAD_COMPILED_PATH
        else:
            outputFolder = settings.PAYLOAD_SOURCE_PATH

        # only show get input if we're doing the interactive menu
        if interactive:
            if showTitle:
                messages.title()

            # Get the base install name for the payloads (i.e. OutputBaseChoice.py/OutputBaseChoice.exe)
            print " [*] Press [enter] for 'payload'"
            OutputBaseChoice = raw_input(" [>] Please enter the base name for output files: ")

        if OutputBaseChoice == "": OutputBaseChoice = "payload"

        # walk the output path and grab all the file bases, disregarding extensions
        fileBases = []
        for (dirpath, dirnames, filenames) in os.walk(outputFolder):
            fileBases.extend(list(set([x.split(".")[0] for x in filenames if x.split(".")[0] != ''])))
            break

        # as long as the file exists, increment a counter to add to the filename
        # i.e. "payload3.py", to make sure we don't overwrite anything
        FinalBaseChoice = OutputBaseChoice
        x = 1
        while FinalBaseChoice in fileBases:
            FinalBaseChoice = OutputBaseChoice + str(x)
            x += 1

        # set the output name to /outout/source/BASENAME.EXT
        OutputFileName = outputFolder + FinalBaseChoice + "." + payload.extension

        OutputFile = open(OutputFileName, 'w')
        OutputFile.write(code)
        OutputFile.close()

        # start building the information string for the generated payload
        message = "\n Language:\t\t"+helpers.color(payload.language)+"\n Payload:\t\t"+payload.shortname

        if hasattr(payload, 'shellcode'):
            # check if msfvenom was used or something custom, print appropriately
            if payload.shellcode.customshellcode != "":
                message += "\n Shellcode:\t\tcustom"
            else:
                message += "\n Shellcode:\t\t" + payload.shellcode.msfvenompayload

            # print out any msfvenom options we used in shellcode generation if specified
            if len(payload.shellcode.options) > 0:
                message += "\n Options:\t\t"
                parts = ""
                for option in payload.shellcode.options:
                    parts += ' ' + option + ' '
                message += parts.strip()

            # reset the internal shellcode state the options don't persist
            payload.shellcode.Reset()

        # if required options were specified, output them
        if hasattr(payload, 'required_options'):
            message += "\n Required Options:\t"
            t = ""
            # sort the dictionary by key before we output, so it looks nice
            for key in sorted(payload.required_options.iterkeys()):
                t += " " + key + "=" + payload.required_options[key][0] + " "
            message += t.strip()

        message += "\n Source File:\t\t"+OutputFileName + "\n"

        # print out notes if set
        if hasattr(payload, 'notes'):
            #message += " Notes:\t\t\t" + payload.notes
            message += helpers.formatLong("Notes:", payload.notes, frontTab=False, spacing=24)

        message += "\n"

        # check if compile_to_exe is in the required options, if so,
        # call supportfiles.supportingFiles() to compile appropriately
        if hasattr(self.payload, 'required_options'):
            if "compile_to_exe" in self.payload.required_options:
                value = self.payload.required_options['compile_to_exe'][0].lower()[0]
                if value == "y" or value==True:
                    if interactive:
                        supportfiles.supportingFiles(self.payload.language, OutputFileName, {})
                    else:
                        supportfiles.supportingFiles(self.payload.language, OutputFileName, {'method':'pyinstaller'})

                    # if we're compiling, set the returned file name to the output .exe
                    # so we can return this for external calls to the framework
                    OutputFileName = settings.PAYLOAD_COMPILED_PATH + FinalBaseChoice + ".exe"

        # print the full message containing generation notes
        print message

        # print the end message
        messages.endmsg()

        if interactive:
            raw_input(" [>] press any key to return to the main menu: ")
            #self.MainMenu(showMessage=True)

        return OutputFileName
Ejemplo n.º 14
0
	def OutputMenu(self, payload, code, showTitle=True, interactive=True, OutputBaseChoice=""):
		"""
		Write a chunk of payload code to a specified ouput file base.
		
		code = the source code to write
		OutputBaseChoice = "payload" or user specified string
		
		Returns the full name the source was written to.
		"""
		
		# if we get .exe code back, output to the compiled folder, otherwise write to the source folder
		if payload.extension == "exe":
			outputFolder = veil.PAYLOAD_COMPILED_PATH
		else:
			outputFolder = veil.PAYLOAD_SOURCE_PATH
		
		# only show get input if we're doing the interactive menu
		if interactive:
			if showTitle:
				messages.title()
			
			# Get the base install name for the payloads (i.e. OutputBaseChoice.py/OutputBaseChoice.exe)
			print " [*] Press [enter] for 'payload'"
			OutputBaseChoice = raw_input(" [>] Please enter the base name for output files: ")
		
		if OutputBaseChoice == "": OutputBaseChoice = "payload"
		
		# walk the output path and grab all the file bases, disregarding extensions
		fileBases = []
		for (dirpath, dirnames, filenames) in os.walk(outputFolder):
			fileBases.extend(list(set([x.split(".")[0] for x in filenames if x.split(".")[0] != ''])))
			break 

		# as long as the file exists, increment a counter to add to the filename
		# i.e. "payload3.py", to make sure we don't overwrite anything
		FinalBaseChoice = OutputBaseChoice
		x = 1
		while FinalBaseChoice in fileBases:
			FinalBaseChoice = OutputBaseChoice + str(x) 
			x += 1

		# set the output name to /outout/source/BASENAME.EXT
		OutputFileName = outputFolder + FinalBaseChoice + "." + payload.extension
		
		OutputFile = open(OutputFileName, 'w')
		OutputFile.write(code)
		OutputFile.close()
				
		# start building the information string for the generated payload
		message = "\n Language:\t\t"+helpers.color(payload.language)+"\n Payload:\t\t"+payload.shortname
		
		if hasattr(payload, 'shellcode'):
			# check if msfvenom was used or something custom, print appropriately
			if payload.shellcode.customshellcode != "":
				message += "\n Shellcode:\t\tcustom"
			else:
				message += "\n Shellcode:\t\t" + payload.shellcode.msfvenompayload
			
			# print out any msfvenom options we used in shellcode generation if specified
			if len(payload.shellcode.options) > 0:
				message += "\n Options:\t\t"
				parts = ""
				for option in payload.shellcode.options:
					parts += ' ' + option + ' '
				message += parts.strip()

			# reset the internal shellcode state the options don't persist
			payload.shellcode.Reset()

		# if required options were specified, output them
		if hasattr(payload, 'required_options'):
			message += "\n Required Options:\t"
			t = ""
			# sort the dictionary by key before we output, so it looks nice
			for key in sorted(payload.required_options.iterkeys()):
				t += " " + key + "=" + payload.required_options[key][0] + " "
			message += t.strip()

		message += "\n Source File:\t\t"+OutputFileName + "\n"
		
		# print out notes if set
		if hasattr(payload, 'notes'):
			#message += " Notes:\t\t\t" + payload.notes
			message += helpers.formatLong("Notes:", payload.notes, frontTab=False, spacing=24)

		message += "\n"

		# check if compile_to_exe is in the required options, if so,
		# call supportfiles.supportingFiles() to compile appropriately
		if hasattr(self.payload, 'required_options'):
			if "compile_to_exe" in self.payload.required_options:
				value = self.payload.required_options['compile_to_exe'][0].lower()[0]
				if value == "y" or value==True:
					if interactive:
						supportfiles.supportingFiles(self.payload.language, OutputFileName, {})
					else:
						supportfiles.supportingFiles(self.payload.language, OutputFileName, {'method':'pyinstaller'})

					# if we're compiling, set the returned file name to the output .exe
					# so we can return this for external calls to the framework
					OutputFileName = veil.PAYLOAD_COMPILED_PATH + FinalBaseChoice + ".exe"

		# print the full message containing generation notes
		print message
				
		# print the end message
		messages.endmsg()

		if interactive:
			raw_input(" [>] press any key to return to the main menu: ")
			#self.MainMenu(showMessage=True)

		return OutputFileName