# 2.1. Processes and Threads — PythonForWindows 1.0.4 documentation

# 2.1. Processes and Threads

## 2.1.1. CurrentProcess

Note

See sample windows.current_process

class windows.winobject.process.CurrentProcess

  Bases: `Process`

  The current process

  allocated_memory(size, prot=PAGE_EXECUTE_READWRITE(0x40))

    ContextManager to allocate memory and free it

    Type:

      `int` – the address of the allocated memory

  property bitness

    The bitness of the process

    Type:

      `int` – 32 or 64

  create_thread(lpStartAddress, lpParameter, dwCreationFlags=0)

    Create a new thread

    Return type:

      `WinThread` or `DeadThread`

  execute(code, parameter=0)

    Execute native code `code` in the current thread.

    Return type:

      `int` the return value of the native code

  exit(code=0)

    Exit the process

  property exit_code

    The exit code of the process : `STILL_ACTIVE` means the process is not dead

    Type:

      `int`

  get_mapped_filename(addr)

    The filename mapped at address `addr` or `None`

    Return type:

      `unicode` or `None`

  property handle

    An handle on the object

    Type:

      HANDLE

      Note

      The handle is automaticaly closed when the object is destroyed

  property is_exit

    `True` if the process is terminated

    Type:

      `bool`

  property is_wow_64

    `True` if the process is a SysWow64 process (32bit process on 64bits system).

    Type:

      `bool`

  load_library(dll_path)

    Load the library in current process

    Return type:

      `LoadedModule`

  memory_state()

    Yield the memory information for the whole address space of the process

    Yield:

      `MEMORY_BASIC_INFORMATION`

  property name

    Name of the process

    Type:

      `str`

  open_token(flags=MAXIMUM_ALLOWED(0x2000000))

    Open the process Token

    Returns:

      `Token`

  property peb

    The Process Environment Block of the current process

    Type:

      `PEB`

  property peb_syswow

    The 64bits PEB of a SysWow64 process

    Type:

      `PEB`

  property pid

    Process ID

    Type:

      `int`

  property ppid

    Parent Process ID

    Type:

      `int`

  property priority
  query_memory(addr)

    Query the memory informations about page at `addr`

    Return type:

      `MEMORY_BASIC_INFORMATION`

  read_byte(addr)

    Read a `CHAR` at `addr`

  read_dword(addr)

    Read a `DWORD` at `addr`

  read_memory(addr, size)

    Read `size` from `addr`

    Returns:

      The data read

    Return type:

      `str`

  read_ptr(addr)

    Read a `PTR` at `addr`

  read_qword(addr)

    Read a `ULONG64` at `addr`

  read_short(addr)

    Read a `SHORT` at `addr`

  read_string(addr)

    Read an ascii string at `addr`

  read_wstring(addr)

    Read a windows UTF16 string at `addr`

  property threads

    The threads of the process

    Type:

      [`WinThread`] – A list of Thread

  property time_info

    The time information of the process (creation, kernel/user time, exit time)

    Type:

      `TimeInfo`

  property token

    The process `Token`

  virtual_alloc(size, prot=PAGE_EXECUTE_READWRITE(0x40), addr=None, type=MEM_COMMIT(0x1000))

    Allocate memory in the process

    Returns:

      The address of the allocated memory

    Return type:

      `int`

  virtual_free(addr)

    Free memory in the process by virtual_alloc

  virtual_protect(addr, size, protect, old_protect=None)

    Change the access right of one or more page of the process

  virtual_protected(addr, size, protect)

    A context manager for local virtual_protect (old Protection are restored at exit)

  wait(timeout=INFINITE(0xffffffff))

    Raise `ValueError` to prevent deadlock :D

  write_byte(addr, byte)

    write a byte at `addr`

  write_dword(addr, dword)

    write a dword at `addr`

  write_memory(addr, data)

    Write data at addr

  write_ptr(addr, value)

    Write a `PTR` at `addr`

  write_qword(addr, qword)

    write a qword at `addr`

  write_short(addr, word)

    write a word at `addr`

## 2.1.2. CurrentThread

class windows.winobject.process.CurrentThread

  Bases: `Thread`

  The current thread

  exit(code=0)

    Exit the thread

  property handle

    An handle on the object

    Type:

      HANDLE

      Note

      The handle is automaticaly closed when the object is destroyed

  open_token(flags=MAXIMUM_ALLOWED(0x2000000), as_self=False)

    Open the Thread token if any (Impersonation) else return None. `as_self` tells which security context should be used

    Returns:

      `Token`

    Note

    see https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-openthreadtoken

  property owner

    The current process

    Type:

      `CurrentProcess`

  set_token(token)

    Set the token for the thread (impersonation). Setting the token to None revert the impersonation

  property tid

    Thread ID

    Type:

      `int`

  property token

    The thread `Token`

    Getter:

      `open_token()`

    Setter:

      `set_token()`

  wait(timeout=INFINITE(0xffffffff))

    Raise `ValueError` to prevent deadlock :D

## 2.1.3. WinProcess

Note

See sample Remote process : WinProcess

class windows.winobject.process.WinProcess(pid=None, handle=None, name=None, ppid=None)

  Bases: `Process`

  A Process on the system

  allocated_memory(size, prot=PAGE_EXECUTE_READWRITE(0x40))

    ContextManager to allocate memory and free it

    Type:

      `int` – the address of the allocated memory

  property bitness

    The bitness of the process

    Returns:

      `int` – 32 or 64

  create_thread(addr, param)

    Create a remote thread

    Return type:

      `WinThread` or `DeadThread`

  execute(code, parameter=0)

    Execute some native code in the context of the process

    Returns:

      The thread executing the code

    Return type:

      `WinThread` or `DeadThread`

  execute_python(pycode)

    Execute Python code in the remote process.

    This function waits for the remote process to end and raises an exception if the remote thread raised one

    Note

    This method is incompatible with Microsoft Store builds of python, as the interpreter DLLs do not grant execute to Users. See workaround: https://hakril.github.io/PythonForWindows/build/html/sample.html#microsoft-store-python-injection

  execute_python_unsafe(pycode)

    Execute Python code in the remote process.

    Return type:

      rtype:

        `WinThread` or `DeadThread` : The thread executing the python code

    Note

    This method is incompatible with Microsoft Store builds of python, as the interpreter DLLs do not grant execute to Users. See workaround: https://hakril.github.io/PythonForWindows/build/html/sample.html#microsoft-store-python-injection

  exit(code=0)

    Exit the process

  property exit_code

    The exit code of the process : `STILL_ACTIVE` means the process is not dead

    Type:

      `int`

  get_mapped_filename(addr)

    The filename mapped at address `addr` or `None`

    Return type:

      `unicode` or `None`

  property handle

    An handle on the object

    Type:

      HANDLE

      Note

      The handle is automaticaly closed when the object is destroyed

  property is_exit

    `True` if the process is terminated

    Type:

      `bool`

  property is_wow_64

    `True` if the process is a SysWow64 process (32bit process on 64bits system).

    Type:

      `bool`

  load_library(dll_path)

    Load the library in remote process

    Return type:

      `LoadedModule`

  memory_state()

    Yield the memory information for the whole address space of the process

    Yield:

      `MEMORY_BASIC_INFORMATION`

  property name

    Name of the process

    Type:

      `str`

  open_token(flags=MAXIMUM_ALLOWED(0x2000000))

    Open the process Token

    Returns:

      `Token`

  property peb

    The PEB of the process (see `remotectypes`)

    Type:

      `PEB`

  property peb_addr

    The address of the PEB.

    Type:

      `int`

  property peb_syswow

    The 64bits PEB of a SysWow64 process

    Type:

      `PEB`

  property pid

    Process ID

    Type:

      `int`

  property ppid

    Parent Process ID

    Type:

      `int`

  property priority
  query_memory(addr)

    Query the memory informations about page at `addr`

    Return type:

      `MEMORY_BASIC_INFORMATION`

  read_byte(addr)

    Read a `CHAR` at `addr`

  read_dword(addr)

    Read a `DWORD` at `addr`

  read_memory(addr, size)

    Read `size` from `addr`

    Returns:

      The data read

    Return type:

      `str`

  read_memory_into(addr, struct)

    Read a `ctypes` struct from addr

    Returns:

      struct

  read_ptr(addr)

    Read a `PTR` at `addr`

  read_qword(addr)

    Read a `ULONG64` at `addr`

  read_short(addr)

    Read a `SHORT` at `addr`

  read_string(addr)

    Read an ascii string at `addr`

  read_wstring(addr)

    Read a windows UTF16 string at `addr`

  property threads

    The threads of the process

    Type:

      [`WinThread`] – A list of Thread

  property time_info

    The time information of the process (creation, kernel/user time, exit time)

    Type:

      `TimeInfo`

  property token

    The process `Token`

  virtual_alloc(size, prot=PAGE_EXECUTE_READWRITE(0x40), addr=None, type=MEM_COMMIT(0x1000))

    Allocate memory in the process

    Returns:

      The address of the allocated memory

    Return type:

      `int`

  virtual_free(addr)

    Free memory in the process by virtual_alloc

  virtual_protect(addr, size, protect, old_protect=None)

    Change the access right of one or more page of the process

  virtual_protected(addr, size, protect)

    A context manager for local virtual_protect (old Protection are restored at exit)

  wait(timeout=INFINITE(0xffffffff))

    Wait for the object

  write_byte(addr, byte)

    write a byte at `addr`

  write_dword(addr, dword)

    write a dword at `addr`

  write_memory(addr, data)

    Write data at addr

  write_ptr(addr, value)

    Write a `PTR` at `addr`

  write_qword(addr, qword)

    write a qword at `addr`

  write_short(addr, word)

    write a word at `addr`

## 2.1.4. WinThread

class windows.winobject.process.WinThread(tid=None, handle=None, owner_pid=None, owner=None)

  Bases: `Thread`

  Represent a thread

  property context

    The context of the thread, type depend of the target process.

    Type:

      `windows.exception.ECONTEXT32` or `windows.exception.ECONTEXT64` or `windows.exception.ECONTEXTWOW64`

  property context_syswow

    The 64 bits context of a syswow thread.

    Type:

      `windows.exception.ECONTEXT64`

  exit(code=0)

    Exit the thread

  property exit_code

    The exit code of the thread : `STILL_ACTIVE` means the process is not dead

    Type:

      `int`

  property handle

    An handle on the object

    Type:

      HANDLE

      Note

      The handle is automaticaly closed when the object is destroyed

  property is_exit

    `True` if the thread is terminated

    Type:

      `bool`

  open_token(flags=MAXIMUM_ALLOWED(0x2000000), as_self=False)

    Open the Thread token if any (Impersonation) else return None. `as_self` tells which security context should be used

    Returns:

      `Token`

    Note

    see https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-openthreadtoken

  property owner

    The Process owning the thread

    Type:

      `WinProcess`

  resume()

    Resume the thread

  set_context(context)

    Set the thread’s context to `context`

  set_syswow_context(context)

    Set a syswow thread’s 64 context to `context`

  set_token(token)

    Set the token for the thread (impersonation). Setting the token to None revert the impersonation

  property start_address

    The start address of the thread

    Type:

      `int`

  suspend()

    Suspend the thread

  property teb_base

    The address of the thread’s TEB. If the owner is a SysWow64 process, return the TEB32.

    Type:

      `int`

  property teb_syswow_base

    The address of the thread’s TEB64 for a SysWow64 process

    Type:

      `int`

  property tid

    Thread ID

    Type:

      `int`

  property token

    The thread `Token`

    Getter:

      `open_token()`

    Setter:

      `set_token()`

  wait(timeout=INFINITE(0xffffffff))

    Wait for the object

class windows.winobject.process.DeadThread(handle, tid=None)

  Bases: `AutoHandle`

  An already dead thread (returned only by API returning a new thread if thread die before being returned)

  property exit_code

    The exit code of the thread : `STILL_ACTIVE` means the process is not dead

    Type:

      `int`

  property handle

    An handle on the object

    Type:

      HANDLE

      Note

      The handle is automaticaly closed when the object is destroyed

  property is_exit

    `True` if the thread is terminated

    Type:

      `bool`

  wait(timeout=INFINITE(0xffffffff))

    Wait for the object

# 2.2. PEB Exploration

The `windows` module is able to parse the PEB of the current process or remote process. The `PEB` is accessible via `process.peb` and is of type `PEB`.

Note

See sample PEB exploration

## 2.2.1. PEB

class windows.winobject.process.PEB

  The PEB (Process Environment Block) of the current process

  property apisetmap

    The `ApiSetMap` of the process

    Return type:

      A subclass of `ApiSetMap`

    Raise:

      `NotImplementedError` – Before `6.2` ApiSetMap did not exist

    Raise:

      `NotImplementedError` – Not implemented for remote process

  property commandline

    The CommandLine of the PEB

    Type:

      `LSA_UNICODE_STRING`

  property exe

    The executable of the process, as pointed by PEB.ImageBaseAddress

    Type:

      `windows.pe_parse.PEFile`

  property imagepath

    The ImagePathName of the PEB

    Type:

      `LSA_UNICODE_STRING`

  property modules

    The loaded modules present in the PEB

    Type:

      [`LoadedModule`] – List of loaded modules

## 2.2.2. LoadedModule

class windows.winobject.process.LoadedModule

  An entry in the PEB Ldr list

  property baseaddr

    Base address of the module

    Type:

      `int`

  property fullname

    Full name of the module (path)

    Type:

      `str`

  property name

    Name of the module

    Type:

      `str`

  property pe

    A PE representation of the module

    Type:

      `windows.pe_parse.PEFile`

## 2.2.3. ApiSetMap

Note

see sample ApiSetMap

class windows.winobject.apisetmap.ApiSetMap(base)

  The base class for the ApiSeMap (see Runtime DLL name resolution: ApiSetSchema)

  property apisetmap_dict

    The apisetmap dll-mapping content extracted from memory as a `dict`

    `key -> value example`:

        u'ext-ms-win-advapi32-encryptedfile-l1-1-1' -> u'advapi32.dll'

  property resolution_dict

    The `dict` based on `apisetmap_dict` with only the part checked by `Windows`.

    `Windows` does not care about what is after the last `-`

    `key -> value example`:

        u'ext-ms-win-advapi32-encryptedfile-l1-1-' -> u'advapi32.dll'

  resolve(dllname)

    The method used to resolve a DLL name using the ApiSetMap. The behavior should match the non-exported function `ntdll!ApiSetResolveToHost`

  version = None

    The version of the ApiSetMap

Note

Currently supported version for the ApiSetMap are 2/4/6

class windows.winobject.apisetmap.ApiSetMapVersion2(base)

  Represent an ApiSetMap version-2

  version = 2

    The version of the ApiSetMap

class windows.winobject.apisetmap.ApiSetMapVersion4(base)

  Represent an ApiSetMap version-4

  version = 4

    The version of the ApiSetMap

class windows.winobject.apisetmap.ApiSetMapVersion6(base)

  Represent an ApiSetMap version-6

  version = 6

    The version of the ApiSetMap

# 2.3. PEFile - Parsing loaded PE

## 2.3.1. `windows.pe_parse`

windows.pe_parse.GetPEFile(baseaddr, target=None, force_bitness=None)

  Returns a `PEFile` to explore a PE loaded at baseaddr in process target.

  Return type:

    `PEFile`

  Note

  If target is `None` it refers to the current process

### 2.3.1.1. PEFile

class windows.pe_parse.PEFile(target, baseaddr, targetedbitness, transformers)

  Represent a PE loaded in a process (current or remote)

  property binid

    Return the hex-string {TimeStamp}{SizeOfCode} used by PDB to identify a PE.

    I do not know the official name of this value…

    Type:

      `str`

  property export_name

    The Name attribute of the `EXPORT_DIRECTORY`

  property exports

    The exports of the PE in a dict. Keys are ordinal (`int`) and name (`str`). The values are the addresses of the exports.

    > type:

    >   {(`int` or `str`) : `int`}

  property imports

    The imports of the PE in a dict. Keys are the names of DLL to import from and values are `list` of `IATEntry`

    > type:

    >   {`str` : [`IATEntry`]}

### 2.3.1.2. IATEntry

class windows.pe_parse.IATEntry

  Represent an entry in the IAT of a module Can be used to get resolved value and setup hook

  addr

    `int` : Address of the IAT Entry

  ord

    `int` : Ordinal of the imported function

  name

    `int` : Name of the imported function

  value

    `int` : The content (destination) of the IAT entry

    Warning

    value is a descriptor. Setting its value will actually CHANGE THE IAT ENTRY, resulting in a segfault if no VirtualProtect have been done.

    Note

    See: `windows.utils.VirtualProtected`

  remove_hook()

    Remove the hook on the entry

  set_hook(callback, types=None)

    Setup a hook on the entry and return it. You MUST keep a reference to the hook while the hook is enabled.

    Parameters:

      callback –

      the hook

      Note

      see Hook protocol

    Return type:

      `windows.hooks.IATHook`

    Warning

    This works only for PEFile with the current process as target.