1.8. Executing External Programs Securely
Problem
Your Windows program needs to execute another program.
Solution
On
Windows, use the
CreateProcess( )
API function to load and execute a new
program. Alternatively, use the CreateProcessAsUser(
)
API function to load and execute a new
program with a primary access token other than the one in use by the
current program.
Discussion
The Win32 API provides several functions for executing new programs.
In the days of the Win16 API, the proper way to execute a new program
was to call WinExec( )
. While this function still exists in the
Win32 API as a wrapper around CreateProcess( ) for
compatibility reasons, its use is deprecated, and new programs should
call CreateProcess( ) directly instead.
A powerful but extremely dangerous API function
that is popular among developers is ShellExecute(
)
. This function is implemented as a wrapper
around CreateProcess( ), and it does exactly what
we’re about to advise against
doing with CreateProcess( )—but
we’re getting a bit ahead of ourselves.
One of the reasons ShellExecute( ) is so popular
is that virtually anything can be executed with the API. If the file
to execute as passed to ShellExecute( ) is not
actually executable, the API will search the registry looking for the
right application to launch the file. For example, if you pass it a
filename with a .TXT extension, the filename will probably start Notepad with the specified file loaded. While this can be an incredibly handy feature, it’s also ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access