How can I get permissions to write to registry keys? - windows

I am trying to write some registry keys under the HKLM portion of the registry. I use RegCreateKeyEx() and RegSetValueEx() in a way similar to some of the MSDN examples I have seen.
However, the RegSetValueEx() call fails with error 5, which FormatMessage() says is 'Access is denied'
I think I need to request elevated permissions, but I am unaware of the API calls needed to do this?
Here is my code:
HKEY hk;
DWORD dwDisp;
LONG result = RegCreateKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\MyApp"), 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hk, &dwDisp);
if(result == ERROR_SUCCESS)
{
BYTE value[] = "Hello world!";
result = RegSetValueEx(hk, _T("MyValue"), 0, REG_EXPAND_SZ, value, strlen((char*)value)+1);
if(result != ERROR_SUCCESS)
{
DBG_PRINT2("RegSetValueEx failed with code: %d\n", result);
}
RegCloseKey(hk);
}

In order to have write access to HKLM, your process needs to run as a user with admin rights. In addition, on systems which include UAC (Vista and up), your process will need to run elevated. To achieve that specify requireAdministrator in your application manifest.
It is important that you don't run your application with elevated rights unless it is strictly necessary. You can move the portion of the application that needs to write to HKLM into a one time only operation, e.g. your install program. Or you can separate your application into two parts: the large part that runs with normal rights, and the small part that requires elevation.
The reason that you may need to split your application into smaller parts is that the user token is assigned at process startup and cannot be modified during the life of the process. So, if you want some parts of your application to be elevated, and others not, you need to have two distinct processes.

Related

Win32 - Launching a highestAvailable child process as a normal user process

Suppose your Windows user account is in the Admin group, UAC is enabled, and you're running some program A with normal user privileges. A never asks for elevation and never receives it. Now suppose A wants to launch program B, which has highestAvailable in its manifest.
If A calls CreateProcess(B), this will fail with error 740 ("elevation required")
If A calls ShellExecuteEx(B), Windows will display a UAC box asking to run B elevated. The user can say Yes, in which case B will run elevated, or No, in which case the launch will fail.
My question is: is there any way to achieve a third option, where we simply launch B without elevation?
It seems like this should be possible in principle, since "highestAvailable" means that B prefers to run with elevation but is perfectly capable of running in normal user mode. But I can't figure out any way to accomplish it. I've tried all sorts of things with tokens and CreateProcessAsUser(), but it all seems to come down to this: "highestAvailable" seems to unalterably refer to the latent privileges inherent in the user account, not the actual privileges expressed in any explicitly constructed token.
I'm hoping that there actually is some way to use CreateProcessAsUser() to do this, and that I'm just missing the trick for properly constructing the token.
Update - solved: the __COMPAT_LAYER=RunAsInvoker solution below works nicely. One caveat, though. This coerces the subprocess to run "as invoker" unconditionally: it applies even if the exe being invoked specifies "requireAdministrator" in its manifest. I think the original "elevation required" error is generally preferable when the exe specifies "requireAdministrator". The whole reason I wanted the RunAsInvoker behavior for programs marked with "highestAvailable" is that such programs are expressly saying "I can function properly in either mode" - so let's go ahead and run in normal user mode when it's inconvenient to use Admin mode. But "requireAdministrator" is a different matter: such programs are saying "I can't function properly without elevated privileges". It seems better to fail up front for such programs than to force them to run un-elevated, which might make them encounter privilege/access errors that they're not properly programmed to handle. So I think a complete, general-purpose solution here would require checking the application manifest, and only applying the RunAsInvoker coercion if the manifest says "highestAvailable". An even completer solution would be to use one of the techniques discussed elsewhere to give the caller an option to invoke UAC when presented with a "requireAdministrator" program and offer the user a chance to launch it elevated. I can imagine a CreateProcessEx() cover with a couple of new flags for "treat process privileges as highest available privileges" and "invoke UAC if elevation is required". (The other approach described below, hooking NTDLL!RtlQueryElevationFlags() to tell CreateProcess() that UAC is unavailable, has exactly this same caveat with respect to requireAdministrator programs.)
(It's probably telling that the Windows shell doesn't even offer a way to do this... launching B directly from the shell would give you the UAC box that lets you either launch with Admin privs or not launch at all. If there were any way to accomplish it, the UAC box might offer a third button to launch without privileges. But then again that could just be a UX decision that the third option is too confusing for civilians.)
(Note that there are quite a lot of posts on StackOverflow and the Microsoft dev support sites asking about a very similar-seeming scenario that unfortunately doesn't apply here. That scenario is where you have a parent program that's running elevated, and it wants to launch a non-elevated child process. The canonical example is an installer, running elevated as installers tend to do, that wants to launch the program it just installed, at normal user level, just before it exits. There's lots of posted code about how to do that, and I've based my attempts on some of those techniques, but this is really a different scenario and the solutions don't work in my situation. The big difference is that the child program they're attempting to launch in this case isn't marked with highestAvailable - the child is just a normal program that would launch without any UAC involvement under normal circumstances. There's another difference as well, which is that in those scenarios, the parent is already running elevated, whereas in my scenario the parent is running as normal user level; that changes things slightly because the parent process in this other scenario has access to a few privileged operations on tokens that I can't use because A isn't itself elevated. But as far as I can tell those privileged token operations wouldn't help anyway; it's the fact that the child has the highestAvailable flag that's the key element of my scenario.)
Set the __COMPAT_LAYER environment variable to RunAsInvoker in your process. I don't think this is formally documented anywhere but it works all the way back to Vista.
You can also make it permanent by setting the it under the AppCompatFlags\Layers key in the registry.
the possible hack solution call CreateProcess from not elevated admin user (restricted admin) for exe with highestAvailable in manifest (or from any not elevated user for requireAdministrator exe) - this is hook RtlQueryElevationFlags call and set returned flags to 0.
this is currently work, but of course no any grantee that will be work in next versions of windows, if something changed. however as is.
for hook single time api call - we can set hardware breakpoint to function address and VEX handler . demo working code:
NTSTATUS NTAPI hookRtlQueryElevationFlags (DWORD* pFlags)
{
*pFlags = 0;
return 0;
}
PVOID pvRtlQueryElevationFlags;
LONG NTAPI OnVex(::PEXCEPTION_POINTERS ExceptionInfo)
{
if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP &&
ExceptionInfo->ExceptionRecord->ExceptionAddress == pvRtlQueryElevationFlags)
{
ExceptionInfo->ContextRecord->
#if defined(_X86_)
Eip
#elif defined (_AMD64_)
Rip
#else
#error not implemented
#endif
= (ULONG_PTR)hookRtlQueryElevationFlags;
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
ULONG exec(PCWSTR lpApplicationName)
{
ULONG dwError = NOERROR;
if (pvRtlQueryElevationFlags = GetProcAddress(GetModuleHandle(L"ntdll"), "RtlQueryElevationFlags"))
{
if (PVOID pv = AddVectoredExceptionHandler(TRUE, OnVex))
{
::CONTEXT ctx = {};
ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;
ctx.Dr7 = 0x404;
ctx.Dr1 = (ULONG_PTR)pvRtlQueryElevationFlags;
if (SetThreadContext(GetCurrentThread(), &ctx))
{
STARTUPINFO si = {sizeof(si)};
PROCESS_INFORMATION pi;
if (CreateProcessW(lpApplicationName, 0, 0, 0, 0, 0, 0, 0, &si,&pi))
{
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
else
{
dwError = GetLastError();
}
ctx.Dr7 = 0x400;
ctx.Dr1 = 0;
SetThreadContext(GetCurrentThread(), &ctx);
}
else
{
dwError = GetLastError();
}
RemoveVectoredExceptionHandler(pv);
}
else
{
dwError = GetLastError();
}
}
else
{
dwError = GetLastError();
}
return dwError;
}

Running and giving codes to admin cmd with visual basic [duplicate]

This is my code trying to run cmd.exe with admin priviligies. However, I get the request operation requires elevation. if I run cmd.exe with "Run as Admin" through my windows, it works, however, through vb, it doesn't. This is my code.
Try
Dim process As New Process()
process.StartInfo.FileName = "cmd.exe "
process.StartInfo.Verb = "runas"
process.StartInfo.UseShellExecute = False
process.StartInfo.RedirectStandardInput = True
process.StartInfo.RedirectStandardOutput = True
process.StartInfo.RedirectStandardError = True
process.StartInfo.CreateNoWindow = True
process.Start()
process.StandardInput.WriteLine("route add 8.31.99.141 mask 255.255.255.255 " & cmdorder)
process.StandardInput.WriteLine("exit")
Dim input As String = process.StandardOutput.ReadToEnd
process.Close()
Dim regex As Regex = New Regex("(ok)+", RegexOptions.IgnoreCase) ' wa requested
' txtLog.AppendText(input)
Return regex.IsMatch(input)
Thanks.
You cannot achieve what you want.
You can use Process.Start() to launch an elevated process, but only if you UseShellExecute = true:
Dim process As New Process()
process.StartInfo.FileName = "cmd.exe "
process.StartInfo.Verb = "runas"
process.StartInfo.UseShellExecute = True
process.Start()
The reason is because you must use ShellExecute if you want to launch an elevated process. Only ShellExecute knows how to elevate.
If you specify UseShellExecute = False, then CreateProcess is used rather than ShellExecute. CreateProcess doesn't know how to elevate. Why? From the AppCompat guy:
Well, CreateProcess is really low in the layers. What can you do without the ability to create a process? Not a whole lot. Elevation, however, is a different story. It requires a trip to the app elevation service. This then calls into consent.exe, which has to know how to read group policy and, if necessary, switch to the secure desktop and pop open a window and ask the user for permission / credentials, etc. We don’t even need to take all of these features, let’s just take the dialog box.
Now, for creating a process that requires elevation, normally you just switch up APIs. The shell sits in a much higher layer, and consequently is able to take a dependency on elevation. So, you’d just swap out your call to CreateProcess with a call to ShellExecute.
So that explains how you can elevate cmd, but once you do: you're not allowed to redirect output, or hide the window; as only CreateProcess can do that:
Redirecting I/O and hiding the window can only work if the process is started by CreateProcess().
Which was a long way of saying that this guy asked the same question over here; but without the indignity of having someone close your question.
Note: Any code is released into the public domain. No attribution required.
Make it as an object and then set it to start up requiring admin priv in the application.object.settings thing.

LockFileEx returns success, but seems to have no effect

I'm trying to lock a file, because it is sitting on a network drive, and multiple instances of a program from multiple computers need to edit it. To prevent damage, I intend to set it up so that only one of the instances has rights to it at a time.
I implemented a lock, which would theoretically lock the first 100 bytes of the file from any access. I'm using Qt with its own file handling, but it has a method of returning a generic file handle.
QFile file(path);
HANDLE handle = (HANDLE)_get_osfhandle(file.handle());
OVERLAPPED ov1;
memset(&ov1, 0, sizeof(ov1));
ov1.Offset = 0;
ov1.OffsetHigh = 0;
if (handle == INVALID_HANDLE_VALUE)
{
// error
return;
}
LockFileEx(handle, LOCKFILE_FAIL_IMMEDIATELY | LOCKFILE_EXCLUSIVE_LOCK, 0, 100, 0, &ov1);
qDebug() << file.readLine();
LockFileEx() returns 1, so it seems to have been successful. However, if I run the program in multiple instances, all of them can read and print the first line of the file. More than this, I can freely edit the file with any text editor.
Being a network file is not an issue, as it behaves similarly with a local file.
The problem was that, while the program does not terminate, the QFile variable was local, so after finishing the function, the destructor of the QFile was called, so it released the file. The OS then seemed to have released the lock.
If my QFile survives the scope, everything works just fine. A minor issue is, that while I expected the file to be locked against reading, external programs do have a read-only access to it. It's not a problem, as my program can check whether it can create a lock, and detect failure to do so. This means that the intended mutex functionality works.

How to detect whether Vista UAC is enabled?

I need my application to behave differently depending on whether Vista UAC is enabled or not. How can my application detect the state of UAC on the user's computer?
This registry key should tell you:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
Value EnableLUA (DWORD)
1 enabled / 0 or missing disabled
But that assumes you have the rights to read it.
Programmatically you can try to read the user's token and guess if it's an admin running with UAC enabled (see here). Not foolproof, but it may work.
The issue here is more of a "why do you need to know" - it has bearing on the answer. Really, there is no API because from a OS behavior point of view, what matters is if the user is an administrator or not - how they choose to protect themselves as admin is their problem.
This post has sample code in C# to test if UAC is on and if the current app has been given elevated rights. You can download the code and interpret as needed. Also linked there is a sample that shows the same in C++
http://www.itwriting.com/blog/198-c-code-to-detect-uac-elevation-on-vista.html
The code in that post does not just read from the registry. If UAC is enabled, chances are you may not have rights to read that from the registry.
You don't want to check if UAC is enabled; that doesn't tell you anything.
I can be a standard user with UAC disabled.
You want to check if the user is running with administrative privileges using CheckTokenMembership:
///This function tells us if we're running with administrative permissions.
function IsUserAdmin: Boolean;
var
b: BOOL;
AdministratorsGroup: PSID;
begin
{
This function returns true if you are currently running with
admin privileges.
In Vista and later, if you are non-elevated, this function will
return false (you are not running with administrative privileges).
If you *are* running elevated, then IsUserAdmin will return
true, as you are running with admin privileges.
Windows provides this similar function in Shell32.IsUserAnAdmin.
But the function is depricated, and this code is lifted from the
docs for CheckTokenMembership:
http://msdn.microsoft.com/en-us/library/aa376389.aspx
}
{
Routine Description: This routine returns TRUE if the caller's
process is a member of the Administrators local group. Caller is NOT
expected to be impersonating anyone and is expected to be able to
open its own process and process token.
Arguments: None.
Return Value:
TRUE - Caller has Administrators local group.
FALSE - Caller does not have Administrators local group.
}
b := AllocateAndInitializeSid(
SECURITY_NT_AUTHORITY,
2, //2 sub-authorities
SECURITY_BUILTIN_DOMAIN_RID, //sub-authority 0
DOMAIN_ALIAS_RID_ADMINS, //sub-authority 1
0, 0, 0, 0, 0, 0, //sub-authorities 2-7 not passed
AdministratorsGroup);
if (b) then
begin
if not CheckTokenMembership(0, AdministratorsGroup, b) then
b := False;
FreeSid(AdministratorsGroup);
end;
Result := b;
end;
You can do it be examining the DWORD value EnableLUA in the following registry key:
HKLM/SOFTWARE/Microsoft/Windows/CurrentVersion/Policies/System
If the value is 0 (or does not exist) then the UAC is OFF. If it's present and non-zero, then UAC is ON:
BOOL IsUacEnabled( )
{
LPCTSTR pszSubKey = _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System");
LPCTSTR pszValue = _T("EnableLUA");
DWORD dwType = 0;
DWORD dwValue = 0;
DWORD dwValueSize = sizeof( DWORD );
if ( ERROR_SUCCESS != SHGetValue( HKEY_LOCAL_MACHINE, pszSubKey, pszValueOn,
&dwType, &dwValue, &dwValueSize) )
{
return FALSE;
}
return dwValue != 0;
}
Note that if the user has changed the state of UAC but has not restarted the computer yet, this function will return an inconsistent result.
Check for the registry value at HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
The EnableLUA value determines if UAC is active.
This post is rather ancient, but I wanted to comment on the "why do you need to know" and "check token membership" bits.
The fact is that Microsoft's very own documentation says that "If User Account Control has been turned off and a Standard user attempts to perform a task that requires elevation" we should provide an error instead of showing buttons and/or links with the UAC shield that attempt elevation. See http://msdn.microsoft.com/en-us/library/windows/desktop/aa511445.aspx towards the bottom for the details.
How are we do to this without a way of checking whether UAC is enabled?
Perhaps checking whether the user is running with admin privileges is the right thing to do in this instance, but who knows? The guidance that Microsoft gives is, at best, iffy, if not just downright confusing.
For anyone else that finds this and is looking for a VBScript solution. Here is what I came up with to detect if UAC is enabled and if so relaunch my script with elevated privileges. Just put your code in the Body() function. I found there were problems with transportability between XP and Windows 7 if I wrote code to always launch elevated. Using this method I bypass the elevation if there is no UAC. Should also take into account 2008 and above server versions that have UAC enabled.
On Error Resume Next
UACPath = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA"
Dim WshShell
Set WshShell = CreateObject("wscript.Shell")
UACValue = WshShell.RegRead(UACPath)
If UACValue = 1 Then
'Run Elevated
If WScript.Arguments.length =0 Then
Set objShell = CreateObject("Shell.Application")
'Pass a bogus argument with leading blank space, say [ uac]
objShell.ShellExecute "wscript.exe", Chr(34) & _
WScript.ScriptFullName & Chr(34) & " uac", "", "runas", 1
WScript.Quit
Else
Body()
End If
Else
Body()
End If
Function Body()
MsgBox "This is the body of the script"
End Function
AFAIK, UAC is apolicy setting on the local user or group. So you can read this property from within .Net. Sorry for not having more details but I hope this helps

GetExitCodeProcess() returns 128

I have a DLL that's loaded into a 3rd party parent process as an extension. From this DLL I instantiate external processes (my own) by using CreateProcess API. This works great in 99.999% of the cases but sometimes this suddenly fails and stops working permanently (maybe a restart of the parent process would solve this but this is undesirable and I don't want to recommend that until I solve the problem.) The failure is symptomized by external process not being invoked any more even though CreteProcess() doesn't report an error and by GetExitCodeProcess() returning 128. Here's the simplified version of what I'm doing:
STARTUPINFO si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
PROCESS_INFORMATION pi;
ZeroMemory(&pi, sizeof(pi));
if(!CreateProcess(
NULL, // No module name (use command line).
"<my command line>",
NULL, // Process handle not inheritable.
NULL, // Thread handle not inheritable.
FALSE, // Set handle inheritance to FALSE.
CREATE_SUSPENDED, // Create suspended.
NULL, // Use parent's environment block.
NULL, // Use parent's starting directory.
&si, // Pointer to STARTUPINFO structure.
&pi)) // Pointer to PROCESS_INFORMATION structure.
{
// Handle error.
}
else
{
// Do something.
// Resume the external process thread.
DWORD resumeThreadResult = ResumeThread(pi.hThread);
// ResumeThread() returns 1 which is OK
// (it means that the thread was suspended but then restarted)
// Wait for the external process to finish.
DWORD waitForSingelObjectResult = WaitForSingleObject(pi.hProcess, INFINITE);
// WaitForSingleObject() returns 0 which is OK.
// Get the exit code of the external process.
DWORD exitCode;
if(!GetExitCodeProcess(pi.hProcess, &exitCode))
{
// Handle error.
}
else
{
// There is no error but exitCode is 128, a value that
// doesn't exist in the external process (and even if it
// existed it doesn't matter as it isn't being invoked any more)
// Error code 128 is ERROR_WAIT_NO_CHILDREN which would make some
// sense *if* GetExitCodeProcess() returned FALSE and then I were to
// get ERROR_WAIT_NO_CHILDREN with GetLastError()
}
// PROCESS_INFORMATION handles for process and thread are closed.
}
External process can be manually invoked from Windows Explorer or command line and it starts just fine on its own. Invoked like that it, before doing any real work, creates a log file and logs some information about it. But invoked like described above this logging information doesn't appear at all so I'm assuming that the main thread of the external process never enters main() (I'm testing that assumption now.)
There is at least one thing I could do to try to circumvent the problem (not start the thread suspended) but I would first like to understand the root of the failure first. Does anyone has any idea what could cause this and how to fix it?
Quoting from the MSDN article on GetExitCodeProcess:
The following termination statuses can be returned if the process has terminated:
The exit value specified in the
ExitProcess or TerminateProcess
function
The return value from the
main or WinMain function of the
process
The exception value for an
unhandled exception that caused the
process to terminate
Given the scenario you described, I think the most likely cause ist the third: An unhandled exception. Have a look at the source of the processes you create.
Have a look at Desktop Heap memory.
Essentially the desktop heap issue comes down to exhausted resources (eg starting too many processes). When your app runs out of these resources, one of the symptoms is that you won't be able to start a new process, and the call to CreateProcess will fail with code 128.
Note that the context you run in also has some effect. For example, running as a service, you will run out of desktop heap much faster than if you're testing your code in a console app.
This post has a lot of good information about desktop heap
Microsoft Support also has some useful information.
There are 2 issues that i could think of from your code sample
1.Get yourusage of the first 2 paramaters to the creatprocess command working first. Hard code the paths and invoke notepad.exe and see if that comes up. keep tweaking this until you have notepad running.
2.Contrary to your comment, If you have passed the currentdirectory parameter for the new process as NULL, it will use the current working directory of the process to start the new process from and not the parent' starting directory.
I assume that your external process exe cannot start properly due to dll dependencies that cannot be resolved in the new path.
ps : In the debugger watch for #err,hr which will tell you the explanation for the last error code,

Resources