I have an application that would check for updates upon start and, if updates are found, it would copy some files over the network to the program files folder. Obviously such task can't be performed by Standard Users under normal scenarios.
I tried creating a service to do the update process but I had some security issues and I asked this question about it in superusers.
Now, considering the fact that most applications require elevated privileges to perform such task I think that might be the right approach. But how do I request elevation for the updater under all Windows version as of XP, included. I've found many topics about a manifest file, but since I need this to work with XP I can't create a solution specifically for UAC.
Privileges can only be elevated at startup for a process; a running process' privileges cannot be elevated. In order to elevate an existing application, a new instance of the application process must be created, with the verb “runas”:
private static string ElevatedExecute(NameValueCollection parameters)
{
string tempFile = Path.GetTempFileName();
File.WriteAllText(tempFile, ConstructQueryString(parameters));
try
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
Uri uri = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase);
startInfo.FileName = uri.LocalPath;
startInfo.Arguments = "\"" + tempFile + "\"";
startInfo.Verb = "runas";
Process p = Process.Start(startInfo);
p.WaitForExit();
return File.ReadAllText(tempFile);
}
catch (Win32Exception exception)
{
return exception.Message;
}
finally
{
File.Delete(tempFile);
}
}
After the user confirms the execution of the program as administrator, another instance of the same application is executed without a UI; one can display a UI running without elevated privileges, and another one running in the background with elevated privileges. The first process waits until the second finishes its execution. For more information and a working example you can check out the MSDN archive.
To prevent all this dialog shenanigans in the middle of some lengthy process, you'll need to run your entire host process with elevated permissions by embedding the appropriate manifest in your application to require the 'highestAvailable' execution level: this will cause the UAC prompt to appear as soon as your app is started, and cause all child processes to run with elevated permissions without additional prompting.
Related
I have a Window 10 vb.net main process (tester) that needs to create a process to clean up certain registry area. The products we test have a single FTDI serial port adapter, but over time these instances build up and slow the registry to a crawl.
As the main process starts, the desire is to use an off the shelf utility, DeviceCleanupCmd.exe, to search and remove the driver instance build up. This requires administrator privileges for that sub process. I've been able to do this on XP with script, but the system is running with full administrator privileges. Since it's not on the network, there's very little risk.
Moving forward, we are trying to replace the XP system with a Windows 10 Enterprise box that is network connected. I wanted to incorporate the equivalent of the script into the vb.net process and I modified the vb.net application to use
Process() with StartInfo.Verb = "runas"
Local user credentials (not a domain user) the application provides to start the sub process.
Using this method, my sub process executes, but not with administrator level privileges. The Stackoverflow reference below explains that I can't use this method and have to use CreateProcessWithLogonW. I understand Ian Boyd's concerns for security in the post.
Run process as administrator from a non-admin application
I have followed the Microsoft implementation that follows and am still having issues.
https://learn.microsoft.com/en-us/troubleshoot/dotnet/visual-basic/start-process-as-another-user
Here's the essential part of my code. You will see that I truncated the MS example to use the W2K portion, as we won't be going back that far!
wUser = System.Text.Encoding.Default.GetString(UnicodeStringToBytes(UserName + Chr(0)))
wDomain = System.Text.Encoding.Default.GetString(UnicodeStringToBytes(DomainName + Chr(0)))
wPassword = System.Text.Encoding.Default.GetString(UnicodeStringToBytes(Password + Chr(0)))
wCommandLine = System.Text.Encoding.Default.GetString(UnicodeStringToBytes(CommandLine + Chr(0)))
wCurrentDir = System.Text.Encoding.Default.GetString(UnicodeStringToBytes(CurrentDirectory + Chr(0)))
Result = CreateProcessWithLogonW(wUser, wDomain, wPassword, CREATE_DEFAULT_ERROR_MODE, 0&, wCommandLine, CREATE_NEW_CONSOLE, 0&, wCurrentDir, si, pi)
If Result <> 0 Then
CloseHandle(pi.hThread)
CloseHandle(pi.hProcess)
W2KRunAsUser = 0
Else
W2KRunAsUser = Err.LastDllError
Status = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, CType(0&, IntPtr), W2KRunAsUser, 0, strMessage, Len(strMessage), 0)
MsgBox("CreateProcessWithLogonW() failed with error: " & W2KRunAsUser & " " & strMessage, vbExclamation)
End If
Please remember that my target administrator user is only resident on the PC I'm running the application on - not on the domain. I've verified that I can login with the credentials and run DeviceCleanupCmd.exe with success. In order to login locally, I must use a \ before the user. When I run the code, I've attempted the following, with the error message that Windows 10 supplies after the colon (:):
Providing "user", "password", and "domain" (I know it's not required): The directory name is invalid.
Providing "user", "password", and domain as "": The directory name is invalid.
Providing "\user", "password", and domain as "": The directory name is invalid.
Providing ".\user", "password", and domain as "": The stub received bad data.
Providing "user", "password", and domain as "computer name": The directory name is invalid.
Providing "non-admin user", "password", and "domain of user": DeviceCleanupCmd.exe runs but complains 'No admin privileges available'.
Because the application is complaining about an invalid directory name, I've purposely placed the DeviceCleanupCmd.exe in a C:\sub-directory that is not protected by Windows (Like Program Files). Attempt 6 above would seem to prove that there's not rights/access violations.
I have also tried CREATE_NEW_CONSOLE in place of CREATE_DEFAULT_ERROR_MODE and same results as above. I've proved the user is being decoded, as when I provide an incorrect password, I get "The user name or password is incorrect".
#Hurshey provided the insight to look at the Windows Task Scheduler and the following links support full configuring the task + incorporating the exported XML into NSIS - my target deployment method.
https://www.windowscentral.com/how-create-automated-task-using-task-scheduler-windows-10
https://nsis.sourceforge.io/Talk:Scheduled_Tasks
Hey, I am trying to get a service to start my program but it isn't showing the GUI. The process starts but nothing is shown. I have tried enabling 'Allow service to interact with desktop' but that still isn't working.
My program is a computer locking device to stop unauthorised users from accessing the computer. I am running windows 7 with a 64 bit OS.
Here is the code for my service:
protected override void OnStart(string[] args)
{
Process p = new Process();
p.StartInfo.FileName = "notepad.exe";
p.Start();
FileStream fs = new FileStream(#"C:\Users\David\Documents\Visual Studio 2010\Projects\LockPCService\LockPCService\bin\Debug\ServiceLog.dj",
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(" LockPCService: Service Started " + DateTime.Now + "\n" + "\n");
m_streamWriter.Flush();
m_streamWriter.Close();
}
protected override void OnStop()
{
FileStream fs = new FileStream(#"C:\Users\David\Documents\Visual Studio 2010\Projects\LockPCService\LockPCService\bin\Debug\ServiceLog.dj",
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(" LockPCService: Service Stopped " + DateTime.Now + "\n"); m_streamWriter.Flush();
m_streamWriter.Close();
}
To try and get the service working I am using notepad.exe. When I look at the processes notepad is running but there is no GUI. Also the ServiceLog is there and working each time I run it.
Any ideas on why this isn't working?
Thanks.
This article explains Session 0 Isolation which among other things disallows services from creating a UI in Windows Vista/7. In your service starts another process, it starts in Session 0 and also will not show any UI. (By the way, the UI is created, it's just that Session 0 is never displayed). This article on CodeProject can help you create a process from a service on the user's desktop and show its UI.
Also, please consider wrapping you stream objects in a using statement so that they are properly disposed.
Services run under different account so notepad is run by another user and on another desktop so that's why you cannot see it. 'Allow service to interact with desktop' is not supported anymore starting from Vista.
I know this is a late post, but I found that this article was very helpful to me. I am running Windows 7 and the solution provided in this article works great.
If you download the code, there is a class called ApplicationLoader. Include that class in your project and then it's as simple as this:
// the name of the application to launch
String applicationName = "cmd.exe";
// launch the application
ApplicationLoader.PROCESS_INFORMATION procInfo;
ApplicationLoader.StartProcessAndBypassUAC(applicationName, out procInfo);
Services run in a different logon session and have a different window station from the user. That means that all GUI activity is segregated from the user's programs, not that the service can't display a GUI. Actually, this design makes it much easier to temporarily block access to the user's programs.
You'll need to call SwitchDesktop.
My app needs to write to a file in \ProgramData that could be protected. This only happens once after installation.
Is there an API function that would take ACL info and prompt the user to authorize the app to access the file? In other words the app would ask Windows to prompt the user for confirmation and authorization. This should happen interactively, and allow the app to resume execution after access to the file has been authorized. The app runs as Standard User, does not require Admin privilege.
The file gets opened with CreateFile().
Edit: There is a subtle difference between my query and the others said to be duplicates. I am asking for permission to access one specific object, a file. The others are asking to elevate the privileges of the whole process. Anyway, I am grateful for all responses which include a solution.
If you don't want to elevate your entire app, you have a few options:
spawn a separate elevated process just to access the file. Use ShellExecute/Ex() with the runas verb, or CreateProcessElevated(), to run a second copy of your app, or another helper app, with command-line parameters to tell it what to do. The main process can wait for the second process to exit, if needed.
create a COM object to access the file, and then use the COM Elevation Moniker to run the COM object in an elevated state.
prompt the user for credentials using CredUIPromptForCredentials() or CredUIPromptForWindowsCredentials() (see Asking the User for Credentials for more details), then logon to the specified account using LogonUser() to get a token, impersonate that token using ImpersonateLoggedOnUser(), access the file as needed, and then stop impersonating using RevertToSelf() and close the token with CloseHandle().
Thanks to #Remy for the ShellExecuteEx suggestion, here are the sordid details. Note the use of 'cmd' and the double-command, so the user only has to reply once. Also, [1] must wait for process completion otherwise you could find yourself creating the file before it was deleted, and [2] don't wait for the process if it failed.
// delete file with Admin privilege
// 'file_name' is path of file to be deleted
SHELLEXECUTEINFO shex;
char param[512];
char *cmd = "/C \"attrib -H \"%s\" && del /F /Q \"%s\"\""; // double command
_snprintf(param, sizeof(param), cmd, file_name, file_name);
ZeroMemory(&shex, sizeof(shex));
shex.cbSize = sizeof(shex);
shex.lpVerb = "runas"; // runas, open
shex.lpFile = "cmd"; // not 'del'
shex.lpParameters = param;
shex.nShow = SW_HIDE;
shex.fMask = SEE_MASK_NOCLOSEPROCESS;
BOOL retshx = ShellExecuteEx(&shex);
// wait otherwise could return before completed
if(retshx)
{ time_t st = clock();
DWORD exitCode;
do
{ if(!GetExitCodeProcess(shex.hProcess, &exitCode))
break;
if(clock() - st > CLOCKS_PER_SEC * 5) // max 5 seconds
break;
} while(exitCode != STATUS_WAIT_0); // STILL_ACTIVE
CloseHandle(shex.hProcess);
}
Processes can only be launched with an elevated token, they can't gain it after the fact. So you can either re-launch your app elevated with a command line argument telling it what to do (simple solution), or implement an out-of-proc COM server that you can create elevated and pass instructions to it (harder).
A third solution is to leverage the built-in UAC support of the IFileOperation interface, but this doesn't let you read/write, only copy. So you could make a copy of the file you need to modify, modify the copy and then use IFileOperation to copy the temporary over the original.
I am running a console application with no UI and generate thumbmail images from pdf files. The compile file for this application works fine. However I have to call this compile file from windows service application that implement the the FileSystemWatcher class to detect when new pdf files are uploaded into the directory.
and I am using the suggestion from this link
How to run console application from Windows Service?
ProcessStartInfo info = new ProcessStartInfo(appName);
info.UseShellExecute = false;
info.RedirectStandardError = true;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.CreateNoWindow = true;
info.ErrorDialog = false;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process process = Process.Start(info);
if (!process.HasExited)
{
LogEvent(process.ProcessName + "has started and called Thumbnail application");
}
else
{ LogEvent(process.ProcessName + "has been terminated"); }
I can see the process involking the "pdfThumbnail.exe" but I am getting this error when the application try to execute.
"System.Exception: Cannot create ActiveX component.
at Microsoft.VisualBasic.Interaction.CreateObject(String ProgId, String ServerName)
at PDFThumbnailCsharp.Main(String[] args)
"
As I have said above the pdfThumbnail.exe execute fine when i run the exe file.
Updates
This is the error from the SysInternals' Process Monitor
The machine-default permission settings do not grant Local Activation permission for the COM Server application with CLSID {FF76CB60-2E68-101B-B02E-04021C009402} and APPID
Unavailable to the user NT AUTHORITY\LOCAL SERVICE SID (S-1-5-19) from address LocalHost (Using LRPC). This security permission can be modified using the Component Services administrative tool.
I have changed the ownership of this CLSID to Administrator with Full control as described on this link
http://social.technet.microsoft.com/Forums/en-US/windowsserver2008r2general/thread/e303c7e1-16de-42fd-a1a4-7512c1261957
However I am still getting the same error.
Any help will be appreciated.
Thanks
This CLSID {FF76CB60-2E68-101B-B02E-04021C009402} is for Acrobat.Excha.PDDoc on my computer registry. Further investigation with Acrobat on this link https://forums.adobe.com/thread/1467460 revealed that Acrobat cannot be run from service.
What I have done for now until I have a better approach is to create a windows Task Scheduler that listen to an event raised by the windows service when new pdf are created and then trigger the console app that create the thumbnails.
I've been tasked with converting a legacy application to mvc. The app used pgp.exe to pgp sign user input and send it as an email. The application works locally and on a test server but won't run on a live server. I've had to jump though hoops such as running a specified user in the application pool so that we can set the keys in the users profile BUT it worked.
For some reason on the live server which is windows 2003 IIS 6 and identical to the testing server it fails. The problem is pgp.exe just wont seem to sign and create files the message I get from the console out put is. "Signature Error"?? When I put the command into a shell window logged in as the app pool user it runs no problem (after a fight with some permissions) but when running through the mvc application/IIS server it fails. The code used to call the process is below.
var startInfo = new ProcessStartInfo();
startInfo.FileName = _pgpexeLocation;
//startInfo.FileName = "pgp.exe";
startInfo.Arguments = string.Format("-sta \"{0}\" -u keyuser-z keypass +COMPATIBLE +FORCE", _tempFilePath);
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.LoadUserProfile = true;
using (Process exeProcess = Process.Start(startInfo))
{
// TODO: set limit to wait for and deal with exit
exeProcess.WaitForExit();
//var stringItem = exeProcess.StandardOutput.ReadToEnd();
//Logger.Info(stringItem);
}
I'm clutching at straws here hoping somebody has done something similar before and can help. I'm guessing it's key location or file location not being picked up somewhere but not sure what else to try?
Turns out that even though the app pool was using a specific user and I'd set the keys up in that users appdata folder when I checked the underlying process call it was actually trying to pick the keys up from the Default User profile. Not sure if this was an IIS config or something similar but moving the keys and pgp folder to this appdata instead worked?