How to solve mysterious registry ghost problem

Have you ever encountered a situation where you can clearly see and edit a registry key using Windows’ regedit.exe, but when trying to access the same key via code, it fails with error code 2 (File not found)? This frustrating “registry ghost” issue can appear when working with Windows API, particularly when dealing with 32-bit and 64-bit applications.

0x1 The issue

Let’s say you wanna access registry HKEY_LOCAL_MACHINE\SOFTWARE\xxx, and you can see it clearly with your beloved regedit.exe, it is right there. But when you try following code, something happened.

with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\xxx',0, winreg.KEY_READ) as key:
    # Query the value of the specified key
    val, regtype = winreg.QueryValueEx(key, 'aaa')

Your code won’t work! It returns error code 2 (File not found)!

How is it possible? The registry folder is right there!

0x2 The root cause

Upon closer inspection using a monitoring tool like procmon.exe, you might realize that your code is actually trying to access HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\xxx instead of the intended 64-bit path. This happens because the code was running in a 32-bit environment on a 64-bit machine. When using a 32-bit Python interpreter, the system automatically redirects registry calls to Wow6432Node, which mirrors the 32-bit view of the registry.

WTF?

So I forgot that I used an old 32bit python, lmao

0x3 The fix

Add a flag (KEY_WOW64_64KEY) to allow registry access 64bit keys in 32 bit program.

with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\xxx', 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY) as key:
    # Query the value of the specified key
    value, regtype = winreg.QueryValueEx(key, 'aaa')

Problem solved!