1 /* DllSecur.c -- DLL loading security
2 2016-10-04 : Igor Pavlov : Public domain */
3 
4 #include "Precomp.h"
5 
6 #ifdef _WIN32
7 
8 #include <windows.h>
9 
10 #include "DllSecur.h"
11 
12 #ifndef UNDER_CE
13 
14 typedef BOOL (WINAPI *Func_SetDefaultDllDirectories)(DWORD DirectoryFlags);
15 
16 #define MY_LOAD_LIBRARY_SEARCH_USER_DIRS 0x400
17 #define MY_LOAD_LIBRARY_SEARCH_SYSTEM32  0x800
18 
19 static const char * const g_Dlls =
20   #ifndef _CONSOLE
21   "UXTHEME\0"
22   #endif
23   "USERENV\0"
24   "SETUPAPI\0"
25   "APPHELP\0"
26   "PROPSYS\0"
27   "DWMAPI\0"
28   "CRYPTBASE\0"
29   "OLEACC\0"
30   "CLBCATQ\0"
31   ;
32 
33 #endif
34 
LoadSecurityDlls()35 void LoadSecurityDlls()
36 {
37   #ifndef UNDER_CE
38 
39   wchar_t buf[MAX_PATH + 100];
40 
41   {
42     // at Vista (ver 6.0) : CoCreateInstance(CLSID_ShellLink, ...) doesn't work after SetDefaultDllDirectories() : Check it ???
43     OSVERSIONINFO vi;
44     vi.dwOSVersionInfoSize = sizeof(vi);
45     if (!GetVersionEx(&vi) || vi.dwMajorVersion != 6 || vi.dwMinorVersion != 0)
46     {
47       Func_SetDefaultDllDirectories setDllDirs = (Func_SetDefaultDllDirectories)
48           GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "SetDefaultDllDirectories");
49       if (setDllDirs)
50         if (setDllDirs(MY_LOAD_LIBRARY_SEARCH_SYSTEM32 | MY_LOAD_LIBRARY_SEARCH_USER_DIRS))
51           return;
52     }
53   }
54 
55   {
56     unsigned len = GetSystemDirectoryW(buf, MAX_PATH + 2);
57     if (len == 0 || len > MAX_PATH)
58       return;
59   }
60   {
61     const char *dll;
62     unsigned pos = (unsigned)lstrlenW(buf);
63 
64     if (buf[pos - 1] != '\\')
65       buf[pos++] = '\\';
66 
67     for (dll = g_Dlls; dll[0] != 0;)
68     {
69       unsigned k = 0;
70       for (;;)
71       {
72         char c = *dll++;
73         buf[pos + k] = c;
74         k++;
75         if (c == 0)
76           break;
77       }
78 
79       lstrcatW(buf, L".dll");
80       LoadLibraryExW(buf, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
81     }
82   }
83 
84   #endif
85 }
86 
87 #endif
88