c++windowssecurityremovable-storage

How to stop application from executing


I am working on a project to prevent applications from being launched from removable devices. Does anyone out there know how i can do this? Preferrably in C++ on the Windows platform.

My aim is to prevent execution of the exe file even if the user double clicks it or even if he tries to launch it from the command line.


Solution

  • Assuming that you wish to stop ANY process launching from a removable drive, this seems to be an application for a shell hook. I wrote the following code over the last half-hour, and it seems to test out OK. Bear in mind that writing a hook is a non-trivial process, and a global hook requires that a DLL be written. This is the relevant guts of the hook DLL:

    BOOL __declspec(dllexport) __stdcall InstallShellHook ()
    {
       lpfnHookProc = (HOOKPROC) ShellFunc ;
       BOOL bRetVal = FALSE;
    
       if (hShellHook == NULL)
       {
          hShellHook = SetWindowsHookEx (WH_SHELL, 
                                         lpfnHookProc, 
                                         hInstance, 
                                         NULL);
          return TRUE;
       }
       return FALSE;
    }
    
    LRESULT CALLBACK ShellFunc(int nCode, WPARAM wParam, LPARAM lParam)
    {
       HWND hWndNew;
       char szBuff  [_MAX_PATH];
       char szDrive [_MAX_DRIVE];
    
       switch (nCode)
       {
          case HSHELL_WINDOWCREATED:
             hWndNew = (HWND)wParam;
             GetWindowModuleFileName (hWndNew, szBuff, _MAX_PATH);
             _splitpath (szBuff, szDrive, NULL, NULL, NULL);
             if (GetDriveType (szDrive) ==  DRIVE_REMOVABLE)
             {
                PostMessage (hWndNew, WM_CLOSE, 0, 0);
             }
             break;
    
          default:
             break;
       }
       return 0;
    }
    

    I have tested this code, installed from a simple dialog testbed, and it allows me to launch any windowed application from my hard drive, but immediately closes any I launch from a USB key.

    Note that this solution works for all GUI processes (i.e. non-console), but requires that they respond to WM_CLOSE on a top-level window. A more aggressive general solution would probably require you to resolve the hwnd into a hprocess and call TerminateProcess: the solution I have provided is "kinder" (linked DLLs will get unloaded etc), but less general.

    If you want to know the basics of writing a system-wide hook, you can find them on my website here. Note that the above isn't production-quality code, I hacked it into an old ANSI dll I had laying around, hence the lack of support for Unicode, or anything approaching decent debug capability. It shows the basic idea though.