·10 min read
Building a Windows memory scanner in Python with ctypes and NumPy
Unfair is a memory scanner for Windows in a single Python file of about 870 lines. It attaches to a process, searches its memory for a value, and narrows the candidates by rescanning after the value changes. I wrote it to understand how this class of tool works, and it is useful for debugging programs you wrote or processes you own. The repository has a single commit and one release, so this post is about design decisions I can show in the code, not a bug-fix history.
- Role
- Creator and sole developer
- Period
- Sep 2026 to Sep 2026
- Status
- Released v1.0.0
- Stack
- Python, ctypes, NumPy, Flask, PyInstaller
The challenge
The Win32 calls are not the hard part. OpenProcess, VirtualQueryEx and ReadProcessMemory are a few lines each. The hard parts are the ones around them. A first scan for a common number returns thousands of hits, so the tool is only useful if rescans collapse them quickly. A 64-bit address space is huge, so reading all of it is not an option. A tool that can write into another process is dangerous if anything else can reach it. And a tool that needs administrator rights is awkward to hand to someone who does not have Python installed.
It is also not for online games. Anti-cheat systems watch for exactly these API calls, and using a tool like this against someone else's software breaks their terms and can get an account banned. The README says the same, and the practice target in the repo, fake_game.py, is a tiny process of my own.
My responsibility
I am the sole author. The commit and the release show me owning:
- The scanner core in
unfair.py: thectypesbindings, region walking, first scans, rescans, writes and the freeze loop. - The interactive shell and the Flask web UI in
web.py. - The test target
fake_game.pyand two end-to-end tests,test_unfair.pyandtest_web.py. - The packaging:
launcher.py,unfair.spec, a generated icon, and the GitHub release withunfair.exeattached.
How I approached it
Talking to Win32 through ctypes
There is no extension module. ctypes.WinDLL("kernel32", use_last_error=True) is enough, as long as every signature is declared. Skipping argtypes and restype works until a 64-bit pointer gets truncated to a 32-bit int.
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
k32.ReadProcessMemory.argtypes = [wt.HANDLE, LPVOID, LPVOID, SIZE_T,
ctypes.POINTER(SIZE_T)]
k32.ReadProcessMemory.restype = wt.BOOL
k32.VirtualQueryEx.argtypes = [wt.HANDLE, LPVOID,
ctypes.POINTER(MEMORY_BASIC_INFORMATION), SIZE_T]
k32.VirtualQueryEx.restype = SIZE_TOpenProcess fails with error 5 when the target needs elevation, so the code turns that into a hint to run as Administrator. enable_debug_privilege() also adjusts the process token to enable SeDebugPrivilege, which the packaged exe calls at startup.
Do not scan everything
VirtualQueryEx walks the address space region by region, and the scanner keeps only what is worth reading:
if (mbi.State == MEM_COMMIT
and not (mbi.Protect & PAGE_GUARD)
and not (mbi.Protect & PAGE_NOACCESS)
and (mbi.Protect & WRITABLE_PROTECTIONS)):
if mbi.Type in (MEM_PRIVATE, MEM_IMAGE) or (
self.include_mapped and mbi.Type == MEM_MAPPED):
out.append(Region(base, size, mbi.Protect, mbi.Type))Committed, not guarded, writable, and private or image memory. Mapped files are off by default. A value that changes at runtime lives in writable memory, so this shrinks the work a lot. Regions are read in 4 MB chunks (CHUNK), and by default only addresses aligned to the value size are checked, which the README notes is much faster.
The first scan and why rescans work
For an integer, the first scan packs the value with struct.pack and loops bytes.find, keeping hits where index % size == 0. For floats, or when a tolerance is given, NumPy takes over:
arr = np.frombuffer(buf[:usable], dtype=npname)
idx = np.nonzero(np.abs(arr - value) <= tolerance)[0]Floats need a tolerance because a number drawn on screen as 92.5 is rarely stored as exactly 92.5. Searching for 100 returns thousands of addresses because 100 is a common number. What separates the real one is behavior: after the program changes it to 99, I re-read only the survivors and keep those that now hold 99.
scan 100
next 99
next 98
next_scan is a predicate filter, a small lambda per operation over the current and previous value:
if op == "dec_by":
return lambda cur, prev: prev - cur == operandRe-reading thousands of scattered addresses with one ReadProcessMemory each would be slow, so _read_many sorts the addresses and merges any within CLUSTER_GAP (64 KB) into one read, then unpacks values with struct.unpack_from.
The scan that wanted hundreds of megabytes
Sometimes nothing on screen shows the number, like a health bar. Then the first scan is an unknown-value scan: snapshot every eligible region, and filter by how values moved (changed, unchanged, inc, dec). This is where NumPy earns its place: two buffers become two arrays and a comparison is one expression.
a_old = np.frombuffer(old[:usable], dtype=npname)
a_new = np.frombuffer(new[:usable], dtype=npname)
mask = a_new < a_old # "dec"The cost is memory: a snapshot is a full copy of every region, which the README warns can reach hundreds of MB. I did not accept that cost forever. Once the survivors drop to two million or fewer, the code drops the snapshot and switches back to the cheap address-list mode:
if len(kept) <= 2_000_000:
...
self.snapshot = None # small enough: switch to address-list mode| First scan | When | Cost |
|---|---|---|
| Byte search | known integer: struct.pack and bytes.find, aligned hits only | cheap |
| NumPy vectorized | float, or a tolerance given: np.frombuffer and a comparison | needs NumPy |
| Unknown value | nothing on screen shows the number: snapshot every eligible region | full copy of each region, up to hundreds of MB |
A tool that can write to any process, behind a web page
web.py wraps the scanner in Flask. Scans run on a worker thread with a progress callback, and a busy flag makes a second request return 409 instead of starting a competing scan. Values that changed since the last refresh turn amber, which makes the unknown-value idea visible.
The part I care about most is the security posture. Every endpoint is unauthenticated, and the write and freeze endpoints can modify any process you can open. So the server binds to 127.0.0.1 and each request is checked:
@app.before_request
def local_only():
if request.remote_addr not in ("127.0.0.1", "::1"):
return jsonify(error="local requests only"), 403I did not leave that as a comment. test_web.py drives the HTTP API end to end, checks that garbage input returns 400 and not 500, and asserts that a non-local request gets 403. The README warns never to put the UI behind a tunnel or reverse proxy.
Shipping an elevated tool as one exe
Handing someone a Python tool that needs admin rights means asking them to install Python, flask and numpy. So the release is unfair.exe, built from unfair.spec with PyInstaller. The spec sets uac_admin=True, which embeds an admin manifest so Windows asks for elevation on double-click, and launcher.py is the entry point. It resolves the template folder inside the PyInstaller bundle (sys._MEIPASS), picks port 5000 or the next free port, opens the browser once the server answers, and serves on localhost only.
def free_port(preferred=5000):
for port in (preferred, 0):
with socket.socket() as sock:
try:
sock.bind(("127.0.0.1", port))The README records two things I learned while building it. Build in a clean virtualenv, because PyInstaller walks whatever is installed and a global site-packages with two Qt bindings aborts the build. And the exe is unsigned, so SmartScreen shows "Windows protected your PC" on first run.
Testing without a target
Testing something that reads another process's memory needs a safe target. fake_game.py holds an ammo counter and a health float as ctypes values, plus 64 decoy copies of 100 so the first scan is not trivially unique. test_unfair.py drives first scan, two narrowing rescans, a decrease filter, a write, a freeze, a float scan and an unknown-value scan, asserting the true address survives each step.
lines in one Python file
read chunk per region
decoy copies of 100 in the test target
survivors before the cheaper list mode
Project journey
The history is one commit, so the timeline is the shape of the first release rather than a sequence of fixes. Everything below landed in 6620371 and the v1.0.0 release.
Sep 2026
Scanner core
6620371: unfair.py with ctypes bindings, region walking, scans and freeze
Sep 2026
Web UI
web.py with worker thread, local-only guard and templates
Sep 2026
Tests and target
fake_game.py, test_unfair.py and test_web.py
Sep 2026
Packaging
launcher.py, unfair.spec and a generated icon
Sep 2026
v1.0.0
GitHub release with unfair.exe attached
Beyond the launch
There is nothing after v1.0.0 in the history, and I will not pretend otherwise. What I can point to are the limits the README states openly: addresses are not stable across restarts because there is no pointer scanning, values guarded by anti-tamper checks will revert or trip a detection, unknown-value snapshots can hold hundreds of MB, and the exe is unsigned. These are the next places I would work.
The outcome
Unfair exists as a public repository with a v1.0.0 release and a downloadable unfair.exe. It has a CLI shell, a local web UI, a practice target and two end-to-end tests. What I took from building it:
- Declare every
ctypessignature, always. - Filter the address space before reading it.
- A single scan means little. The information is in how values change between scans.
- If a tool can write into other processes, the guard belongs in code and in a test, not only in the README.
Evidence
- Repository: ddatunashvili/unfair, commit
6620371 - Release: v1.0.0 with
unfair.exe - Files relied on:
unfair.py,web.py,launcher.py,unfair.spec,fake_game.py,test_unfair.py,test_web.py,README.md - Microsoft Win32 documentation for OpenProcess, ReadProcessMemory and VirtualQueryEx, and the NumPy documentation
Not verified: I did not benchmark scan speed or memory use for this post. The session with 5,827, 3 and 1 candidates is the README's example, not a fresh measurement, and so are the "much faster" note on aligned scans and the "hundreds of MB" warning for snapshots. I did not run the packaged exe for this post.
#python#ctypes#windows#numpy
Keep reading
Have a project in mind?