Syncronize time wint NTP-servers without admin rights - c#

I wrote an application, that grab time from NTP server and change system time of my machine. It works good, but time synchronizing only if my apps start with admin rights. So a question is how to launch it without admin privileges, but to save it functionality?
I set system time using WinAPI function SetSystemTime.

you can do this in several ways (have the most proper one for you).
Identity Impersonation => described with example at this address
WindowsIdentity identity = new WindowsIdentity(accessToken);
WindowsImpersonationContext context = identity.Impersonate() ;
runas verb
ProcessStartInfo startInfo = new ProcessStartInfo (m_strInstallUtil, strExePath);
startInfo.Verb = "runas";
System.Diagnostics.Process.Start (startInfo);
please keep in mind that UAC will be prompted for the second method
PrincipalPermissin (if the user is the member of Admin group)
[PrincipalPermission(SecurityAction.Demand, Role = #"BUILTIN\Administrators")]

Related

C# / .Net: Run CMD as admin with provided credentials

i searched for this some hours today but i only find solutions that wont work.
Maybe it is impossible but let's give it a try:
I'm in a company and I will write some code so that a user can run the software whenever he need it. The software needs administrator-permissions. For example I've wrote some code to start the cmd as admin and create a folder at c:/Windows (you'll need admin-permission for that). The credentials for the admin account are right (we use Microsoft AD) but I only get "Access denied" in the cmd.
Does anyone know whether it is possible to get admin permission with hard coded credentials?
Note: Don't talk about security risks, the cmd is not the target software but it should demonstrate the problem.
My code:
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = #"/Kmkdir C:\Windows\_Test";
p.StartInfo.UserName = "admin";
System.Security.SecureString sPW = new System.Security.SecureString();
sPW.AppendChar('a');
sPW.AppendChar('b');
sPW.AppendChar('c');
p.StartInfo.Password = sPW;
p.StartInfo.UseShellExecute = false;
p.Start();
You are still getting an error because all admin accounts in newer windows versions (since Vista) technically are standard user accounts. The way administrative tasks are performed is through the User Account Control (UAC). It allows you to elevate permissions as administrator to perform administrative tasks. So yes, you are executing the process using an administrator account, but you did not elevate the process. To do so, add this parameter:
p.StartInfo.Verb = "runas";
p.StartInfo.UseShellExecute = true;
You can remove all other parameters regarding authentication, since all the authentication is handled by UAC. If for some reason you wish not to use UAC, then you probably will have to disable it, which is not recommended in most cases.

Cannot run as a non-admin impersonated user - access is denied

I do impersonation of a non-admin user account in an app that is running as an admin user (using LogonUser(), DuplicateToken() and WindowsIdentity.Impersonate() functions). Since this user account is temporary, I also need to load a user profile (using LoadUserProfile() native function). All methods execute successfully (no last error is set) and the current identity is the impesonated non-admin user as expected. However, when I try to run a new process with System.Diagnostics.Process.Start(), I get an error:
Access is denied.
When I try to manually execute the same scenario with runas /profile /user:mynonadmin user, everything works fine.
What am I missing here?
Ran into this a while back.
The impersonated user did not have access to the CWD which was set on the Process object. Create a ProcessStartInfo object and set the working directory to a location the impersonated user has access to.
I had a very similar situation with a service project. Here is some over-simplified pseudo code to give you an idea of what I was doing:
uint ConsoleSessionID = WTSGetActiveConsoleSessionId()
WTSQueryUserToken(ConsoleSessionID, out hToken)
IsUserInAdminGroup(hToken)
DuplicateTokenEx(hToken, TOKEN_ALL_ACCESS, ref sa, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out IntPtr DuplicateToken)
WindowsIdentity.RunImpersonated(new SafeAccessTokenHandle(DuplicateToken), () =>
{
Process p = new Process();
p.StartInfo.FileName = ...
p.StartInfo.Arguments = ...
p.WorkingDirectory = ...
p.StartInfo.UseShellExecute = true;
p.StartInfo.Verb = "runas"; // Elevated!
p.Start();
}
This worked ABSOLUTELY FINE when logging into Windows using the local Administrator account.
However, if I created a "Test_User" account that was a member of the administrators group, I was getting ACCESS DENIED OR a 0xc0000142 exception from Process.Start().
Allow service to interact with desktop
After checking "Allow service to interact with desktop", now whether I used the actual local Administrator account, or any other account that is a member of the local administrators group, my service can now start an elevated application in the context of the logged-on user.
Of course I went back and updated my code for installing the service, to ensure the SERVICE_INTERACTIVE_PROCESS flag was set, so this option was set programmatically.
Hope this helps someone...

how to start a process as user then elevate in c# ASP.NET

I am working on a web application that install software on a server.
I can run the install by hand if I log in a user that is apart of a specific group then run install msi as administrator.
This specific group is apart of the local administrators group.
My app pool is running as Network_Service.
Do I impersonate then use the runAs verb? but then I need to know the u/p as user and u/p of Administrator .. I think
I am using the System.Diagnostics.Process classes.
System.Diagnostics.ProcessStartInfo oInfo = new System.Diagnostics.ProcessStartInfo(str);
oInfo.UseShellExecute = false;
oInfo.ErrorDialog = false;
oInfo.CreateNoWindow = false;
oInfo.RedirectStandardOutput = true;
Process p = System.Diagnostics.Process.Start(oInfo);
System.IO.StreamReader oReader2 = p.StandardOutput;
string sRes = oReader2.ReadToEnd();
oReader2.Close();
return sRes;
You need to set the UserName and Password properties to the login credentials of an Administrator account.
You can't change the user context of a running process later on. I suggest u use windows authentication and impersonation to be sure the web request is executed as the authenticated user and besides that you don't have to care about the user credentials.

Admin rights for a single method

Is it possible to require administrator rights for one single method?
Something like this:
[RequireAdminRightsForThisMethod()]
private void TheMethod(){
// Do something
}
You can add a PrincipalPermission attribute to your method to demand administrative privileges for its execution:
[PrincipalPermission(SecurityAction.Demand, Role = #"BUILTIN\Administrators")]
public void MyMethod()
{
}
This is described in more detail in the following article:
Security Principles and Local Admin Rights in C# .Net
If you are looking for a way to elevate an already existing process I doubt that this is possible as administrator privileges are given on process-level to a process upon startup (see this related question). You would have to run your application "as administrator" to get the desired behavior.
However, there are some tricks that might allow you to do what you want, but be warned that this might open up severe security risks. See the following thread in the MSDN forums:
Launching MyElevatedCom Server without prompting Administrator credentialls from Standard User
Update (from comment)
It seems that if an update requires elevation your application update is best done by a separate process (either another executable, or your application called with a command line switch). For that separate process you can request elevation as follows:
var psi = new ProcessStartInfo();
psi.FileName = "path to update.exe";
psi.Arguments = "arguments for update.exe";
psi.Verb = "runas";
var process = new Process();
process.StartInfo = psi;
process.Start();
process.WaitForExit();
A method can require administrative privileges to run, but it's not possible to automatically elevate to Admin when executing a method.

Elevating process privilege programmatically?

I'm trying to install a service using InstallUtil.exe but invoked through Process.Start. Here's the code:
ProcessStartInfo startInfo = new ProcessStartInfo (m_strInstallUtil, strExePath);
System.Diagnostics.Process.Start (startInfo);
where m_strInstallUtil is the fully qualified path and exe to "InstallUtil.exe" and strExePath is the fully qualified path/name to my service.
Running the command line syntax from an elevated command prompt works; running from my app (using the above code) does not. I assume I'm dealing with some process elevation issue, so how would I run my process in an elevated state? Do I need to look at ShellExecute for this?
This is all on Windows Vista. I am running the process in the VS2008 debugger elevated to admin privilege.
I also tried setting startInfo.Verb = "runas"; but it didn't seem to solve the problem.
You can indicate the new process should be started with elevated permissions by setting the Verb property of your startInfo object to 'runas', as follows:
startInfo.Verb = "runas";
This will cause Windows to behave as if the process has been started from Explorer with the "Run as Administrator" menu command.
This does mean the UAC prompt will come up and will need to be acknowledged by the user: if this is undesirable (for example because it would happen in the middle of a lengthy process), you'll need to run your entire host process with elevated permissions by Create and Embed an Application Manifest (UAC) 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.
Edit: I see you just edited your question to state that "runas" didn't work for you. That's really strange, as it should (and does for me in several production apps). Requiring the parent process to run with elevated rights by embedding the manifest should definitely work, though.
This code puts the above all together and restarts the current wpf app with admin privs:
if (IsAdministrator() == false)
{
// Restart program and run as admin
var exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
ProcessStartInfo startInfo = new ProcessStartInfo(exeName);
startInfo.Verb = "runas";
System.Diagnostics.Process.Start(startInfo);
Application.Current.Shutdown();
return;
}
private static bool IsAdministrator()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
// To run as admin, alter exe manifest file after building.
// Or create shortcut with "as admin" checked.
// Or ShellExecute(C# Process.Start) can elevate - use verb "runas".
// Or an elevate vbs script can launch programs as admin.
// (does not work: "runas /user:admin" from cmd-line prompts for admin pass)
Update: The app manifest way is preferred:
Right click project in visual studio, add, new application manifest file, change the file so you have requireAdministrator set as shown in the above.
A problem with the original way: If you put the restart code in app.xaml.cs OnStartup, it still may start the main window briefly even though Shutdown was called. My main window blew up if app.xaml.cs init was not run and in certain race conditions it would do this.
According to the article Chris Corio: Teach Your Apps To Play Nicely With Windows Vista User Account Control, MSDN Magazine, Jan. 2007, only ShellExecute checks the embedded manifest and prompts the user for elevation if needed, while CreateProcess and other APIs don't. Hope it helps.
See also: same article as .chm.
[PrincipalPermission(SecurityAction.Demand, Role = #"BUILTIN\Administrators")]
This will do it without UAC - no need to start a new process. If the running user is member of Admin group as for my case.
i know this is a very old post, but i just wanted to share my solution:
System.Diagnostics.ProcessStartInfo StartInfo = new System.Diagnostics.ProcessStartInfo
{
UseShellExecute = true, //<- for elevation
Verb = "runas", //<- for elevation
WorkingDirectory = Environment.CurrentDirectory,
FileName = "EDHM_UI_Patcher.exe",
Arguments = #"\D -FF"
};
System.Diagnostics.Process p = System.Diagnostics.Process.Start(StartInfo);
NOTE: If VisualStudio is already running Elevated then the UAC dialog won't show up, to test it run the exe from the bin folder.
You should use Impersonation to elevate the state.
WindowsIdentity identity = new WindowsIdentity(accessToken);
WindowsImpersonationContext context = identity.Impersonate();
Don't forget to undo the impersonated context when you are done.

Categories

Resources