{"id":26552107,"url":"https://github.com/hakril/pythonforwindows","last_synced_at":"2025-05-14T12:11:43.159Z","repository":{"id":45990132,"uuid":"49235784","full_name":"hakril/PythonForWindows","owner":"hakril","description":"A codebase aimed to make interaction with Windows and native execution easier","archived":false,"fork":false,"pushed_at":"2025-05-05T09:57:45.000Z","size":18591,"stargazers_count":618,"open_issues_count":0,"forks_count":117,"subscribers_count":25,"default_branch":"master","last_synced_at":"2025-05-05T10:32:22.337Z","etag":null,"topics":["python","rpc","windows","wmi"],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hakril.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":"AUTHORS","dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2016-01-07T22:54:33.000Z","updated_at":"2025-05-05T09:57:51.000Z","dependencies_parsed_at":"2024-01-12T03:36:28.976Z","dependency_job_id":"f7684066-9106-475f-a03e-e2c5c80cb4e9","html_url":"https://github.com/hakril/PythonForWindows","commit_stats":{"total_commits":690,"total_committers":11,"mean_commits":62.72727272727273,"dds":0.2623188405797101,"last_synced_commit":"0f501ab46d033749ad1c2f6a77593c063904d7c1"},"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hakril%2FPythonForWindows","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hakril%2FPythonForWindows/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hakril%2FPythonForWindows/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hakril%2FPythonForWindows/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hakril","download_url":"https://codeload.github.com/hakril/PythonForWindows/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254140768,"owners_count":22021220,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["python","rpc","windows","wmi"],"created_at":"2025-03-22T08:23:53.701Z","updated_at":"2025-05-14T12:11:38.146Z","avatar_url":"https://github.com/hakril.png","language":"Python","readme":"# PythonForWindows\n\n[![Pytest](https://github.com/hakril/PythonForWindows/actions/workflows/tests.yml/badge.svg?branch=master)](https://github.com/hakril/PythonForWindows/actions/workflows/tests.yml)\n\nPythonForWindows (PFW) is a base of code aimed to make interaction with `Windows` (on X86/X64) easier (for both 32 and 64 bits Python).\nIts goal is to offer abstractions around some of the OS features in a (I hope) pythonic way.\nIt also tries to make the barrier between python and native execution thinner in both ways.\nThere is no external dependencies but it relies heavily on the `ctypes` module.\n\nLet's say that the codebase evolves with my needs, my researches and my curiosity.\n\nComplete online documentation is available [here][ONLINE_DOC]\nYou can find some examples of code in the [samples directory][SAMPLE_DIR] or [online][ONLINE_SAMPLE].\n\nPythonForWindows is principally known for:\n\n- its ALPC-RPC Client (see [samples](https://hakril.github.io/PythonForWindows/build/html/sample.html#windows-rpc))\n- its generated [ctypes definitions](https://github.com/hakril/PythonForWindows/tree/master/windows/generated_def).\n\n\n\nIf you have any issue, question or suggestion do not hesitate to create an issue or reach me out.\nI am always glad to have feedbacks from people using this project.\n\n## Installation\n\n\nPythonForWindows is available on [Pypi](https://pypi.org/project/PythonForWindows/) an this can be installed with\n\n``\npython -m pip install PythonForWindows\n``\n\nYou can also install PythonForWindows by cloning it and using the ``setup.py`` script:\n\n``\npython setup.py install\n``\n\n## Encoding \u0026 unicode\n\nPythonForWindows support `python2.7` \u0026 `python3` and is currently tested for `Python2.7`, `3.6` \u0026 `3.11` via [Github Workflow](https://github.com/hakril/PythonForWindows/actions/workflows/tests.yml)\n\nSince 1.0.0, the code uses \"wide APIs\" whenever possible and accept/returns python3 `str` (py2.7 `unicode` type) almost everywhere. Any functions/APIs not accepting unicode string can be  considered a bug if its not stated explicitly in the documentation.\n\n### Python2\n\nPythonForWindows continues to support python2.7 as its the only way to have it running on `Windows XP` \u0026 `Windows Server 2003` which are sadly still seen in production.\nEncoding errors at print time might be awkward for unicode string on python2, see the [PythonForWindows encoding guide](https://hakril.github.io/PythonForWindows/build/html/encoding.html) in the documentation.\n\n\n## Overview\n\n### Processes / Threads\n\nPythonForWindows offers objects around processes and allows you to:\n\n- Retrieve basic process informations (pid, name, ppid, bitness, ...)\n- Perform basic interprocess operation (allocation, create thread, read/write memory)\n- Explore the PEB (Process Environment Block)\n- Execute `native` and `Python` code in the context of a process.\n\nI try my best to make those features available for every cross-bitness processes (`32 \u003c-\u003e 64` in both ways).\nThis involves relying on non-documented `Windows` functions/behaviours and also injecting code in the 64bits world of a `Syswow64` process.\nAll those operations are also available for the `current_process`.\n\nYou can also make some operation on threads (suspend/resume/wait/get(or set) context/ kill)\n\n```python\n\u003e\u003e\u003e import windows\n\u003e\u003e\u003e windows.current_process.bitness\n32\n\u003e\u003e\u003e windows.current_process.token.integrity\nSECURITY_MANDATORY_MEDIUM_RID(0x2000)\n\u003e\u003e\u003e proc = [p for p in windows.system.processes if p.name == \"notepad.exe\"][0]\n\u003e\u003e\u003e proc\n\u003cWinProcess \"notepad.exe\" pid 16520 at 0x544e410\u003e\n\u003e\u003e\u003e proc.bitness\n64\n\u003e\u003e\u003e proc.peb.modules[:3]\n[\u003cRemoteLoadedModule64 \"notepad.exe\" at 0x3671e90\u003e, \u003cRemoteLoadedModule64 \"ntdll.dll\" at 0x3671030\u003e, \u003cRemoteLoadedModule64 \"kernel32.dll\" at 0x3671080\u003e]\n\u003e\u003e\u003e k32 = proc.peb.modules[2]\n\u003e\u003e\u003e hex(k32.pe.exports[\"CreateFileW\"])\n'0x7ffee6761550L'\n\u003e\u003e\u003e proc.threads[0]\n\u003cWinThread 17688 owner \"notepad.exe\" at 0x53b47f0\u003e\n\u003e\u003e\u003e hex(proc.threads[0].context.Rip)\n'0x7ffee68b54b0L'\n\u003e\u003e\u003e proc.execute_python(\"import os\")\nTrue\n\u003e\u003e\u003e proc.execute_python(\"exit(os.getpid() + 1)\")\n# execute_python raise if process died\nTraceback (most recent call last):\n...\nWindowsError: \u003cWinProcess \"notepad.exe\" pid 16520 (DEAD) at 0x579f610\u003e died during execution of python command\n\u003e\u003e\u003e calc\n\u003cWinProcess \"notepad.exe\" pid 16520 (DEAD) at 0x579f610\u003e\n\u003e\u003e\u003e calc.exit_code\n16521L\n```\n\n### System information\n\nInformation about the Windows computer running the script are available through the `windows.system` object.\n\n```python\n\u003e\u003e\u003e windows.system\n\u003cwindows.winobject.system.System object at 0x03FEED10\u003e\n\u003e\u003e\u003e windows.system.bitness\n64\n\u003e\u003e\u003e windows.system.computer_name\n'DESKTOP-VKUGISR'\n\u003e\u003e\u003e windows.system.product_type\nVER_NT_WORKSTATION(0x1)\n\u003e\u003e\u003e windows.system.version\n(10, 0)\n\u003e\u003e\u003e windows.system.version_name\n'Windows 10'\n\u003e\u003e\u003e windows.system.build_number\n'10.0.15063.608'\n\n# windows.system also contains dynamic lists about processes / threads / handles / ...\n\u003e\u003e\u003e windows.system.handles[-2:]\n[\u003cHandle value=\u003c0x5cc\u003e in process pid=14360\u003e, \u003cHandle value=\u003c0x28e4\u003e in process pid=14360\u003e]\n\u003e\u003e\u003e windows.system.processes[:2]\n[\u003cWinProcess \"[System Process]\" pid 0 at 0x433f7d0\u003e, \u003cWinProcess \"System\" pid 4 at 0x433fd30\u003e]\n\u003e\u003e\u003e windows.system.logicaldrives[0]\n\u003cLogicalDrive \"C:\\\" (DRIVE_FIXED)\u003e\n\u003e\u003e\u003e windows.system.services[23]\n\u003cServiceA \"Appinfo\" SERVICE_RUNNING(0x4)\u003e\n\n```\n\n### IAT Hook\n\nThis codebase is born from my need to have IAT hooks implemented in Python.\nSo the features is present (See [online documentation][ONLINE_IATHOOK] about IAT hooks).\n\n\n### Winproxy\n\nA wrapper around some Windows functions. Arguments name and order are the same,\nbut some have default values and the functions raise exception on call error (I don't like `if` around all my call).\n\n```python\n\u003e\u003e\u003e import windows\n\u003e\u003e\u003e help(windows.winproxy.VirtualAlloc)\n# Help on function VirtualAlloc in module windows.winproxy:\n# VirtualAlloc(lpAddress=0, dwSize=NeededParameter, flAllocationType=MEM_COMMIT(0x1000L), flProtect=PAGE_EXECUTE_READWRITE(0x40L))\n#     Errcheck:\n#     raise WinproxyError if result is 0\n\n# Positional arguments\n\u003e\u003e\u003e windows.winproxy.VirtualAlloc(0, 0x1000)\n34537472\n\n# Keyword arguments\n\u003e\u003e\u003e windows.winproxy.VirtualAlloc(dwSize=0x1000)\n34603008\n\n# NeededParameter must be provided\n\u003e\u003e\u003e windows.winproxy.VirtualAlloc()\n\"\"\"\nTraceback (most recent call last):\nFile \"\u003cstdin\u003e\", line 1, in \u003cmodule\u003e\nFile \"windows\\winproxy.py\", line 264, in VirtualAlloc\n    return VirtualAlloc.ctypes_function(lpAddress, dwSize, flAllocationType, flProtect)\nFile \"windows\\winproxy.py\", line 130, in perform_call\n    raise TypeError(\"{0}: Missing Mandatory parameter \u003c{1}\u003e\".format(self.func_name, param_name))\nTypeError: VirtualAlloc: Missing Mandatory parameter \u003cdwSize\u003e\n\"\"\"\n\n# Error raises exception\n\u003e\u003e\u003e windows.winproxy.VirtualAlloc(dwSize=0xffffffff)\n\"\"\"\nTraceback (most recent call last):\nFile \"\u003cstdin\u003e\", line 1, in \u003cmodule\u003e\nFile \"windows\\winproxy.py\", line 264, in VirtualAlloc\n    return VirtualAlloc.ctypes_function(lpAddress, dwSize, flAllocationType, flProtect)\nFile \"windows\\winproxy.py\", line 133, in perform_call\n    return self._cprototyped(*args)\nFile \"windows\\winproxy.py\", line 59, in kernel32_error_check\n    raise WinproxyError(func_name)\nwindows.winproxy.error.WinproxyError: VirtualAlloc: [Error 87] The parameter is incorrect.\n\"\"\"\n```\n\n\n### Native execution\n\nTo make the barrier between `native` and `Python` code thinner,\nPythonForWindows allows you to create native function callable from Python (thanks to `ctypes`) and also embed\na simple x86/x64 assembler.\n\n```python\n\u003e\u003e\u003e import windows.native_exec.simple_x86 as x86\n\u003e\u003e\u003e code = x86.MultipleInstr()\n\u003e\u003e\u003e code += x86.Mov(\"EAX\", 41)\n\u003e\u003e\u003e code += x86.Inc(\"EAX\")\n\u003e\u003e\u003e code += x86.Ret()\n\u003e\u003e\u003e code.get_code()\n'\\xc7\\xc0)\\x00\\x00\\x00@\\xc3'\n# Create a function that takes no parameters and return an uint\n\u003e\u003e\u003e f = windows.native_exec.create_function(code.get_code(), [ctypes.c_uint])\n\u003e\u003e\u003e f()\n42L\n# Assemblers can also be used in a more standard way\n\u003e\u003e\u003e x86.assemble(\"cmp edi, 0; jnz :end; mov eax, 1; label :end; ret\")\n'\\x81\\xff\\x00\\x00\\x00\\x00u\\x06\\xc7\\xc0\\x01\\x00\\x00\\x00\\xc3'\n```\n\n### Token / Security Descriptor\n\nObjects easing access to some information about ``Token`` and ``SecurityDescriptor`` are also available.\n\n```python\n\u003e\u003e\u003e import windows.security\n\u003e\u003e\u003e import windows.generated_def as gdef\n\u003e\u003e\u003e tok = windows.current_process.token\n\u003e\u003e\u003e tok\n\u003cToken TokenId=0x6a2b4550 Type=TokenPrimary(0x1)\u003e\n\u003e\u003e\u003e tok.username\nu'hakril'\n\u003e\u003e\u003e tok.type\ntagTOKEN_TYPE.TokenPrimary(0x1)\n\u003e\u003e\u003e tok.integrity\nSECURITY_MANDATORY_MEDIUM_RID(0x2000)\n\u003e\u003e\u003e tok.duplicate(type=gdef.TokenImpersonation, impersonation_level=gdef.SecurityIdentification)\n\u003cToken TokenId=0x6a3532ce Type=TokenImpersonation(0x2) ImpersonationLevel=SecurityIdentification(0x1)\u003e\n\n# Security Descriptor\n\u003e\u003e\u003e sd = windows.security.SecurityDescriptor.from_filename(\"c:\\windows\\system32\\kernel32.dll\")\n\u003e\u003e\u003e sd\n\u003cSecurityDescriptor object at 0x054E3DF0\u003e\n\u003e\u003e\u003e windows.utils.lookup_sid(sd.owner)\n(u'NT SERVICE', u'TrustedInstaller')\n\u003e\u003e\u003e sd.dacl\n\u003cAcl count=6\u003e\n\u003e\u003e\u003e list(sd.dacl)\n[\u003cAccessAllowedACE mask=2032127\u003e, \u003cAccessAllowedACE mask=1179817\u003e, \u003cAccessAllowedACE mask=1179817\u003e, \u003cAccessAllowedACE mask=1179817\u003e, \u003cAccessAllowedACE mask=1179817\u003e, \u003cAccessAllowedACE mask=1179817\u003e]\n\u003e\u003e\u003e sd.dacl[1].sid\n\u003cPSID \"S-1-5-32-544\"\u003e\n```\n\n### Wintrust\n\nTo easily script some signature check script, PythonForWindows implements some wrapper functions around ``wintrust.dll``\n\n```python\n\u003e\u003e\u003e import windows.wintrust\n\u003e\u003e\u003e windows.wintrust.is_signed(r\"C:\\Windows\\system32\\ntdll.dll\")\nTrue\n\u003e\u003e\u003e windows.wintrust.is_signed(r\"C:\\Windows\\system32\\python27.dll\")\nFalse\n\u003e\u003e\u003e windows.wintrust.full_signature_information(r\"C:\\Windows\\system32\\ntdll.dll\")\nSignatureData(signed=True,\n    catalog=u'C:\\\\Windows\\\\system32\\\\CatRoot\\\\{F750E6C3-38EE-11D1-85E5-00C04FC295EE}\\\\Package_35_for_KB3128650~31bf3856ad364e35~amd64~~6.3.1.2.cat',\n    catalogsigned=True, additionalinfo=0L)\n\u003e\u003e\u003e windows.wintrust.full_signature_information(r\"C:\\Windows\\system32\\python27.dll\")\nSignatureData(signed=False, catalog=None, catalogsigned=False, additionalinfo=TRUST_E_NOSIGNATURE(0x800b0100))\n```\n\n### WMI\n\nTo extract/play with even more information about the system, PythonForWindows is able to perform WMI request.\n\n```python\n\u003e\u003e\u003e import windows\n\u003e\u003e\u003e windows.system.wmi.select\n\u003cbound method WmiNamespace.select of \u003cWmiNamespace \"root\\cimv2\"\u003e\u003e\n\u003e\u003e\u003e windows.system.wmi.select(\"Win32_Process\")[:3]\n[\u003cWmiObject instance of \"Win32_Process\"\u003e, \u003cWmiObject instance of \"Win32_Process\"\u003e, \u003cWmiObject instance of \"Win32_Process\"\u003e]# Get WMI data for current process\n\u003e\u003e\u003e windows.system.wmi.select(\"Win32_Process\")[42][\"Name\"]\nu'svchost.exe'\n\u003e\u003e\u003e wmi_cp = [p for p in windows.system.wmi.select(\"Win32_Process\") if int(p[\"Handle\"]) == windows.current_process.pid][0]\n\u003e\u003e\u003e wmi_cp[\"CommandLine\"], wmi_cp[\"HandleCount\"]\n(u'\"C:\\\\Python27\\\\python.exe\"', 227)\n```\n\n### Registry\n\nThe project also contains some wrapping classes around `_winreg` for simpler use.\n\n```python\n\u003e\u003e\u003e import windows\n\u003e\u003e\u003e from windows.generated_def import KEY_WRITE, KEY_READ, REG_QWORD\n\u003e\u003e\u003e registry = windows.system.registry\n\u003e\u003e\u003e cuuser_software = registry(r'HKEY_CURRENT_USER\\Software')\n\u003e\u003e\u003e cuuser_software\n\u003cPyHKey \"HKEY_CURRENT_USER\\Software\"\u003e\n\u003e\u003e\u003e cuuser_software.sam\nKEY_READ(0x20019)\n# Explore subkeys\n\u003e\u003e\u003e cuuser_software.subkeys[:3]\n[\u003cPyHKey \"HKEY_CURRENT_USER\\Software\\7-Zip\"\u003e, \u003cPyHKey \"HKEY_CURRENT_USER\\Software\\AppDataLow\"\u003e, \u003cPyHKey \"HKEY_CURRENT_USER\\Software\\Audacity\"\u003e]\n\u003e\u003e\u003e tstkey = registry('HKEY_CURRENT_USER\\TestKey',  KEY_WRITE | KEY_READ)\n# Get / Set individual value\n\u003e\u003e\u003e tstkey[\"VALUE\"] = 'a_value_for_my_key'\n\u003e\u003e\u003e tstkey[\"VALUE\"]\nKeyValue(name='VALUE', value=u'a_value_for_my_key', type=1)\n\u003e\u003e\u003e tstkey[\"MYQWORD\"] = (123456789987654321, REG_QWORD)  # Default is REG_DWORD for int/long\n\u003e\u003e\u003e tstkey[\"MYQWORD\"]\nKeyValue(name='MYQWORD', value=123456789987654321L, type=11)\n# Explore Values\n\u003e\u003e\u003e tstkey.values\n[KeyValue(name='MYQWORD', value=123456789987654321L, type=11), KeyValue(name='VALUE', value=u'a_value_for_my_key', type=1)]\n```\n\n### Object manager\n\nPythonForWindows uses the native Windows NT API to display some information about the object in the Object Manager's name space.\nJust like the well-known tools ``winobj.exe``\n\n```python\n\u003e\u003e\u003e windows.system.object_manager.root\n\u003cKernelObject \"\\\" (type=\"Directory\")\u003e\n# The objects of type \"Directory\" can be acceded just like a dict\n\u003e\u003e\u003e list(windows.system.object_manager.root)[:3]\n[u'PendingRenameMutex', u'ObjectTypes', u'storqosfltport']\n# Find an object by its path\n\u003e\u003e\u003e windows.system.object_manager[\"KnownDLLs\\\\kernel32.dll\"]\n\u003cKernelObject \"\\KnownDLLs\\kernel32.dll\" (type=\"Section\")\u003e\n\u003e\u003e\u003e k32 = windows.system.object_manager[\"KnownDLLs\\\\kernel32.dll\"]\n\u003e\u003e\u003e k32.name, k32.fullname, k32.type\n('kernel32.dll', '\\\\KnownDLLs\\\\kernel32.dll', u'Section')\n# Follow SymbolicLink object\n\u003e\u003e\u003e windows.system.object_manager[\"\\\\KnownDLLs\\\\KnownDLLPath\"]\n\u003cKernelObject \"\\KnownDLLs\\KnownDLLPath\" (type=\"SymbolicLink\")\u003e\n\u003e\u003e\u003e windows.system.object_manager[\"\\\\KnownDLLs\\\\KnownDLLPath\"].target\nu'C:\\\\WINDOWS\\\\System32'\n```\n\n### Scheduled Task\n\nThe ``windows.system.task_scheduler`` object allows to query and create scheduled task.\n\n**This part is still in developpement and the API may evolve**\n\n```python\n\u003e\u003e\u003e windows.system.task_scheduler\n\u003cTaskService at 0x4774670\u003e\n\u003e\u003e\u003e windows.system.task_scheduler.root\n\u003cTaskFolder \"\\\" at 0x4774710\u003e\n\u003e\u003e\u003e task = windows.system.task_scheduler.root.tasks[2]\n\u003e\u003e\u003e task\n\u003cTask \"DemoTask\" at 0x47748f0\u003e\n\u003e\u003e\u003e task.name\nu'DemoTask'\n# Explore task actions\n\u003e\u003e\u003e task.definition.actions[1]\n\u003cExecAction at 0x4774800\u003e\n\u003e\u003e\u003e task.definition.actions[1].path\nu'c:\\\\windows\\\\python\\\\python.exe'\n\u003e\u003e\u003e task.definition.actions[1].arguments\nu'yolo.py --test'\n```\n\n### Event logs\n\nThe ``windows.system.event_log`` object allows to query event logs.\n\n**This part is still in developpement and the API may evolve**\n\n```python\n\u003e\u003e\u003e windows.system.event_log\n\u003cwindows.winobject.event_log.EvtlogManager object at 0x04A78270\u003e\n# Find a channel by its name\n\u003e\u003e\u003e chan = windows.system.event_log[\"Microsoft-Windows-Windows Firewall With Advanced Security/Firewall\"]\n\u003e\u003e\u003e chan\n\u003cEvtChannel \"Microsoft-Windows-Windows Firewall With Advanced Security/Firewall\"\u003e\n# Open .evtx files\n\u003e\u003e\u003e windows.system.event_log[\"test.evtx\"]\n\u003cEvtFile \"test.evtx\"\u003e\n# Query a channel for all events\n\u003e\u003e\u003e chan.query().all()[:2]\n[\u003cEvtEvent id=\"2004\" time=\"2018-07-12 07:44:08.081504\"\u003e, \u003cEvtEvent id=\"2006\" time=\"2018-07-12 07:57:59.806938\"\u003e]\n# Query a channel for some ids\n\u003e\u003e\u003e chan.query(ids=2004).all()[:2]\n[\u003cEvtEvent id=\"2004\" time=\"2018-07-12 07:44:08.081504\"\u003e, \u003cEvtEvent id=\"2004\" time=\"2018-07-12 07:57:59.815156\"\u003e]\n# Query a channel via XPATH\n\u003e\u003e\u003e evt = chan.query(\"Event/EventData[Data='Netflix']\").all()[0]\n# Explore event information\n\u003e\u003e\u003e evt\n\u003cEvtEvent id=\"2006\" time=\"2018-07-17 10:32:39.160423\"\u003e\n\u003e\u003e\u003e evt.data\n{u'ModifyingUser': 69828304, u'RuleName': u'Netflix', u'ModifyingApplication': ...}\n```\n\n### ALPC-RPC\n\n#### ALPC\n\nClasses around **A**dvanced **L**ocal **P**rocedure **C**all (**ALPC**) syscalls allows to simply\nwrite client and server able to send **ALPC** messages.\n\n```python\n\u003e\u003e\u003e import windows.alpc\n# Test server juste reply to each message with \"REQUEST '{msg_data}' RECEIVED\"\n\u003e\u003e\u003e client = windows.alpc.AlpcClient(r\"\\RPC Control\\PythonForWindowsTESTPORT\")\n\u003e\u003e\u003e response = client.send_receive(\"Hello world !\")\n\u003e\u003e\u003e response\n\u003cwindows.alpc.AlpcMessage object at 0x04C0D5D0\u003e\n\u003e\u003e\u003e response.data\n\"REQUEST 'Hello world !' RECEIVED\"\n```\n\nFull client/server code for this example is available is the [ALPC samples][ONLINE_SAMPLE_ALPC] along with a more complex example.\n\n\n#### RPC\n\nAn RPC-Client based using **ALPC** communication is also integred\n\n```python\n# Server (port ALPC '\\RPC Control\\HelloRpc') offers:\n# Interface '41414141-4242-4343-4444-45464748494a' version 1.0\n#   Method 1 -\u003e int Add(int a, int b) -\u003e return a + b\n# This Test server is a real RPC Server using rpcrt4.dll and compiled with VS2015.\n\n\u003e\u003e\u003e import windows.rpc\n\u003e\u003e\u003e from windows.rpc import ndr\n\u003e\u003e\u003e client = windows.rpc.RPCClient(r\"\\RPC Control\\HelloRpc\")\n\u003e\u003e\u003e client\n\u003cwindows.rpc.client.RPCClient object at 0x0411E130\u003e\n\u003e\u003e\u003e iid = client.bind(\"41414141-4242-4343-4444-45464748494a\")\n\u003e\u003e\u003e ndr_params = ndr.make_parameters([ndr.NdrLong] * 2)\n# NDR pack + Make RPC call to method 1.\n\u003e\u003e\u003e resp = client.call(iid, 1, ndr_params.pack([41414141, 1010101]))\n# Unpack the NDR response\n\u003e\u003e\u003e result = ndr.NdrLong.unpack(ndr.NdrStream(resp))\n\u003e\u003e\u003e result\n42424242\n```\n\nA sample with the **U**ser **A**ccount **C**ontrol (**UAC**) and one with `lsasrv.dll` are available in the [RPC samples][ONLINE_SAMPLE_RPC].\n\n\n### Debugger\n\nPythonForWindows provides a standard debugger to debug other processes.\n\n```python\nimport windows\nimport windows.debug\nimport windows.test\nimport windows.native_exec.simple_x86 as x86\nimport windows.generated_def as gdef\n\nfrom windows.test import pop_proc_32\n\nclass MyDebugger(windows.debug.Debugger):\n    def on_exception(self, exception):\n        code = exception.ExceptionRecord.ExceptionCode\n        addr = exception.ExceptionRecord.ExceptionAddress\n        print(\"Got exception {0} at 0x{1:x}\".format(code, addr))\n        if code == gdef.EXCEPTION_ACCESS_VIOLATION:\n            print(\"Access Violation: kill target process\")\n            self.current_process.exit()\n\ncalc = windows.test.pop_proc_32(dwCreationFlags=gdef.DEBUG_PROCESS)\nd = MyDebugger(calc)\ncalc.execute(x86.assemble(\"int3; mov [0x42424242], EAX; ret\"))\nd.loop()\n\n## Ouput ##\nGot exception EXCEPTION_BREAKPOINT(0x80000003) at 0x77e13c7d\nGot exception EXCEPTION_BREAKPOINT(0x80000003) at 0x230000\nGot exception EXCEPTION_ACCESS_VIOLATION(0xc0000005) at 0x230001\nAccess Violation: kill target process\n```\n\nThe debugger handles\n\n* Standard breakpoint ``int3``\n* Hardware Execution breakpoint ``DrX``\n* Memory breakpoint ``virtual protect``\n\n\n#### LocalDebugger\n\nYou can also debug your own process (or debug a process by injection) via the LocalDebugger.\n\nThe LocalDebugger is an abstraction around Vectored Exception Handler (VEH)\n\n```python\nimport windows\nfrom windows.generated_def.winstructs import *\nimport windows.native_exec.simple_x86 as x86\n\nclass SingleSteppingDebugger(windows.debug.LocalDebugger):\n    SINGLE_STEP_COUNT = 4\n    def on_exception(self, exc):\n        code = self.get_exception_code()\n        context = self.get_exception_context()\n        print(\"EXCEPTION !!!! Got a {0} at 0x{1:x}\".format(code, context.pc))\n        self.SINGLE_STEP_COUNT -= 1\n        if self.SINGLE_STEP_COUNT:\n            return self.single_step()\n        return EXCEPTION_CONTINUE_EXECUTION\n\nclass RewriteBreakpoint(windows.debug.HXBreakpoint):\n    def trigger(self, dbg, exc):\n        context = dbg.get_exception_context()\n        print(\"GOT AN HXBP at 0x{0:x}\".format(context.pc))\n        # Rewrite the infinite loop with 2 nop\n        windows.current_process.write_memory(self.addr, \"\\x90\\x90\")\n        # Ask for a single stepping\n        return dbg.single_step()\n\n\nd = SingleSteppingDebugger()\n# Infinite loop + nop + ret\ncode = x86.assemble(\"label :begin; jmp :begin; nop; ret\")\nfunc = windows.native_exec.create_function(code, [PVOID])\nprint(\"Code addr = 0x{0:x}\".format(func.code_addr))\n# Create a thread that will infinite loop\nt = windows.current_process.create_thread(func.code_addr, 0)\n# Add a breakpoint on the infinite loop\nd.add_bp(RewriteBreakpoint(func.code_addr))\nt.wait()\nprint(\"Done!\")\n\n## Output ##\n\nCode addr = 0x6a0002\nGOT AN HXBP at 0x6a0002\nEXCEPTION !!!! Got a EXCEPTION_SINGLE_STEP(0x80000004) at 0x6a0003\nEXCEPTION !!!! Got a EXCEPTION_SINGLE_STEP(0x80000004) at 0x6a0004\nEXCEPTION !!!! Got a EXCEPTION_SINGLE_STEP(0x80000004) at 0x6a0005\nEXCEPTION !!!! Got a EXCEPTION_SINGLE_STEP(0x80000004) at 0x770c7c04\nDone!\n\n```\n\nThe local debugger handles\n\n* Standard breakpoint ``int3``\n* Hardware Execution breakpoint ``DrX``\n\n### Symbols\n\nClasses around the Symbols APIs of `dbghelp.dll` are also implemented and can be used independently of the Debugger.\nThe path of `dbghelp.dll` can also be given via the `PFW_DBGHELP_PATH` environment variable.\n\n\n```python\n# Python3\n\n\u003e\u003e\u003e from windows.debug import symbols\n\u003e\u003e\u003e # symbols.set_dbghelp_path(MY_DBGHELP_PATH)\n\u003e\u003e\u003e symbols.engine.options = 0 # Disable defered load\n\u003e\u003e\u003e sh = symbols.VirtualSymbolHandler()\n\u003e\u003e\u003e ntmod = sh.load_file(r\"c:\\windows\\system32\\ntdll.dll\", addr=0x420000)\n\u003e\u003e\u003e ntmod\n\u003cSymbolModule name=\"ntdll\" type=SymPdb pdb=\"ntdll.pdb\" addr=0x420000\u003e\n\u003e\u003e\u003e ntmod.name\n'ntdll'\n\u003e\u003e\u003e ntmod.path\n'c:\\\\windows\\\\system32\\\\ntdll.dll'\n\u003e\u003e\u003e ntmod.pdb\n'c:\\\\Symbols\\\\ntdll.pdb\\\\8D5D5ED5D5B8AA609A82600C14E3004D1\\\\ntdll.pdb'\n\u003e\u003e\u003e sym = sh[\"ntdll!LdrLoadDll\"]\n\u003e\u003e\u003e sym\n\u003cSymbolInfoW name=\"LdrLoadDll\" start=0x44a160 tag=SymTagFunction\u003e\n\u003e\u003e\u003e sym.fullname\n'ntdll!LdrLoadDll'\n\u003e\u003e\u003e hex(sym.addr)\n'0x44a160'\n\u003e\u003e\u003e sh.search(\"ntdll!*CreateFile\")\n[\u003cSymbolInfoW name=\"EtwpCreateFile\" start=0x47d9ec tag=SymTagFunction\u003e, \u003cSymbolInfoW name=\"EtwpCreateFile\" start=0x47d9ec tag=SymTagPublicSymbol\u003e, \u003cSymbolInfoW name=\"NtCreateFile\" start=0x4c03e0 tag=SymTagPublicSymbol\u003e, \u003cSymbolInfoW name=\"ZwCreateFile\" start=0x4c03e0 tag=SymTagPublicSymbol\u003e, \u003cSymbolInfoW name=\"__imp_NtCreateFile\" start=0x55cb70 tag=SymTagPublicSymbol\u003e]\n# Some types exploration\n\u003e\u003e\u003e peb = sh.get_type(\"ntdll!_PEB\")\n\u003e\u003e\u003e peb\n\u003cSymbolType name=\"_PEB\" tag=_SymTagEnum.SymTagUDT(0xb)\u003e\n\u003e\u003e\u003e peb.size\n2000\n\u003e\u003e\u003e peb.children[:3]\n[\u003cSymbolType name=\"InheritedAddressSpace\" tag=_SymTagEnum.SymTagData(0x7)\u003e, \u003cSymbolType name=\"ReadImageFileExecOptions\" tag=_SymTagEnum.SymTagData(0x7)\u003e, \u003cSymbolType name=\"BeingDebugged\" tag=_SymTagEnum.SymTagData(0x7)\u003e]\n\u003e\u003e\u003e peb.children[2].offset\n2\n```\n\n### Other stuff (see doc / samples)\n\n- Network\n- COM\n\n## Acknowledgments\n\n* clmntb for his initial work on ``windows.security``\n\n\n[LKD_GITHUB]: https://github.com/sogeti-esec-lab/LKD/\n[SAMPLE_DIR]: https://github.com/hakril/PythonForWindows/tree/master/samples\n[ONLINE_DOC]: https://hakril.github.io/PythonForWindows/\n[ONLINE_SAMPLE]: https://hakril.github.io/PythonForWindows/build/html/sample.html\n[ONLINE_SAMPLE_ALPC]: https://hakril.github.io/PythonForWindows/build/html/sample.html#windows-alpc\n[ONLINE_SAMPLE_RPC]: https://hakril.github.io/PythonForWindows/build/html/sample.html#windows-rpc\n[ONLINE_IATHOOK]: https://hakril.github.io/PythonForWindows/build/html/iat_hook.html","funding_links":[],"categories":["\u003ca id=\"b478e9a9a324c963da11437d18f04998\"\u003e\u003c/a\u003e工具"],"sub_categories":["\u003ca id=\"1afda3039b4ab9a3a1f60b179ccb3e76\"\u003e\u003c/a\u003e其他"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhakril%2Fpythonforwindows","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhakril%2Fpythonforwindows","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhakril%2Fpythonforwindows/lists"}