Exemplo n.º 1
0
def get_haldispatchtable():
    """
	Get the address of the halDispatchTable.

	:return: The address of the halDispatchTable.
	:rtype: int
	"""
    if process_is_wow64():
        raise RuntimeError('python running in WOW64 is not supported')
    (krnlbase, kernelver) = find_driver_base()
    hKernel = m_k32.LoadLibraryExA(kernelver, 0, 1)
    halDispatchTable = m_k32.GetProcAddress(hKernel, 'HalDispatchTable')
    halDispatchTable -= hKernel
    halDispatchTable += krnlbase
    return halDispatchTable
Exemplo n.º 2
0
def mayhem():
    handle = -1  # -1 is always a handle to the current process
    module_handle = m_k32.GetModuleHandleW('user32.dll')
    if not module_handle:
        print('user32.dll is not loaded')
        return
    address = m_k32.GetProcAddress(module_handle, b'GetClipboardData')
    if not address:
        print('failed to resolve user32.dll!GetClipboardData')
        return

    stub = jump_stub(ctypes.cast(GetClipboardData, ctypes.c_void_p).value)
    if m_k32.WriteProcessMemory(handle, address, stub, len(stub), None):
        print(
            "successfully installed the trampoline at 0x{0:x}".format(address))
    else:
        print('failed to install the trampoline')
Exemplo n.º 3
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()