Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- BOOL
- NTAPI
- WriteProcessMemory(IN HANDLE hProcess,
- IN LPVOID lpBaseAddress,
- IN LPCVOID lpBuffer,
- IN SIZE_T nSize,
- OUT SIZE_T *lpNumberOfBytesWritten)
- {
- NTSTATUS Status;
- ULONG OldValue;
- SIZE_T RegionSize;
- PVOID Base;
- BOOLEAN UnProtect;
- /* Set parameters for protect call */
- RegionSize = nSize;
- Base = lpBaseAddress;
- /* Check the current status */
- Status = NtProtectVirtualMemory(hProcess,
- &Base,
- &RegionSize,
- PAGE_EXECUTE_READWRITE,
- &OldValue);
- if (NT_SUCCESS(Status))
- {
- /* Check if we are unprotecting */
- UnProtect = OldValue & (PAGE_READWRITE |
- PAGE_WRITECOPY |
- PAGE_EXECUTE_READWRITE |
- PAGE_EXECUTE_WRITECOPY) ? FALSE : TRUE;
- if (!UnProtect)
- {
- /* Set the new protection */
- Status = NtProtectVirtualMemory(hProcess,
- &Base,
- &RegionSize,
- OldValue,
- &OldValue);
- /* Write the memory */
- Status = NtWriteVirtualMemory(hProcess,
- lpBaseAddress,
- (LPVOID)lpBuffer,
- nSize,
- &nSize);
- /* In Win32, the parameter is optional, so handle this case */
- if (lpNumberOfBytesWritten) *lpNumberOfBytesWritten = nSize;
- if (!NT_SUCCESS(Status))
- {
- /* We failed */
- BaseSetLastNTError(Status);
- return FALSE;
- }
- /* Flush the ITLB */
- NtFlushInstructionCache(hProcess, lpBaseAddress, nSize);
- return TRUE;
- }
- else
- {
- /* Check if we were read only */
- if (OldValue & (PAGE_NOACCESS | PAGE_READONLY))
- {
- /* Restore protection and fail */
- NtProtectVirtualMemory(hProcess,
- &Base,
- &RegionSize,
- OldValue,
- &OldValue);
- BaseSetLastNTError(STATUS_ACCESS_VIOLATION);
- /* Note: This is what Windows returns and code depends on it */
- return STATUS_ACCESS_VIOLATION;
- }
- /* Otherwise, do the write */
- Status = NtWriteVirtualMemory(hProcess,
- lpBaseAddress,
- (LPVOID)lpBuffer,
- nSize,
- &nSize);
- /* In Win32, the parameter is optional, so handle this case */
- if (lpNumberOfBytesWritten) *lpNumberOfBytesWritten = nSize;
- /* And restore the protection */
- NtProtectVirtualMemory(hProcess,
- &Base,
- &RegionSize,
- OldValue,
- &OldValue);
- if (!NT_SUCCESS(Status))
- {
- /* We failed */
- BaseSetLastNTError(STATUS_ACCESS_VIOLATION);
- /* Note: This is what Windows returns and code depends on it */
- return STATUS_ACCESS_VIOLATION;
- }
- /* Flush the ITLB */
- NtFlushInstructionCache(hProcess, lpBaseAddress, nSize);
- return TRUE;
- }
- }
- else
- {
- /* We failed */
- BaseSetLastNTError(Status);
- return FALSE;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement