John's Computer Journal: sudo for Vista's User Access Control (UAC)

Sunday, April 22, 2007

sudo for Vista's User Access Control (UAC)

By setting a SHELLEXECUTEINFO's lpVerb value to "runas" a call to ShellExecuteEx will cause the UAC to elevate the run privileges for a given program. The concept can be implemented into a simple program so that a behavior similar to linux's sudo command can be achieved.

Methods of Implementation

The ShellExecuteEx runas method can be implemented by any method that interfaces with the ShellExecuteEx API. The code provided below for download was written using c++. Within a visual basic script the ShellExecute function of the Shell.Application object can be used to invoke runas.

The command line tool `runas' provides similar functionality. However, the `runas' command is different enough that it can be confusing for users to use in Vista. The obvious difference is the command line vs. the graphical interface. Other differences include the inability for the `runas' command to accept empty passwords and recognize when the user already has elevated permissions.

Issues

Directory Change

When the runas verb is passed to ShellExecuteEx the current directory always gets reset to the %systemroot%/system32 directory. The lpDirectory variable has no effect. Therefore, to maintain the correct directory the directory must become part of the command that ShellExecuteEx runs. By wrapping the command to execute using runas within a %comspec% /c cd /d "directory" start /d "directory" call the correct directory is used when the command or file is executed.

User Context

The ShellExecuteEx runas method suffers from the same user context problems that haunt the command line tool `runas'. The context switch can cause problems for programs that access user specific areas and variables such as the username, home directory, desktop, or registry. For example, if an installation program is launched through `runas' by a non-administrative user an option such as "create desktop shortcut for local user" will create the shortcut on the administrators desktop NOT the desktop of the user that initialized the installation through the runas command.

There is a workaround to the context problem that would require the user to provide an administrative username and password and then provide their own non-administrative username and password. Aaron Margosis introduced the concept in his "Non-Admin" WebLog where he introduced his MakeMeAdmin batch script.

Download

References

TweakUAC has a package of functions to handle UAC events. The VistaTools.cxx package clued me into setting the lpVerb to "runas".

1 comment:

Rhian said...

This bit of code is freakin' awesome. Thanks!