| 1 | #include "scanner.h" |
| 2 | |
| 3 | std::uint8_t* sig(const HMODULE module, const std::string& byte_array) { |
| 4 | if (!module) |
| 5 | return nullptr; |
| 6 | |
| 7 | static const auto pattern_to_byte = [&](std::string pattern) { |
| 8 | std::vector<int> bytes{}; |
| 9 | const auto start = const_cast<char*>(pattern.c_str()); |
| 10 | const auto end = const_cast<char*>(pattern.c_str()) + pattern.length(); |
| 11 | |
| 12 | for (auto current = start; current < end; ++current) { |
| 13 | if (*current == '?') { |
| 14 | ++current; |
| 15 | |
| 16 | if (*current == '?') |
| 17 | ++current; |
| 18 | |
| 19 | bytes.push_back(-1); |
| 20 | } |
| 21 | else { |
| 22 | bytes.push_back(std::strtoul(current, ¤t, 16)); |
| 23 | } |
| 24 | } |
| 25 | return bytes; |
| 26 | }; |
| 27 | |
| 28 | const auto dos_header = reinterpret_cast<PIMAGE_DOS_HEADER>(module); |
| 29 | const auto nt_headers = |
| 30 | reinterpret_cast<PIMAGE_NT_HEADERS>(reinterpret_cast<std::uint8_t*>(module) + dos_header->e_lfanew); |
| 31 | |
| 32 | const auto size_of_image = nt_headers->OptionalHeader.SizeOfImage; |
| 33 | const auto pattern_bytes = pattern_to_byte(byte_array); |
| 34 | const auto scan_bytes = reinterpret_cast<std::uint8_t*>(module); |
| 35 | |
| 36 | const auto pattern_size = pattern_bytes.size(); |
| 37 | const auto pattern_data = pattern_bytes.data(); |
| 38 | |
| 39 | for (auto i = 0ul; i < size_of_image - pattern_size; ++i) { |
| 40 | bool found = true; |
| 41 | |
| 42 | for (auto j = 0ul; j < pattern_size; ++j) { |
| 43 | if (scan_bytes[i + j] != pattern_data[j] && pattern_data[j] != -1) { |
| 44 | found = false; |
| 45 | break; |
| 46 | } |
| 47 | } |
| 48 | if (found) |
| 49 | return &scan_bytes[i]; |
| 50 | } |
| 51 | |
| 52 | return nullptr; |
| 53 | } |