且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Delphi 2006或更早版本的可执行文件上启用DEP / NX和ASLR?

更新时间:2022-05-03 05:41:45

设置PE标志

您可以使用 {$ SetPEOptFlags $ 40} 设置DEP标志, {$ SetPEOptFlags $ 100} 设置ASLR标志。要使用 {$ SetPEOptFlags $ 140}

You can use {$SetPEOptFlags $40} to set the DEP flag, and {$SetPEOptFlags $100} to set the ASLR flag. To set both use {$SetPEOptFlags $140}.

如果您有一个版本的Delphi,必要的定义Windows.pas单元可以使用更加可读:

If you have a version of Delphi with the necessary definitions in the Windows.pas unit you can use the much more readable:

{$SetPEOptFlags IMAGE_DLLCHARACTERISTICS_NX_COMPAT or
    IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE }

通常,您可以在 $ SetPEOptFlags 中添加。 dpr文件。因此,您需要确保 Windows 在.dpr文件使用子句中,这些 IMAGE_XXX 常量可用。

Typically you include the $SetPEOptFlags setting in the .dpr file. And so you need to make sure that Windows is in the .dpr file uses clause for these IMAGE_XXX constants to be available.

在运行时设置DEP策略

对于不支持的版本基于PE标志的方法,您可以在应用程序的初始化早期调用此函数:

For versions that don't support PE flag based approaches you can call this function early in your app's initialization:

procedure EnableDEP;
const
  PROCESS_DEP_ENABLE: DWORD=$00000001;
var
  SetProcessDEPPolicy: function(dwFlags: DWORD): BOOL; stdcall;
begin
  SetProcessDEPPolicy := GetProcAddress(GetModuleHandle(kernel32), 
     'SetProcessDEPPolicy');
  if Assigned(SetProcessDEPPolicy) then begin
    //don't bother checking for errors since we don't need to know if it fails
    SetProcessDEPPolicy(PROCESS_DEP_ENABLE);
  end;
end;

这将适用于任何版本的Delphi。

This will work for any version of Delphi.

您不能在运行时设置ASLR标志,因为它会影响模块的加载方式。所以ASLR只能使用PE标志设置。

You cannot set the ASLR flag at runtime since it influences how the module is loaded. So ASLR can only be set using PE flags.

修改Delphi的旧版本的PE标志

旧版本的Delphi不支持 $ SetPEFlags $ SetPEOptFlags 。对于这样的版本,您需要使用外部工具来修改可执行的后期制作。当我最初写这个答案时,我认为MS工具链中的 EDITBIN 将会做这个工作。对于DEP,使用 / NXCOMPAT 选项就足够了。对于ASLR,您将需要使用不同的PE标志编辑器。我的网络搜索从cygwin透露了 peflags

Older versions of Delphi do not support $SetPEFlags and $SetPEOptFlags. For such versions you need to use an external tool to modify the executable post-build. When I originally wrote this answer I assumed that EDITBIN from the MS toolchain would do the job. For DEP it will suffice, using the /NXCOMPAT option. For ASLR you will need to use a different PE flag editor. My websearch revealed peflags from cygwin.

peflags --dynamicbase=true --nxcompat=true MyApp.exe

我确定有其他PE标志编辑选项可用。

I'm sure there are other PE flag editing options available.