且构网

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

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

更新时间:2021-07-25 04:43:34

设置 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}.

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

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 }

通常在 .dpr 文件中包含 $SetPEOptFlags 设置.因此,您需要确保 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 标志,因为它会影响模块的加载方式.所以只能使用 PE 标志设置 ASLR.

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.