If you've been using Windows for any length of time, you should be familiar with the registry. The configuration for the entire system is maintained in the registry, and you can alter the behavior of the system by tweaking its settings. The entry I'll discuss is in the following key:
HKEY_LOCAL_MACHINE\Software\Microsoft \Windows NT\CurrentVersion\Windows\AppInit_DLLs |
Windows 98
Windows 98 ignores this registry key, so you cannot use this technique to inject a DLL under Windows 98.
The window below shows what the entries in this key look like when viewed with Registry Editor. The value for this key might contain a single DLL filename or a set of DLL filenames (separated by spaces or commas). Since spaces delimit filenames, you must avoid filenames that contain spaces. The first DLL filename listed might include a path, but any other DLLs that contain a path are ignored. For this reason, it is usually best to place your DLL in the Windows system directory so that paths need not be specified. In the window, I have set the value to a single DLL pathname, C:\MyLib.dll.
When you restart your machine and Windows initializes, the system saves the value of this key. Then, when the User32.dll library is mapped into a process, it receives a DLL_PROCESS_ATTACH notification. When this notification is processed, User32.dll retrieves the saved value of this key and calls LoadLibrary for each DLL specified in the string. As each library is loaded, the library's associated DllMain is called with an fdwReason value of DLL_PROCESS_ATTACH so that each library can initialize itself. Because the injected DLL is loaded so early in the process's lifetime, you must exercise caution when calling functions. There should be no problem calling functions in Kernel32.dll, but calling functions in some other DLL might cause problems. User32.dll does not check whether each library has been successfully loaded or initialized.
Of all the methods for injecting a DLL, this is by far the easiest. All you do is add a value to an already existing registry key. But this technique also has some disadvantages: