kdmapper-1803-20H2/kdmapper/utils.cpp

68 lines
2.0 KiB
C++
Raw Permalink Normal View History

2020-05-30 21:26:01 +08:00
#include "utils.hpp"
bool utils::ReadFileToMemory(const std::string& file_path, std::vector<uint8_t>* out_buffer)
{
std::ifstream file_ifstream(file_path, std::ios::binary);
if (!file_ifstream)
return false;
out_buffer->assign((std::istreambuf_iterator<char>(file_ifstream)), std::istreambuf_iterator<char>());
file_ifstream.close();
return true;
}
bool utils::CreateFileFromMemory(const std::string& desired_file_path, const char* address, size_t size)
{
std::ofstream file_ofstream(desired_file_path.c_str(), std::ios_base::out | std::ios_base::binary);
if (!file_ofstream.write(address, size))
{
file_ofstream.close();
return false;
}
file_ofstream.close();
return true;
}
uint64_t utils::GetKernelModuleAddress(const std::string& module_name)
{
void* buffer = nullptr;
DWORD buffer_size = 0;
NTSTATUS status = NtQuerySystemInformation(static_cast<SYSTEM_INFORMATION_CLASS>(nt::SystemModuleInformation), buffer, buffer_size, &buffer_size);
while (status == nt::STATUS_INFO_LENGTH_MISMATCH)
{
VirtualFree(buffer, 0, MEM_RELEASE);
buffer = VirtualAlloc(nullptr, buffer_size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
status = NtQuerySystemInformation(static_cast<SYSTEM_INFORMATION_CLASS>(nt::SystemModuleInformation), buffer, buffer_size, &buffer_size);
}
if (!NT_SUCCESS(status))
{
VirtualFree(buffer, 0, MEM_RELEASE);
return 0;
}
const auto modules = static_cast<nt::PRTL_PROCESS_MODULES>(buffer);
for (auto i = 0u; i < modules->NumberOfModules; ++i)
{
const std::string current_module_name = std::string(reinterpret_cast<char*>(modules->Modules[i].FullPathName) + modules->Modules[i].OffsetToFileName);
if (!_stricmp(current_module_name.c_str(), module_name.c_str()))
{
const uint64_t result = reinterpret_cast<uint64_t>(modules->Modules[i].ImageBase);
VirtualFree(buffer, 0, MEM_RELEASE);
return result;
}
}
VirtualFree(buffer, 0, MEM_RELEASE);
return 0;
}