From 47bc61d69dd76592295214ba6e29c94c90e60a95 Mon Sep 17 00:00:00 2001 From: david Date: Sat, 4 Sep 2010 04:52:23 +0000 Subject: [PATCH] Restrict the search path for DLLs to prevent DLL hijacking. If the SetDllDirectory function is available, as it is on Windows XP SP1 and later, use it to remove the current directory from the DLL search path. If the function is not available, call SetCurrentDirectory to the directory containing the executable. I believe that such an attack is not currently possible against Nmap, because it doesn't register any file type associations. This protects us in case such associations are added in the future. --- mswin32/winfix.cc | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/mswin32/winfix.cc b/mswin32/winfix.cc index 2bd1935eb..872b5f10d 100644 --- a/mswin32/winfix.cc +++ b/mswin32/winfix.cc @@ -189,6 +189,30 @@ quit_error: return false; } +/* Restrict where we're willing to load DLLs from to prevent DLL hijacking. */ +static void init_dll_path() +{ + BOOL (WINAPI *SetDllDirectory)(LPCTSTR); + + SetDllDirectory = (BOOL (WINAPI *)(LPCTSTR)) GetProcAddress(GetModuleHandle("kernel32.dll"), "SetDllDirectoryA"); + if (SetDllDirectory == NULL) { + char nmapdir[MAX_PATH]; + + /* SetDllDirectory is not available before XP SP1. Instead, set + the current directory to the home of the executable (instead + of where a malicious DLL may be). */ + if (GetModuleFileName(NULL, nmapdir, sizeof(nmapdir)) == 0 || + GetLastError() == ERROR_INSUFFICIENT_BUFFER) { + pfatal("Error in GetModuleFileName"); + } + if (SetCurrentDirectory(nmapdir)) + pfatal("Error in SetCurrentDirectory"); + } else { + if (SetDllDirectory("") == 0) + pfatal("Error in SetDllDirectory(\"\")"); + } +} + /* Requires that win_pre_init() has already been called, also that options processing has been done so that o.debugging is available */ @@ -202,6 +226,7 @@ void win_init() int i; int numipsleft; + init_dll_path(); ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if(!GetVersionEx((LPOSVERSIONINFO)&ver))