Skip to content

Instantly share code, notes, and snippets.

@anthonyprintup
Created August 5, 2022 16:11
Show Gist options
  • Save anthonyprintup/a3d58d6a5c9e988d9e151ef75d4f3969 to your computer and use it in GitHub Desktop.
Save anthonyprintup/a3d58d6a5c9e988d9e151ef75d4f3969 to your computer and use it in GitHub Desktop.
API resolution using software breakpoints
#include <cstdio>
#include <cstdint>
#include <Windows.h>
constexpr auto instruction_bytes_to_skip {1z}; // sizeof(int 3)
constexpr auto first_magic_value {1234z}, second_magic_value {5678z}, magic_return_value {0xABCDz};
using HashType = std::uint64_t;
[[gnu::always_inline, gnu::pure, nodiscard]] std::uint64_t resolve_api(const HashType module_hash, const HashType api_hash) {
std::uint64_t first_register {}, second_register {}, return_value {};
asm volatile(
"mov %[first_register_arg], %[module_hash_arg];"
"mov %[second_register_arg], %[api_hash_arg];"
"int $3;"
: [first_register_arg] "=r" (first_register),
[second_register_arg] "=r" (second_register),
"=a" (return_value) // force the lvalue "return_value" to be stored in rax
: [module_hash_arg] "rg" (module_hash), [api_hash_arg] "rg" (api_hash));
return return_value;
}
LONG unhandled_exception_filter(const PEXCEPTION_POINTERS exception_info) { // NOLINT(misc-misplaced-const)
if (exception_info->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT &&
(exception_info->ContextRecord->Rcx == first_magic_value || exception_info->ContextRecord->Rdx == first_magic_value) &&
(exception_info->ContextRecord->Rcx == second_magic_value || exception_info->ContextRecord->Rdx == second_magic_value)) {
exception_info->ContextRecord->Rax = magic_return_value;
exception_info->ContextRecord->Rip += instruction_bytes_to_skip;
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
int main() {
SetUnhandledExceptionFilter(unhandled_exception_filter);
const auto api_address = resolve_api(first_magic_value, second_magic_value);
std::printf("api_address=%llx\n", api_address);
std::printf("magic_return_value=%llx\n", magic_return_value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment