I am using makecert to create certificate i need to do it though c# program the command doesnot execute as it requires administrator privileges.
Please suggest me how to run any exe using administrator privileges in windows 7?
If possible than just suggest me the sample code.
Does th o.s. really matters in my case?
Another hint again is using UAC( User Account Control) from the code. Very interestimg source IMHO is this one http://victorhurdugaci.com/using-uac-with-c-part-1/
You can use the RunAs:
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/runas.mspx?mfr=true and select an account with the required permissions.
Use the runas verb when starting the process:
ProcessStartInfo info = new ProcessStartInfo(path) { Verb = "runas" };
Process p = Process.Start(info);
This assumes that you are running as a user in the administrator group. In that case the UAC dialog will be shown when the process starts.
Change the manifest of the C# application so that it requires adminstrator privileges. UAC should do the rest to prompt the user and elevate the process.
Related
I have a problem with this situation:
I made 2 programs:
The first one just print an output saying that was launched with admin provileges or not, and the second one, execute the first program with admin privileges and without use the UAC. The trouble is that the second program can't launch the first with admin privileges i don't know why.
This is my code:
Code of the first program:
// This only prints if you start as administrator or not.
bool isElevated;
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
Console.WriteLine("I got admin privileges?: "+isElevated);
Code of the second program:
// This execute the first program with admin privileges without UAC
string username = "myuser";
SecureString userpass = new SecureString();
userpass.AppendChar('m');
userpass.AppendChar('y');
userpass.AppendChar('p');
userpass.AppendChar('a');
userpass.AppendChar('s');
userpass.AppendChar('s');
Process program = new Process();
program.StartInfo.UserName = username;
program.StartInfo.Password = userpass;
program.StartInfo.FileName = "Path/First_program.exe";
program.StartInfo.UseShellExecute = false;
program.Start();
PD: I don't want the user to open the UAC, thats why i already insert the username and the password.
Thanks in advance.
You have half of the answer. The other half is that the program must request to be executed with elevated privileges. By default, Windows programs run in a "Basic" trust level, regardless of the true level of permissions possible under the user. To gain access to administrative powers, the program must request elevation, which by definition will involve UAC.
Programs like yours can request elevation using the runas verb in the ProcessStartInfo, or by specifying requireAdministrator elevated permissions in the manifest of either application (assuming you control them). Either way, if UAC is enabled, the user will get a prompt.
The only way to circumvent this is to set up the program that would otherwise require elevated permissions as a Windows service, configured in services.msc to run with administrative permissions. You'll get one UAC prompt when installing/registering the service to run in this way, and from then on the service can perform that task without any further UAC action. You can then use various communication technologies, from named pipes to true network comms like TCP, to signal the service that it should do what you want.
I have an application that under rare circumstances needs to change its registry setting. Also during it's first execution it needs to create a new key. I'm developing this in Windows 7. I get ThrowUnauthorizedAccessException. How do I force Windows to give me a UAC prompt to temporarily elevate my permissions?
Thanks in advance.
Should all users be allowed to modify this setting? If so, the simplest solution is to modify your installation program to give Users Full Control of the registry key.
If only administrators should be able to modify this setting, then you will need to launch another copy of your program, asking Windows to elevate it:
ProcessStartInfo startInfo = new ProcessStartInfo("C:\Path\To\MyApplication.exe");
startInfo.Verb = "runas"; //trigger a UAC prompt (if UAC is enabled)
System.Diagnostics.Process.Start(startInfo);
If you were smart you would include some command line arguments, so you can tell "yourself" that it should jump straight to the part of the software that the user needs to deal with. Or your command line arguments could just say what you want done:
ProcessStartInfo startInfo = new ProcessStartInfo(
"C:\Path\To\MyApplication.exe",
"/setLoggingEnabled yes");
startInfo.Verb = "runas"; //trigger a UAC prompt (if UAC is enabled)
System.Diagnostics.Process.Start(startInfo);
Have your application check for the setLoggingEnabled switch, make the change, and then exit.
Update: A common situation is players of World of Warcraft. Since the game is allowed to update itself while running, all users must be allowed to modify the game data sitting in Program Files. The correct and valid action is to modify the ACLs on the
C:\Program Files\Blizzard\World of Warcraft
folder so that all users have full control. In fact, before Blizzard got their act together, Microsoft released an application compatibility update that gives all users full control to the WoW folder next time it run as an administrator.
Another common case is when the Blizzard Launcher is launched with administrative privelages, it updates a registry key in HKLM, recording where the game is. This happens when, for example, i move WoW from a hard drive to an SSD drive
run the launcher once as an administator so that the updaters work correctly.
I tried
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = filename,
UserName = "System",
UseShellExecute = false,
},
};
process.Start();
but it yields
Win32Exception was unhandled
Login failed: unknown user name or wrong password
I will have to use CreateProcessAsUser?
How can I get the appropriate parameters to pass to that method?
The System accounts password is maintained interally by Windows (I think) i.e. attempting to start a process as the System account by supplying credentials in this way is ultimately destined to failure.
I did however find a forum post that describes a neat trick that can be used to run processes under the system account by (ab)using windows services:
Tip: Run process in system account (sc.exe)
Alternatively the Windows Sysinternals tool PsExec appears to allow you to run a process under the System account by using the -s switch.
The Username should be LocalSystem if you want to run your process with high privileges (it's a member of Administrators group) or LocalService for normal privileges
EDIT: My mistake LocalSystem & LocalService are not regulary users and, therefore, they cannot be provided as a username. Kragen's solution is the right one
I used the application manifest file as described here to have a part of my application running with elevated privileges (which it needs).
So when needed, the main program just invokes a small assembly using Process.Start which then handles the task for which admin rights are required.
However, how can I do the same thing on Windows XP?
It seems XP just ignores this manifest and runs the small assembly in the current user context.
The following code from here does just what I need:
ProcessStartInfo processStartInfo = new ProcessStartInfo("path", "args");
processStartInfo.Verb = "runas";
using (Process process = new Process())
{
process.StartInfo = processStartInfo;
process.Start();
process.WaitForExit();
}
So in fact you need to set "runas" on ProcessStartInfo.Verb.
With the attached manifest this code now works fine on Windows XP, Vista and 7.
Update:
See also this answer to a similar question. This is basically the same code, just using arguments as well.
Windows XP does not have UAC.
You need to call Process.Start with the login credentials of a user with administrative priviliges.
You can use the runas command.
my application include a self-updater executable that is used to update the application.
One of the first steps the updater is performing is to check that it does have write permission to the application folder
IPermission perm = new FileIOPermission(FileIOPermissionAccess.AllAccess, _localApplicationCodebase);
if (!SecurityManager.IsGranted(perm))
{
OnProgressChanged("Security Permission Not Granted \n The updater does not have read/write access to the application's files (" +
_localApplicationCodebase + ")",MessageTypes.Error);
return false;
}
OnProgressChanged("Updater have read/write access to local application files at " + _localApplicationCodebase);
return true;
When executing under Win7/Vista, this code pass (meaning that according to CAS, the code does have write access), however when I try to write files, I got an Access Denied (and I confirmed that the files are NOT in use)
I understand that Vista/Win7 UAC is preventing users from writing files in the program files folders. However, what I don't understand is why the permission is granted if in reality it is not
Regards,
Eric Girard
PS : If I run the same code using 'Run As Administrator', it works fine
The important thing to know about UAC is that by default, no code runs with Administrator privileges and thus cannot write to the Program Files directory. Even if you are logged in as an administrator, the apps are launched with standard user privliges.
There are two ways around this. You can have the user start the app with the Run As Administrator menu item. But this relies on the user to remember something. The better was is to embed a manifest into your executable that requests administrator privileges. In the manifest, set requestedExecutionLevel to requireAdministrator. This will cause UAC to prompt the user for admin credentials as soon as the app starts.
As Daniel said, the best solution is to put the updating functionality in a separate application. Your primary app will have an manifest that sets the requestedExecutionLevel to "asInvoker" and your updater app with request "requireAdministrator". Your primary app can run with standard privileges. But when the update needs to happen, use Process.Start to launch the updater application that requires the user to enter the admin credentials.
The best way to write an auto updater is to have a secondary application. The first program calls the second with elevated privileges, prompting UAC. Then the second application can install the patches.
I'm not sure if this is what you're trying to do, but I've found this post helpful. The included code let's you detect if you're app is running on Vista, if UAC is enabled and if user is elevated.
http://www.itwriting.com/blog/198-c-code-to-detect-uac-elevation-on-vista.html
then restart your app with runas to let user elevate permissions
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.Verb = "runas";
processInfo.FileName = Application.ExecutablePath;
Process.Start(processInfo);