Skip to content

Commit 45e73c5

Browse files
ivonastojanovicgodlygeek
authored andcommitted
Prevent attaching to a process with a different architecture
Ensure that the caller and target processes have matching architectures before proceeding. Attaching to a 64-bit process from a 32-bit process will fail when using CreateToolhelp32Snapshot, and attempting to attach to a 32-bit process from a 64-bit process may cause issues during PE file parsing. To avoid potential errors abort the operation if the architectures differ.
1 parent 075ca65 commit 45e73c5

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Python/remote_debugging.c

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,28 @@ search_map_for_section(proc_handle_t *handle, const char* secname, const char* m
422422

423423
#ifdef MS_WINDOWS
424424

425+
static BOOL is_process64Bit(HANDLE hProcess) {
426+
BOOL isWow64 = FALSE;
427+
if (IsWow64Process(hProcess, &isWow64)) {
428+
return !isWow64;
429+
}
430+
else {
431+
PyErr_SetString(PyExc_RuntimeError, "Failed to determine the architecture of the process.");
432+
return FALSE;
433+
}
434+
}
435+
436+
static
437+
BOOL is_current_process64Bit() {
438+
#if defined(_WIN64)
439+
return TRUE;
440+
#elif defined(_WIN32)
441+
return is_process64Bit(GetCurrentProcess());
442+
#else
443+
return FALSE;
444+
#endif
445+
}
446+
425447
static void* analyze_pe(const wchar_t* mod_path, BYTE* remote_base, const char* secname) {
426448
HANDLE hFile = CreateFileW(mod_path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
427449
if (hFile == INVALID_HANDLE_VALUE) {
@@ -482,6 +504,16 @@ static void* analyze_pe(const wchar_t* mod_path, BYTE* remote_base, const char*
482504

483505
static uintptr_t
484506
search_windows_map_for_section(proc_handle_t* handle, const char* secname, const wchar_t* substr) {
507+
// Check if the architecture of the current process matches the target process
508+
BOOL currentProcess64Bit = is_current_process64Bit();
509+
BOOL targetProcess64Bit = is_process64Bit(handle->hProcess);
510+
511+
// If the architectures of the current and target processes differ, abort
512+
if (currentProcess64Bit != targetProcess64Bit) {
513+
PyErr_SetString(PyExc_RuntimeError, "Bitness mismatch between current process and target process.");
514+
return 0;
515+
}
516+
485517
HANDLE hProcSnap;
486518
do {
487519
hProcSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, handle->pid);

0 commit comments

Comments
 (0)