예제 #1
0
        static void ProtectionSafeMemoryCopy(IntPtr dest, IntPtr source, int count)
        {
            // UIntPtr = size_t
            var bufferSize = new UIntPtr((uint)count);

            Enums.VirtualProtectionType oldProtection, temp;

            // unprotect memory to copy buffer
            if (!NativeImport.VirtualProtect(dest, bufferSize, Enums.VirtualProtectionType.ExecuteReadWrite, out oldProtection))
            {
                throw new Exception("Failed to unprotect memory.");
            }

            byte *pDest = (byte *)dest;
            byte *pSrc  = (byte *)source;

            // copy buffer to address
            for (int i = 0; i < count; i++)
            {
                *(pDest + i) = *(pSrc + i);
            }

            // protect back
            if (!NativeImport.VirtualProtect(dest, bufferSize, oldProtection, out temp))
            {
                throw new Exception("Failed to protect memory.");
            }
        }
예제 #2
0
        public static void MemCpy(nint dest, nint source, int count)
        {
            var bufferSize = new UIntPtr((uint)count);
            NativeImport.NativeStructs.VirtualProtectionType oldProtection, temp;

            //Unprotect memory to copy buffer
            if (!NativeImport.VirtualProtect(dest, bufferSize, NativeImport.NativeStructs.VirtualProtectionType.ExecuteReadWrite, out oldProtection))
                throw new Exception($"Failed to change protection to ExecuteReadWrite at: 0x{dest:X}");

            byte* pDest = (byte*)dest;
            byte* pSrc = (byte*)source;

            // copy buffer to address
            for (int i = 0; i < count; i++)
                *(pDest + i) = *(pSrc + i);

            //Protect back
            if (!NativeImport.VirtualProtect(dest, bufferSize, oldProtection, out temp))
                throw new Exception($"Failed to change protection back to {oldProtection} at: 0x{dest:X}");
        }
예제 #3
0
        private void BuildHook(nint gatewayStubAddr)
        {
            NativeImport.NativeStructs.VirtualProtectionType oldProt;

            if (!NativeImport.VirtualProtect(TargetFunctionAddress, (UIntPtr)5, NativeImport.NativeStructs.VirtualProtectionType.ExecuteReadWrite, out oldProt))
            {
                throw new Exception($"Failed to change page protection to ExecuteReadWrite at: 0x{TargetFunctionAddress:X}");
            }

            RelativeJmpInstructions = new byte[]
            {
                0xE9,                              //jmp [DWORD]
                0x0, 0x0, 0x0, 0x0                 // DWORD
            };

            fixed(byte *allocInstructions = &RelativeJmpInstructions[0])
            {
                nint relAddr = gatewayStubAddr - (TargetFunctionAddress + RelativeJmpInstructions.Length);

                *(nint *)((nint)allocInstructions + 1) = relAddr;
            }

            Console.WriteLine("Successfully built X64 Hook");
        }