1 /* DllSecur.c -- DLL loading security
2 2018-02-21 : 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   "VERSION\0"
32   ;
33 
34 #endif
35 
My_SetDefaultDllDirectories()36 void My_SetDefaultDllDirectories()
37 {
38   #ifndef UNDER_CE
39 
40     OSVERSIONINFO vi;
41     vi.dwOSVersionInfoSize = sizeof(vi);
42     GetVersionEx(&vi);
43     if (!GetVersionEx(&vi) || vi.dwMajorVersion != 6 || vi.dwMinorVersion != 0)
44     {
45       Func_SetDefaultDllDirectories setDllDirs = (Func_SetDefaultDllDirectories)
46           GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "SetDefaultDllDirectories");
47       if (setDllDirs)
48         if (setDllDirs(MY_LOAD_LIBRARY_SEARCH_SYSTEM32 | MY_LOAD_LIBRARY_SEARCH_USER_DIRS))
49           return;
50     }
51 
52   #endif
53 }
54 
55 
LoadSecurityDlls()56 void LoadSecurityDlls()
57 {
58   #ifndef UNDER_CE
59 
60   wchar_t buf[MAX_PATH + 100];
61 
62   {
63     // at Vista (ver 6.0) : CoCreateInstance(CLSID_ShellLink, ...) doesn't work after SetDefaultDllDirectories() : Check it ???
64     OSVERSIONINFO vi;
65     vi.dwOSVersionInfoSize = sizeof(vi);
66     if (!GetVersionEx(&vi) || vi.dwMajorVersion != 6 || vi.dwMinorVersion != 0)
67     {
68       Func_SetDefaultDllDirectories setDllDirs = (Func_SetDefaultDllDirectories)
69           GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "SetDefaultDllDirectories");
70       if (setDllDirs)
71         if (setDllDirs(MY_LOAD_LIBRARY_SEARCH_SYSTEM32 | MY_LOAD_LIBRARY_SEARCH_USER_DIRS))
72           return;
73     }
74   }
75 
76   {
77     unsigned len = GetSystemDirectoryW(buf, MAX_PATH + 2);
78     if (len == 0 || len > MAX_PATH)
79       return;
80   }
81   {
82     const char *dll;
83     unsigned pos = (unsigned)lstrlenW(buf);
84 
85     if (buf[pos - 1] != '\\')
86       buf[pos++] = '\\';
87 
88     for (dll = g_Dlls; dll[0] != 0;)
89     {
90       unsigned k = 0;
91       for (;;)
92       {
93         char c = *dll++;
94         buf[pos + k] = (Byte)c;
95         k++;
96         if (c == 0)
97           break;
98       }
99 
100       lstrcatW(buf, L".dll");
101       LoadLibraryExW(buf, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
102     }
103   }
104 
105   #endif
106 }
107 
108 #endif
109