Search code examples
c#.netsecuritydep

Enforce Data Execution Prevention (DEP) in C# app


I have a C# app thats going to run with admin privileges. I want to force DEP for it. Either set DEP On for the process or kill the app if DEP is disabled.

But I've failed in both. My code is:

private static void CheckDEP()
{
    var dep = SetProcessDEPPolicy(3);

    var handle = Process.GetCurrentProcess().Handle;
    var res = GetProcessDEPPolicy(handle, out var flags, out var permanent);
}

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetProcessDEPPolicy(uint dwFlags);

[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
static extern bool GetProcessDEPPolicy(IntPtr hProcess, out uint lpFlags, out bool lpPermanent);

Calling the function SetProcessDEPPolicy(3) always fails with error 50 (documentation says that it should return this error only when it's called from 64bit process, but this is not the case).

And I probably have some bug in GetProcessDEPPolicy, because the call fails with error 87 (parameter is incorrect). Maybe the Handle is wrong?


Solution

  • So, the solution is to change the build configuration in Configuration Manager from AnyCPU to x86. Now both methods work as expected.

    The errors are the same for AnyCPU as for x64 (where DEP is enforced by default and these methods should return the mentioned errors).