Example #1
0
    def inject_dll(self, dll_path):
        result = True
        if self.pid != None:
            # Getting process handler
            try:
                arch = self.get_arch()
                self.process_handle = WindowsProcess(pid=self.pid, arch=arch)
            except Exception as error:
                self.print_error("{0}".format(error.msg))
                return False

            self.print_info("Opened a handle to pid: {0}".format(self.pid))

            # Finding and injecting dll
            self.dll = ctypes.util.find_library(dll_path)
            if self.dll:
                self.print_info("Found DLL at: {0}".format(self.dll))
            else:
                self.print_error('Failed to find the DLL in the system')
                return False

            # Loading DLL into the process
            self.print_info('Loading DLL into the process...')
            try:
                self.dll_handle = self.process_handle.load_library(self.dll)
            except Exception as error:
                print("[-] {0}".format(error.msg))
                return False
            else:
                self.print_ok(
                    "Loaded {0} into process with pid {1} with handle 0x{2:08x}".format(self.dll, self.pid, self.dll_handle))

            return result
Example #2
0
    def __init__(self, os_name=None):
        """
		:param str os_name: The name of the Windows operating system for which to resolve syscall names to numbers.
		"""
        if process_is_wow64():
            raise RuntimeError('python running in WOW64 is not supported')

        self._syscall_db_con = None
        if os_name is None:
            os_name = self.__name_map.get(platform.platform())
        if os_name is not None:
            self._syscall_db_con = sqlite3.connect(self._syscall_db_path,
                                                   check_same_thread=False)
            if not self._syscall_db_con.execute(
                    'SELECT COUNT(os_name) FROM syscalls WHERE arch = ? AND os_name = ?',
                (
                    self._syscall_arch,
                    os_name,
                )).fetchone()[0]:
                raise ValueError(
                    'no syscall numbers available in the database for ' +
                    os_name)
        self.os_name = os_name

        process_h = WindowsProcess(pid=-1)
        shellcode_sz = mayhem.utilities.align_up(len(self._syscall_stub), 1024)
        self.address = process_h.allocate(size=shellcode_sz)
        process_h.write_memory(self.address, self._syscall_stub)
        process_h.protect(self.address,
                          size=shellcode_sz,
                          permissions='PAGE_EXECUTE_READ')
        self._syscall = self._syscall_prototype(self.address)
Example #3
0
 def __init__(self, stub=None):
     if process_is_wow64():
         raise RuntimeError('python running in WOW64 is not supported')
     asm_function_stub = stub or self._asm_function_stub
     process_h = WindowsProcess(pid=-1)
     shellcode_sz = mayhem.utilities.align_up(len(asm_function_stub), 1024)
     self.address = process_h.allocate(size=shellcode_sz)
     process_h.write_memory(self.address, asm_function_stub)
     process_h.protect(self.address,
                       size=shellcode_sz,
                       permissions='PAGE_EXECUTE_READ')
     self._asm_function = self._asm_function_prototype(self.address)
Example #4
0
	def __init__(self, syscall_map=None):
		self.syscall_map = syscall_map

		process_h = WindowsProcess(pid=-1)
		shellcode_sz = align_up(len(syscall_stub), 1024)
		self.address = process_h.allocate(size=shellcode_sz)
		process_h.write_memory(self.address, syscall_stub)
		process_h.protect(self.address, size=shellcode_sz, permissions='PAGE_EXECUTE_READ')
		self._syscall = syscall_prototype(self.address)
Example #5
0
	def __init__(self, stub=None):
		if process_is_wow64():
			raise RuntimeError('python running in WOW64 is not supported')
		asm_function_stub = stub or self._asm_function_stub
		process_h = WindowsProcess(pid=-1)
		shellcode_sz = mayhem.utilities.align_up(len(asm_function_stub), 1024)
		self.address = process_h.allocate(size=shellcode_sz)
		process_h.write_memory(self.address, asm_function_stub)
		process_h.protect(self.address, size=shellcode_sz, permissions='PAGE_EXECUTE_READ')
		self._asm_function = self._asm_function_prototype(self.address)
Example #6
0
	def __init__(self, os_name=None):
		"""
		:param str os_name: The name of the Windows operating system for which to resolve syscall names to numbers.
		"""
		if process_is_wow64():
			raise RuntimeError('python running in WOW64 is not supported')

		self._syscall_db_con = None
		if os_name is not None:
			self._syscall_db_con = sqlite3.connect(self._syscall_db_path, check_same_thread=False)
			if not self._syscall_db_con.execute('SELECT COUNT(os_name) FROM syscalls WHERE arch = ? AND os_name = ?', (self._syscall_arch, os_name,)).fetchone()[0]:
				raise ValueError('no syscall numbers available in the database for ' + os_name)
		self.os_name = os_name

		process_h = WindowsProcess(pid=-1)
		shellcode_sz = align_up(len(self._syscall_stub), 1024)
		self.address = process_h.allocate(size=shellcode_sz)
		process_h.write_memory(self.address, self._syscall_stub)
		process_h.protect(self.address, size=shellcode_sz, permissions='PAGE_EXECUTE_READ')
		self._syscall = self._syscall_prototype(self.address)
Example #7
0
class BoomerModule(Module):

    process_handle = None
    pid = None
    dll = None
    dll_handle = None

    def __init__(self, options={}, info={}):
        if len(info) == 0:
            info = {
                "Name": "DLL Injection - CreateRemoteThread Method",
                "Author": "Antonio Marcos",
                "Description": "Inject a DLL into a process."
            }
        if len(options) == 0:
            options = {
                "pid": ["Target PID to inject dll", None, False],
                "process_name": ["Process name to inject dll", None, False],
                "dll": ["Absolute path to the DLL to inject", None, True]
            }

        if architecture()[0] == "64bit":
            self.print_info("Process and DLL to injec must be 64 bits")
        else:
            self.print_info("Process and DLL to injec must be 32 bits")
        super(BoomerModule, self).__init__(options, info)


    def run(self):
        validation_message = self.initial_validation()
        if validation_message is not None:
            self.print_error(validation_message)
            return

        # Setting pid variable
        self.pid_initialization()

        # Getfing dll path form options
        dll_path = self.options.get('dll')[1]

        # Injecting dll from the given path into the process with the given pid
        if not self.inject_dll(dll_path):
            return

        # Closing process handle
        self.close_process_handle()

    def pid_initialization(self):
        if self.options.get('pid')[1] == "" or self.options.get('pid')[1] == None:
            self.pid = self.get_pid_by_process_name(self.options.get('process_name')[1])
        else:
            self.pid = int(self.options.get('pid')[1])

    def inject_dll(self, dll_path):
        result = True
        if self.pid != None:
            # Getting process handler
            try:
                arch = self.get_arch()
                self.process_handle = WindowsProcess(pid=self.pid, arch=arch)
            except Exception as error:
                self.print_error("{0}".format(error.msg))
                return False

            self.print_info("Opened a handle to pid: {0}".format(self.pid))

            # Finding and injecting dll
            self.dll = ctypes.util.find_library(dll_path)
            if self.dll:
                self.print_info("Found DLL at: {0}".format(self.dll))
            else:
                self.print_error('Failed to find the DLL in the system')
                return False

            # Loading DLL into the process
            self.print_info('Loading DLL into the process...')
            try:
                self.dll_handle = self.process_handle.load_library(self.dll)
            except Exception as error:
                print("[-] {0}".format(error.msg))
                return False
            else:
                self.print_ok(
                    "Loaded {0} into process with pid {1} with handle 0x{2:08x}".format(self.dll, self.pid, self.dll_handle))

            return result

    def initial_validation(self):
        # Validate that there is an option set for pid and process_name
        if not self.input_validation():
            return "It's mandatory to specify a pid or a process name"

        # Validate that the platform where the module is running is Windows
        if not self.platform_validation():
            return "This module is only available on Windows"

    def platform_validation(self):
        result = True
        if not sys.platform.startswith('win'):
            result = False
        return result

    def input_validation(self):
        result = True
        option_pid = self.options.get("pid")[1]
        option_process_name = self.options.get("process_name")[1]
        if (option_pid == None or option_pid == "") and (option_process_name == None or option_process_name == ""):
            result = False
        return result

    def get_arch(self):
        return architecture()[0]

    def get_pid_by_process_name(self, process_name):
        pid = None
        for proc in psutil.process_iter():
            if proc.name() == process_name:
                pid = proc.pid
                break
        return pid

    def close_process_handle(self):
        self.process_handle.close()
Example #8
0
def main():
    parser = argparse.ArgumentParser(
        description='python_injector: inject python code into a process',
        conflict_handler='resolve')
    parser.add_argument('script_path',
                        action='store',
                        help='python script to inject into the process')
    parser.add_argument('procname',
                        action='store',
                        help='process to inject into')
    parser.epilog = 'The __name__ variable will be set to "__mayhem__".'
    arguments = parser.parse_args()

    if not sys.platform.startswith('win'):
        print('[-] This tool is only available on Windows')
        return

    proc_pid = getpid(arguments.procname)
    if proc_pid is None:
        print("Cant find process")
        sys.exit(1)
    else:
        print(f"PID is : {proc_pid}")
    # get a handle the the process
    try:
        process_h = WindowsProcess(pid=proc_pid)
    except ProcessError as error:
        print("[-] {0}".format(error.msg))
        return
    print("[+] Opened a handle to pid: {0}".format(proc_pid))

    # find and inject the python library
    python_lib = "python{0}{1}.dll".format(sys.version_info.major,
                                           sys.version_info.minor)
    python_lib = ctypes.util.find_library(python_lib)
    if python_lib:
        print("[*] Found Python library at: {0}".format(python_lib))
    else:
        print('[-] Failed to find the Python library')
        return

    print('[*] Injecting Python into the process...')
    try:
        python_lib_h = process_h.load_library(python_lib)
    except ProcessError as error:
        print("[-] {0}".format(error.msg))
        return
    else:
        print("[+] Loaded {0} with handle 0x{1:08x}".format(
            python_lib, python_lib_h))

    # resolve the necessary functions
    local_handle = m_k32.GetModuleHandleW(python_lib)
    py_initialize_ex = python_lib_h + (
        m_k32.GetProcAddress(local_handle, b'Py_InitializeEx') - local_handle)
    py_run_simple_string = python_lib_h + (m_k32.GetProcAddress(
        local_handle, b'PyRun_SimpleString') - local_handle)
    print('[*] Resolved addresses:')
    print("  - Py_InitializeEx:    0x{0:08x}".format(py_initialize_ex))
    print("  - PyRun_SimpleString: 0x{0:08x}".format(py_run_simple_string))

    # call remote functions to initialize and run via remote threads
    thread_h = process_h.start_thread(py_initialize_ex, 0)
    process_h.join_thread(thread_h)
    print('[*] Initialized Python in the host process')

    print("[*] Waiting for client to connect on \\\\.\\pipe\\{0}".format(
        PIPE_NAME))
    injection_stub = INJECTION_STUB_TEMPLATE
    injection_stub = injection_stub.format(path=_escape(
        os.path.abspath(arguments.script_path)),
                                           pipe_name=PIPE_NAME)
    injection_stub = injection_stub.encode('utf-8') + b'\x00'

    alloced_addr = process_h.allocate(size=utilities.align_up(
        len(injection_stub)),
                                      permissions='PAGE_READWRITE')
    process_h.write_memory(alloced_addr, injection_stub)
    thread_h = process_h.start_thread(py_run_simple_string, alloced_addr)
    client = NamedPipeClient.from_named_pipe(PIPE_NAME)
    print('[*] Client connected on named pipe')
    while True:
        message = client.read()
        if message is None:
            break
        sys.stdout.write(message.decode('utf-8'))
    client.close()
    process_h.join_thread(thread_h)
    process_h.close()
Example #9
0
def main():
	parser = argparse.ArgumentParser(description='python_injector: inject python code into a process', conflict_handler='resolve')
	parser.add_argument('script_path', action='store', help='python script to inject into the process')
	parser.add_argument('pid', action='store', type=int, help='process to inject into')
	parser.epilog = 'The __name__ variable will be set to "__mayhem__".'
	arguments = parser.parse_args()

	if not sys.platform.startswith('win'):
		print('[-] This tool is only available on Windows')
		return

	# get a handle the the process
	try:
		process_h = WindowsProcess(pid=arguments.pid)
	except ProcessError as error:
		print("[-] {0}".format(error.msg))
		return
	print("[+] Opened a handle to pid: {0}".format(arguments.pid))

	# find and inject the python library
	python_lib = "python{0}{1}.dll".format(sys.version_info.major, sys.version_info.minor)
	python_lib = ctypes.util.find_library(python_lib)
	if python_lib:
		print("[*] Found Python library at: {0}".format(python_lib))
	else:
		print('[-] Failed to find the Python library')
		return

	print('[*] Injecting Python into the process...')
	try:
		python_lib_h = process_h.load_library(python_lib)
	except ProcessError as error:
		print("[-] {0}".format(error.msg))
		return
	else:
		print("[+] Loaded {0} with handle 0x{1:08x}".format(python_lib, python_lib_h))

	# resolve the necessary functions
	local_handle = m_k32.GetModuleHandleW(python_lib)
	py_initialize_ex = python_lib_h + (m_k32.GetProcAddress(local_handle, b'Py_InitializeEx') - local_handle)
	py_run_simple_string = python_lib_h + (m_k32.GetProcAddress(local_handle, b'PyRun_SimpleString') - local_handle)
	print('[*] Resolved addresses:')
	print("  - Py_InitializeEx:    0x{0:08x}".format(py_initialize_ex))
	print("  - PyRun_SimpleString: 0x{0:08x}".format(py_run_simple_string))

	# call remote functions to initialize and run via remote threads
	thread_h = process_h.start_thread(py_initialize_ex, 0)
	process_h.join_thread(thread_h)
	print('[*] Initialized Python in the host process')

	print("[*] Waiting for client to connect on \\\\.\\pipe\\{0}".format(PIPE_NAME))
	injection_stub = INJECTION_STUB_TEMPLATE
	injection_stub = injection_stub.format(
		path=_escape(os.path.abspath(arguments.script_path)),
		pipe_name=PIPE_NAME
	)
	injection_stub = injection_stub.encode('utf-8') + b'\x00'

	alloced_addr = process_h.allocate(size=utilities.align_up(len(injection_stub)), permissions='PAGE_READWRITE')
	process_h.write_memory(alloced_addr, injection_stub)
	thread_h = process_h.start_thread(py_run_simple_string, alloced_addr)
	client = NamedPipeClient.from_named_pipe(PIPE_NAME)
	print('[*] Client connected on named pipe')
	while True:
		message = client.read()
		if message is None:
			break
		sys.stdout.write(message.decode('utf-8'))
	client.close()
	process_h.join_thread(thread_h)
	process_h.close()