This technique uses the GetForegroundWindow and Sleep APIs to attempt to evade sandboxes. Many sandboxes do not alter the foreground window like a user would in a normal desktop environment.

It accomplishes this by making a call to GetForegroundWindow, which returns a handle to the current window. Then the malware sample will sleep for a short time, followed by another call to GetForegroundWindow. If the foreground window has not changed, the malware assumes it is in a sandbox or analysis virtual machine and will continue this loop until the foreground window changes. If there is no change, the program will loop indefinitely or may make a call to ExitProcess.


Code Snippets

Kyle Cucci


This technique is using the API GetForegroundWindow.

#include <winuser.h> // Required import for GetForegroundWindow API
int main()
    //Get a handle to user's current foreground window.
    int foregroundWindowHandle1 = GetForegroundWindow(); 
    do {
        //Sleep for .1 second.
        //Get a handle to user's current foreground window again.
        int foregroundWindowHandle2 = GetForegroundWindow(); 
    //While the handles to the current foreground windows are equal, continue to loop.
    while (foregroundWindowHandle1 == foregroundWindowHandle2);
    return 0;

Detection Rules

import "pe"
rule UNPROTECT_Possible_GetForegroundWindow_Evasion
        description = "Attempts to detect possible usage of sandbox evasion techniques using GetForegroundWindow API, based on module imports."
        author = "Kyle Cucci"
        date = "2020-09-30"
        uint16(0) == 0x5A4D and
        pe.imports("user32.dll", "GetForegroundWindow") and
        pe.imports("kernel32.dll", "Sleep")

Additional Resources

Subscribe to our Newsletter and don't miss important updates