Experience
Projects
My Stack
Case studies
Contact me
Open my CV

·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: the ctypes bindings, 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.py and two end-to-end tests, test_unfair.py and test_web.py.
  • The packaging: launcher.py, unfair.spec, a generated icon, and the GitHub release with unfair.exe attached.

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.

python
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_T

OpenProcess 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:

python
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:

python
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.

$ attach mygame.exe
attached to mygame.exe (pid 12345, 64-bit), type = i32
$ scan 100
# ammo reads 100 on screen
5,827 candidate(s) in 2.1s
$ next 99
# fire a shot, ammo is now 99
3 candidate(s) left
$ next 98
1 candidate(s) left
Figure 1. The README's example session: three scans take an ammo counter from thousands of candidates to one address.

scan 100

0candidates

next 99

0candidates

next 98

0candidates
Figure 2. Each rescan throws away almost every candidate that did not follow the value.

next_scan is a predicate filter, a small lambda per operation over the current and previous value:

python
if op == "dec_by":
    return lambda cur, prev: prev - cur == operand

Re-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.

handleregionseligiblehitsrescanre-readsOpenProcessaccess maskVirtualQueryExwalks the regionsRegion filtercommitted, writableFirst scanvalue or snapshotCandidatesaddress listnext_scanpredicate filter_read_manymerged reads
Figure 3. A scan walks the committed writable regions, builds a candidate list, and each rescan re-reads only the survivors.

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.

python
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:

python
if len(kept) <= 2_000_000:
    ...
    self.snapshot = None   # small enough: switch to address-list mode
Note. Addresses do not survive a restart of the target. Unfair does no pointer scanning, so you rescan each run. That is a known limit listed in the README, not a bug.
First scanWhenCost
Byte searchknown integer: struct.pack and bytes.find, aligned hits onlycheap
NumPy vectorizedfloat, or a tolerance given: np.frombuffer and a comparisonneeds NumPy
Unknown valuenothing on screen shows the number: snapshot every eligible regionfull 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:

python
@app.before_request
def local_only():
    if request.remote_addr not in ("127.0.0.1", "::1"):
        return jsonify(error="local requests only"), 403

I 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.

requestevery requestscan jobrunsprogressweb.pyFlask on 127.0.0.1local_onlyrejects other IPsWorker threadprogress callbackScannerunfair.pyBrowser pagelocal UI
Figure 4. The web UI runs scans on a worker thread behind a localhost-only check, so the page stays responsive and nothing outside the machine can reach it.

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.

python
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.

0

lines in one Python file

0 MB

read chunk per region

0

decoy copies of 100 in the test target

0

survivors before the cheaper list mode

Figure 5. The sizes and limits that shape the scanner.

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.

  1. Sep 2026

    Scanner core

    6620371: unfair.py with ctypes bindings, region walking, scans and freeze

  2. Sep 2026

    Web UI

    web.py with worker thread, local-only guard and templates

  3. Sep 2026

    Tests and target

    fake_game.py, test_unfair.py and test_web.py

  4. Sep 2026

    Packaging

    launcher.py, unfair.spec and a generated icon

  5. Sep 2026

    v1.0.0

    GitHub release with unfair.exe attached

Figure 6. A single commit and one release, so this is the shape of v1.0.0, not a long history.

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 ctypes signature, 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

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?