Creating folders in UAC-protected areas - windows-7

I have an application which needs to be able to create folders in UAC-protected directories semi-automatically (the user will be there to approve the UAC notice, but I don't want to ask them to go do it themselves). The program does not otherwise need elevation; is there a common call that can be used to leverage Explorer's built in elevation prompts for this, or must I implement my own elevated helper component to do this?

This is usually done by creating a separate process with the "runas" verb:
ShellExecute example
C# example
This process can perform any operations which require elevation.

Related

Set up file and registry redirection for a given (new) process in Windows

I want to set up path redirection in both files and registry keys in the same manner UAC virtualization works for another process at launch time (either programmatically or using some existing interface).
For example, I want to run C:\my_path\app.exe and when it opens any file on disk (C:\other_path\file.txt) for writing, the actual open file should be C:\temp_for_my_app\C\other_path\file.txt.
I've seen some programs are able to set up such redirection (i.e. Sandboxie), but I'm unsure which mechanism they are using (not even sure if it is the same UAC virtualization uses).
Any insight into the way UAC virtualization implements it might be useful (your comment on this will be appreciated)
Try cmregistercallback() or API HOOKING to hook zwopenkey() and zwcreatekey()

Get administrator privilegs in Qt during runtime [duplicate]

Is it possible to get a C++ application running in Windows to request administrator privileges from the operating system at run time?
I know it can be done at compile time, but can't seem to find anywhere whether it can be done at run time.
Thanks for your help!
EDIT: What if I want the current instance to have elevated privileges? For example, I might have data stored in memory which I want to keep.
If you want the application to always elevate, you can give it a manifest, either by building one in (not compiling technically) or by putting an external manifest in the same folder as the exe. If you want to decide, as a person, to run it elevated, you right click the exe or short cut and choose Run As Administrator. If you are launching it from code, then as #vcsjones comments, you use the runas verb when you launch that process. For example:
ShellExecute( NULL,
"runas",
"c:\\windows\\notepad.exe",
" c:\\temp\\report.txt",
NULL, // default dir
SW_SHOWNORMAL
);
You can elevate a process only during its creation. When a process already runs, there's no way to change its security token: it either runs elevated or not.
If your application needs to perform an administrative task, and it usually runs non-elevated, you have to create another .exe which will request elevation with its manifest. To start a process elevated, you have to use ShellExecute or ShellExecuteEx function. From your main process you will need a way to pass the commands to that new process that will run elevated.
For more information about UAC, read Designing UAC Applications for Windows Vista series.
Not quite, but you can do the opposite—you can drop privileges if you already have them. So, you can have your program start out running as an Administrator, using one of the methods listed by Kate Gregory. Then, drop your unneeded privileges; see Dropping privileges in C++ on Windows for how to do that.
Add a manifest file into your EXE as described here.
http://msdn.microsoft.com/en-us/library/bb756929.aspx
Your process (and threads) have a token assinged to them. That token already have all your groups set up. Under UAC, the Administrator group is disabled. UAC will remove that disabled group so you end up with a full administrator token.
To acheive the same, you must have the TCB priviledge. In other words, to elevate a process at runtime, you will need help from a process running under the SYSTEM account, and Microsoft isn't providing one, nor an API to control the current UAC implementation. Otherwise, it would defeat the purpose.
For the sake of completness, there is a whitelist of process that can perform some elevated operations without prompting. In short, your executable needs :
To be signed by Microsoft
To perform predefined operations, like with IFileOperation
The best explanation I found is this hack. It has been fixed since then, but is sheds some light on the whole thing.

What are the differences between "Run as administrator" and a manifest with requireAdministrator?

I've written a program with a manifest that includes requireAdministrator. On Windows 7 systems with UAC enabled, Windows pops up a dialog asking for permissions, as it should. Works great.
If a user starts my program by right-clicking it and choosing "Run as administrator", then Windows 7 also pops up a dialog asking for permissions. However, there are some slight differences in how my program operates in some of the more esoteric parts of my program.
So what are the differences between "Run as administrator" and a manifest with requireAdministrator? Any links to documentation that describe differences would be appreciated.
Edit: This is with UAC enabled.
Edit: As promised below is the full explanation of the difference I'm seeing.
I'm using the EasyHook library to inject a DLL into another process. When my application is run with "Run as administrator", the injected process crashes and EasyHook returns the error "Unknown error in injected assembler code". None of the code in my DLL gets a chance to execute; the crash occurs before then. (Moreover, the crash occurs even if I strip the DLL down to nothing)
If I run my program normally (i.e., elevated via requireAdministrator), everything works fine.
My application is composed of a few different executables. The process that the user launches is not the same process that performs the injection.
With the information given there would be no differences in the permissions between the two processes.
If you request an execution level of "requireAdministrator" via the applications manifest your application will either be launched with the full access token of an administrator or not at all if the user denies consent (see Create and Embed an Application Manifest (UAC) for further information).
The same will happen when a user chooses Run as Administrator.
The only difference is the way that the process is started. When you start an executable from the shell, e.g. by double-clicking in Explorer or by selecting Run as Administrator from the context menu, the shell will call ShellExecute to actually start process execution. The whole process of elevation is hidden inside this function. Kenny Kerr describes this process in more details in Windows Vista for Developers – Part 4 – User Account Control:
ShellExecute first calls CreateProcess to attempt to create the new process. CreateProcess does all the work of checking application compatibility settings, application manifests, runtime loaders, etc. If it determines that the application requires elevation but the calling process is not elevated then CreateProcess fails with ERROR_ELEVATION_REQUIRED. ShellExecute then calls the Application Information service to handle the elevation prompt and creation of the elevated process since the calling process obviously doesn’t have the necessary permissions to perform such a task. The Application Information service ultimately calls CreateProcessAsUser with an unrestricted administrator token.
If on the other hand you want to create an elevated process regardless of what application information is available then you can specify the little-known “runas” verb with ShellExecute. This has the effect of requesting elevation regardless of what an application’s manifest and compatibility information might prescribe. The runas verb is not actually new to Windows Vista. It was available on Windows XP and Windows 2003 and was often used to create a restricted token directly from the shell. This behavior has however changed. Here is a simple example:
::ShellExecute(0, // owner window
L"runas",
L"C:\\Windows\\Notepad.exe",
0, // params
0, // directory
SW_SHOWNORMAL);
So essentially starting an executable using the Run as Administrator option means that ShellExecute bypasses the checks for compatibility settings, application manifests etc and directly requests elevation.
Kenny Kerr's article also has sample code to query the current process' token for its permission using the OpenProcessToken function. Possibly you can use the example to identify that there are no differences in the way your process is elevated.
I'm definitely curious to know which differences you are observing as I strongly doubt they are related to elevation.
As a last thing: Can you double check that you really request a level of requireAdministrator and not by mistake only a level of highestAvailable?
One possible difference might be the rarely used/understood/deliberately-chosen uiAccess attribute. Can you create two manifests, one with uiAccess=false and one with uiAccess=true, then tell us whether one of them gives the same behaviour as you see with right-click-run-as-admin?
The EasyHook documentation for the RemoteHooking class' IsAdministrator property mentions:
Due to UAC on Windows Vista, this property in general will be false even if the user is in the builtin-admin group. As you can't hook without administrator privileges you should just set the UAC level of your application to requireAdministrator.
It's hard to imagine why this is happening, but it is conceivable (especially as you are seeing it happen!) that assets, processes, assemblies, &c, with possibly different trust levels and so forth, will not inherit the elevation of your main app. Setting the requireAdministrator flag may handle/enforce this globally across the entire scope of resources and dependencies. Would love to know how this turns out.
I thought I was seeing a difference between these as well. However, it turned out that in my case the issue was this:
When I click "Run as Administrator" from my file browser (Q-Dir), the working directory is different than when I try simply double clicking an application with requireAdministrator set in the manifest. This changed the behavior of some buggy DLLs I had received. In fact, it turned out that 100% of the differences I saw were due to running from different working directories (specifically, it mattered whether I was on C: drive or a different drive letter) and that the method of getting the program to run as administrator had nothing to do with it.
It's an issue that is specific to my computer's exact configuration, but it is a possible clue into the type of thing that might be happening (or might have happened 7 years ago . . . )

Programatically registering .dll's on Windows Vista (using DllRegisterServer)

Instead of calling regsvr32.exe, one can register a .DLL using the following steps:
HINSTANCE hLib = ::LoadLibraryEx(dllPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
HRESULT (STDAPICALLTYPE* lpDllEntryPoint)(void);
(FARPROC&)lpDllEntryPoint = ::GetProcAddress(hLib, "DllRegisterServer");
const HRESULT hRes = (*lpDllEntryPoint)();
This works fine on Windows XP. Regrettably, it fails on Vista, but only with some specific DLLs. hRes becomes E_ACCESSDENIED. I guess this is a security issue. Does anyone know how to register a .DLL from code on Windows Vista?
Note: I was logged in as administrator when running this code.
COM registration requires write access to the HKEY_LOCAL_MACHINE part of the registry.
Under UAC, write access to the HKEY_LOCAL_MACHINE requires an elevated administrator.
The easiest way to get an elevated process is to create it with a manifest that specifies 'requireAdministrator' access. - Look under the Project Properties -> Configuration Properties->Linker->Manifest File->UAC Execution Level to set the correct setting.
This means you will probably want to split your EXE into two parts. The 'normal' asInvoker part, and, when self registration is detected as a requirement, an elevated InstallMyself part. When the non elevated part detects a first-run type condition, it needs to use ShellExecute(Ex) to execute the FirstInstall.exe part - using CreateProcess or some other API will simply fail with a insufficient privilege error. ShellExecute will present the UAC prompt.
It is possible to use Application Isolation to load COM dll's without any registration step at all.
Is is unfortunate that the cause cannot be determined. However, if you are interested in doing further research, a tool that will help a lot would be Process Monitor from SysInternals. Process Monitor can log all the File, Registry and other access for a process, including all success and fail codes making it a lot easier to debug problems like this without having to resort to deeper means of reverse engineering.
Regrettably, I couldn't get this to work for all DLLs, even with Chris Becke's excellent tips. I didn't want to spend too much time solving the problem, so now I simply call regsvr32.exe. I expect this .exe to be present on all Windows machines, so I guess it is a good enough solution.

Using SHFileOperation within a Windows service

It's possible, but is it appropriate to use SHFileOperation within a Windows service? All those SHxxx API functions in shell32.dll seem to have been written with user level programs in mind. Can I be certain SHFileOperation won't display GUI ever?
According to the SHFILEOPTSTRUCT documentation, you can use the following flags to prevent any UI from appearing:
FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR
or (if you're targeting Windows Vista), FOF_NO_UI, which is the same as the above.
Looking in the ShellAPI.h header file in the Windows SDK, the comment against FOF_NO_UI says "don't display any UI at all", so from this I assume it's OK to use SHFileOperation.
I would say, not it's not appropriate or advisable. Most of the shell32 APIs were written with a basic understanding that they would be used in interactive processes. I don't think there is any way you can guarantee that SHFileOperation will never display a UI component. In fact, if you look at IFileOperation (which is the new Vista interface that replaces SHFileOperation), it clearly states:
Exposes methods to copy, move, rename, create, and delete Shell items as well as methods to provide progress and error dialogs. This interface replaces the SHFileOperation function.
I have to agree: not appropriate or advisable.
The prinicpal reason to use SHFileOperation is to perform operations with a UI, and/or which are reversable. I.e. using SHFileOperation to delete files is going to place the files in a recycle bin rather than deleting them allowing the current interactive user to undelete, or undo the operation performed.
As the services run on a non interactive desktop, no one will ever be able to clear that recycle bin out.
I had this issue as well and working at implementing a secure and reliable network file copy between servers and network shares ( most of these shares are CIFS / NetApp filer based ) and SHFileOperation fails from time to time.
now started using ROBOCOPY (available by default in all Microsoft OS from Vista/Server 2008 upwards) and really looks interesting and reliable.
this has opened my eyes: https://stackoverflow.com/a/1030752/559144

Resources