DSK-27Required
Load libraries only from folders attackers cannot write
At start-up on Windows, limit the library search to the app's own folder and System32 with SetDefaultDllDirectories. Load every other library by its full path. Install machine-wide apps under Program Files, where only administrators can write.
How to do it
A library loaded by name alone is searched for in a list of folders. Microsoft warns that an attacker who controls one of them can plant a malicious copy there, and the app runs it with the user's rights. If the app runs as administrator, the attacker gains those rights too. Installers are the common victim, because they start from the Downloads folder next to whatever else was downloaded. Limit an installer to System32 alone. On a Mac, keep library validation on, which the hardened runtime of Sign and notarise every Mac build turns on. Never ship the entitlement that disables it. A helper that runs as administrator also follows Check who is calling before a privileged helper acts.
Examples
Go example
import "golang.org/x/sys/windows"
const appAndSystemFolders = windows.LOAD_LIBRARY_SEARCH_APPLICATION_DIR | windows.LOAD_LIBRARY_SEARCH_SYSTEM32
func init() {
if err := windows.SetDefaultDllDirectories(appAndSystemFolders); err != nil {
panic(err)
}
}
Plain text example
using System.Runtime.InteropServices;
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.ApplicationDirectory | DllImportSearchPath.System32)]
static class Engine
{
public static IntPtr Load() => NativeLibrary.Load(Path.Combine(AppContext.BaseDirectory, "engine.dll"));
}
How to check
Put a test library named after one the app loads, such as version.dll, in the Downloads folder and in the current folder. Run the installer from Downloads and the app from that folder with a file monitor, such as Process Monitor. The test library is never loaded. A machine-wide install lands under Program Files.
Sources
Related rules
- DSK-33 Keep hardened runtime exceptions to the few the app uses in Desktop apps and extensions
- DSK-1 Sign and notarise every Mac build in Desktop apps and extensions
- DSK-28 Check who is calling before a privileged helper acts in Desktop apps and extensions
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/desktop-apps/installs-and-local-privileges/safe-library-loading">Agent Wranglers desktop apps and extensions playbook</a>. In code you write, add a comment next to it with the same link.