Skip to content

Commit 05f485e

Browse files
committed
added per page protection
1 parent e4ac0ff commit 05f485e

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

source/yail.cpp

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ namespace
8383
decltype(&LoadLibraryA) fn_load_library_a;
8484
decltype(&GetProcAddress) fn_get_proc_address;
8585
decltype(&RtlAddFunctionTable) fn_rtl_add_function_table;
86+
decltype(&VirtualProtect) fn_virtual_protect;
8687
void* fn_ldrp_handle_tls_data;
8788
void* fn_rtl_insert_inverted_function_table;
8889
};
@@ -187,6 +188,48 @@ namespace
187188
}
188189
}
189190

191+
// --- Apply per-section memory protections ---
192+
{
193+
auto* section = reinterpret_cast<IMAGE_SECTION_HEADER*>(
194+
reinterpret_cast<std::uint8_t*>(&nt_headers->OptionalHeader) + nt_headers->FileHeader.SizeOfOptionalHeader);
195+
196+
for (std::uint16_t i = 0; i < nt_headers->FileHeader.NumberOfSections; i++, section++)
197+
{
198+
if (!section->Misc.VirtualSize)
199+
continue;
200+
201+
DWORD protect = PAGE_NOACCESS;
202+
const DWORD sc = section->Characteristics;
203+
204+
if (sc & IMAGE_SCN_MEM_EXECUTE)
205+
{
206+
if (sc & IMAGE_SCN_MEM_WRITE)
207+
protect = PAGE_EXECUTE_READWRITE;
208+
else if (sc & IMAGE_SCN_MEM_READ)
209+
protect = PAGE_EXECUTE_READ;
210+
else
211+
protect = PAGE_EXECUTE;
212+
}
213+
else if (sc & IMAGE_SCN_MEM_WRITE)
214+
{
215+
if (sc & IMAGE_SCN_MEM_READ)
216+
protect = PAGE_READWRITE;
217+
else
218+
protect = PAGE_WRITECOPY;
219+
}
220+
else if (sc & IMAGE_SCN_MEM_READ)
221+
{
222+
protect = PAGE_READONLY;
223+
}
224+
225+
if (sc & IMAGE_SCN_MEM_NOT_CACHED)
226+
protect |= PAGE_NOCACHE;
227+
228+
DWORD old_protect;
229+
data->fn_virtual_protect(base + section->VirtualAddress, section->Misc.VirtualSize, protect, &old_protect);
230+
}
231+
}
232+
190233
// --- Call entry point ---
191234
if (nt_headers->OptionalHeader.AddressOfEntryPoint)
192235
{
@@ -366,6 +409,7 @@ namespace yail
366409
loader_data.fn_load_library_a = LoadLibraryA;
367410
loader_data.fn_get_proc_address = GetProcAddress;
368411
loader_data.fn_rtl_add_function_table = RtlAddFunctionTable;
412+
loader_data.fn_virtual_protect = VirtualProtect;
369413
const auto tls_fn = find_ldrp_handle_tls_data();
370414
if (!tls_fn)
371415
{

0 commit comments

Comments
 (0)