How can I impersonate a webservice file (asmx) from code? - c#

Until recently, I've used the "<impersonate >" tag in web.config, followed by proper credentials.
Now I'm trying to add another asmx file, that will impersonate to a different account, and trying to do that from code.
Question is -
How to impersonate (on every request) from code in an asmx file (webservice) ?
(I'm using C#)
I guess the code should be in the ctor of the asmx class, but I'm not sure what the could should be.
I've googled thru many examples but haven't found a decent code that do what I wants.
Thank you in advance!

See sample code how you can do it:
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
[assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode = true)]
[assembly: PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]
public class ImpersonationDemo
{
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(
String lpszUsername,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
// Test harness.
// If you incorporate this code into a DLL, be sure to demand FullTrust.
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public static void Main(string[] args)
{
IntPtr tokenHandle = new IntPtr(0);
try
{
string userName, domainName;
// Get the user token for the specified user, domain, and password using the
// unmanaged LogonUser method.
// The local machine name can be used for the domain name to impersonate a user on this machine.
Console.Write("Enter the name of the domain on which to log on: ");
domainName = Console.ReadLine();
Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
userName = Console.ReadLine();
Console.Write("Enter the password for {0}: ", userName);
const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
tokenHandle = IntPtr.Zero;
// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser(
userName,
domainName,
Console.ReadLine(),
3,
LOGON32_PROVIDER_DEFAULT,
ref tokenHandle);
Console.WriteLine("LogonUser called.");
if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
Console.WriteLine("LogonUser failed with error code : {0}", ret);
throw new System.ComponentModel.Win32Exception(ret);
}
Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
Console.WriteLine("Value of Windows NT token: " + tokenHandle);
// Check the identity.
Console.WriteLine("Before impersonation: " + WindowsIdentity.GetCurrent().Name);
// Use the token handle returned by LogonUser.
WindowsIdentity newId = new WindowsIdentity(tokenHandle);
using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
{
// Check the identity. Here you shoul place code that will be executed on belaf of other login.
Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name);
GC.KeepAlive(impersonatedUser);
}
// Check the identity.
Console.WriteLine("After Undo: " + WindowsIdentity.GetCurrent().Name);
// Free the tokens.
if (tokenHandle != IntPtr.Zero)
CloseHandle(tokenHandle);
}
catch (Exception ex)
{
Console.WriteLine("Exception occurred. " + ex.Message);
}
}
}

If you have impersonate set to ON in your web.config you can specify a different credential via:
new System.Net.NetworkCredential("username", "password", "domain");
I have also found a good article How to impersonate a user given her token
It shows how to attach a diffrent WindowsIdentity to a given thread

Related

Copy file using impersonation and CopyFileEx from Kernel DLL?

I am using the following code to copy a file to a directory where only one X user has access, I am using impersonation but when I use it the CopyFileEx does not work, but I don't know why. if I remove the part of the impersonation it works correctly but I need it to be copied with a user X since in production it has to be like that.
ImpersonationUtils impersonation = new ImpersonationUtils();
var token = impersonation.LogonAsUser("User", "Domain", "pwd");
if (!IntPtr.Equals(token, IntPtr.Zero))
{
System.Security.Principal.WindowsImpersonationContext impersonatedUser = null;
var newIdentity = new System.Security.Principal.WindowsIdentity(token);
impersonatedUser = newIdentity.Impersonate();
bool result = CopyFileEx(filename, tempFilepath, new CopyProgressRoutine(this.CopyProgressHandler), IntPtr.Zero, cancelp, 0);
if (impersonatedUser != null)
impersonatedUser.Undo();
impersonation.LogonAsUserEnd(token);
}
Here is a class I wrote in the past to make operations under Impersonation,
Check out how the token is created inside DoWorkUnderImpersonation()
with the credentials and the required constants to LogonUser() of advapi32.dll.
The required operation is made inside the DoWork() method, add your copy files logic there.
Call the static method DoWorkUnderImpersonation() from out side
// Implementation of the Impersonation class
Impersonation.DoWorkUnderImpersonation("DOMAIN", "USER", "PASSWORD");
public static class Impersonation
{
// obtains user token
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
// closes open handes returned by LogonUser
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
public static void DoWorkUnderImpersonation(string _domain, string _userName, string _password)
{
//elevate privileges before doing file copy to handle domain security
WindowsImpersonationContext impersonationContext = null;
IntPtr userHandle = IntPtr.Zero;
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
string domain = _domain;
string user = _userName;
string password = _password;
try
{
Debug.WriteLine("windows identify before impersonation: " + WindowsIdentity.GetCurrent().Name);
// if domain name was blank, assume local machine
if (domain == "")
domain = System.Environment.MachineName;
// Call LogonUser to get a token for the user
bool loggedOn = LogonUser(user,
domain,
password,
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
ref userHandle);
if (!loggedOn)
{
Debug.WriteLine("Exception impersonating user, error code: " + Marshal.GetLastWin32Error());
return;
}
// Begin impersonating the user
using (impersonationContext = WindowsIdentity.Impersonate(userHandle))
{
Debug.WriteLine("Main() windows identify after impersonation: " + WindowsIdentity.GetCurrent().Name);
//run the program with elevated privileges (like file copying from a domain server)
DoWork();
}
}
catch (Exception ex)
{
Console.Write("Exception impersonating user: " + ex.Message);
}
finally
{
// Clean up
if (impersonationContext != null)
{
impersonationContext.Undo();
}
if (userHandle != IntPtr.Zero)
{
CloseHandle(userHandle);
}
}
}
private static void DoWork()
{
try
{
// MAKE YOUR REQUIRED TASK HERE UNDER IMPERSONATION
}
catch (Exception ex)
{
Console.Write("error in Impersonation.DoWork() executing a task: " + ex.Message);
}
}
}

.NET 4.5 File.Copy ok, but file does not exist

strange behaviour in our production environment, these days.
I have the following:
try {
var sourcePath = ... // my source path
var destinationPath = ... // guess what? You're right, my destination path
File.Copy(sourcePath, destinationPath);
Log.Debug(string.Format("Image {0} copied successfully", imagename));
}
catch(Exception e) {
// exception handling
}
Both source and destination path are on a network share, a folder on an other (virtual) machine with a large number of files (> 500k).
From the last 2 days, the code above runs, logs the last line (the one stating that image have been copied), but if I check in the destination folder, the supposed destination file does not exist.
I thought that for any I/O error File.Copy would raise an exception, so this thing is driving me mad.
Please note that other code parts that write files in that folder are working correctly. Also, note that all files names are unique (business code not included for brevity is making sure of that), and I think an exception would be thrown or the file would be at least overwritten, in that case.
Has anyone faced the same problem? Possible causes? Any solution?
EDIT 2016-07-01 15:12 (GMT+0200)
Ok, folks, apparently files aren't being deleted at all... simply for apparently no reason at all, after they are copied they're left open in read+write mode from the client connected user.
I found this trying running the reader application on my computer, in debug mode, and trying to open one of the files i knew that were copied recently.
I got an exception stating that the file was opened by someone else, and that seemed weird to me.
Opening Computer Management in the remote server (the one which stores the files), then going to Shared Folders > Open Files, I found that the file was left open in read+write mode from the impersonated user that the web application that copies the files is impersonating to do that job.
Also a whole bunch of other files where in the same conditions, and many others where open in read mode.
I found also in Shared Folders > Sessions, an astronomical long list of session of the impersonated user, all with long idle time.
Since impersonation is used only to copy the files, and then is disposed, I shouldn't expect that, right?
I think maybe there is a problem in the way we impersonate the user during file copy, linked to the large number of files in the destination folder.
I'll check that.
END EDIT
Thanks,
Claudio Valerio
Found a solution, I think.
My problem was the code used for impersonating the user with write permissions on the destination folder.
(In my defence, all this project have been inherited from previous software company, and it's pretty massive, so keeping an eye on everything isn't that easy)
The impersonation process was wrapped in a class implementing IDisposable
public class Impersonator :
IDisposable
{
public Impersonator()
{
string userName = // get username from config
string password = // get password from config
string domainName = // get domain from config
ImpersonateValidUser(userName, domainName, password);
}
public void Dispose()
{
UndoImpersonation();
}
[DllImport("advapi32.dll", SetLastError = true)]
private static extern int LogonUser(
string lpszUserName,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int DuplicateToken(
IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern bool CloseHandle(
IntPtr handle);
private const int LOGON32_LOGON_INTERACTIVE = 2;
private const int LOGON32_PROVIDER_DEFAULT = 0;
private void ImpersonateValidUser(
string userName,
string domain,
string password)
{
WindowsIdentity tempWindowsIdentity = null;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
try
{
if (RevertToSelf())
{
if (LogonUser(
userName,
domain,
password,
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
finally
{
if (token != IntPtr.Zero)
{
CloseHandle(token);
}
if (tokenDuplicate != IntPtr.Zero)
{
CloseHandle(tokenDuplicate);
}
}
}
private void UndoImpersonation()
{
if (impersonationContext != null)
{
impersonationContext.Undo();
}
}
private WindowsImpersonationContext impersonationContext = null;
}
This class is used this way:
using(new Impersonator())
{
// do stuff with files in here
}
My suspect was that closing the handlers of the impersonated user, somehow, it could break something in the way that windows handles file open by the impersonated user through a network share, as in my case, leaving shared files open in read+write mode, preventing any other process/user to open them.
I modified the Impersonator class as follows:
public class Impersonator :
IDisposable
{
public Impersonator()
{
string userName = // get username from config
string password = // get password from config
string domainName = // get domain from config
ImpersonateValidUser(userName, domainName, password);
}
public void Dispose()
{
UndoImpersonation();
impersonationContext.Dispose();
}
[DllImport("advapi32.dll", SetLastError = true)]
private static extern int LogonUser(
string lpszUserName,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int DuplicateToken(
IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern bool CloseHandle(
IntPtr handle);
private const int LOGON32_LOGON_INTERACTIVE = 2;
private const int LOGON32_PROVIDER_DEFAULT = 0;
private void ImpersonateValidUser(
string userName,
string domain,
string password)
{
WindowsIdentity tempWindowsIdentity = null;
token = IntPtr.Zero;
tokenDuplicate = IntPtr.Zero;
try
{
if (RevertToSelf())
{
if (LogonUser(
userName,
domain,
password,
LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,
ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
else
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
finally
{
}
}
private void UndoImpersonation()
{
try
{
if (impersonationContext != null)
{
impersonationContext.Undo();
}
}
finally
{
if (token != IntPtr.Zero)
{
CloseHandle(token);
}
if (tokenDuplicate != IntPtr.Zero)
{
CloseHandle(tokenDuplicate);
}
}
}
private WindowsImpersonationContext impersonationContext = null;
private IntPtr token;
private IntPtr tokenDuplicate;
}
Basically I moved the handlers closing in the UndoImpersonation method. Also I had a doubt about leaving the impersonationContext not explicitly disposed, si I disposed it in the Dispose method of the Impersonator class.
Since I put in production this update, I hadn't any other issue with this code, and not any other shared file left open in read+write mode on the destination server.
Maybe not the optimal solution (I still have a whole bunch of sessions in Computer Management > Shared Folders > Sessions, but this seems not harming the system, for now.
If anyone have some additional comment, suggestion or depth study about this situation, I will be please to read.
Thanks,
Claudio

Impersonation on windows 7

I've been working on some application that copy files trough a local domain. When I try to copy files with the application on windows XP with an account with absolutely no right which is impersonating an account with all right, everything is done perfectly. But, when I take the same account wich is impersonating the same account as above on windows 7 the application return "access denied" on the first line
I took the same snippet code on Impersonate msdn but here's mine with the fileSeeker function:
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
// Test harness.
// If you incorporate this code into a DLL, be sure to demand FullTrust.
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public impersonateSetting(string userName, string domainName, string password, string pathToSeek)
{
SafeTokenHandle safeTokenHandle;
try
{
const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser(userName, domainName, password,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
out safeTokenHandle);
Console.WriteLine("LogonUser called.");
if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
Console.WriteLine("LogonUser failed with error code : {0}", ret);
throw new System.ComponentModel.Win32Exception(ret);
}
using (safeTokenHandle)
{
Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
Console.WriteLine("Value of Windows NT token: " + safeTokenHandle);
// Check the identity.
Console.WriteLine("Before impersonation: "
+ WindowsIdentity.GetCurrent().Name);
// Use the token handle returned by LogonUser.
using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
{
using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
{
// Check the identity.
Console.WriteLine("After impersonation: "
+ WindowsIdentity.GetCurrent().Name);
fileRunner.fileSeeker(pathToSeek, true);
}
}
// Releasing the context object stops the impersonation
// Check the identity.
Console.WriteLine("After closing the context: " + WindowsIdentity.GetCurrent().Name);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception occurred. " + ex.Message);
}
}
}
public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
private SafeTokenHandle()
: base(true)
{
}
[DllImport("kernel32.dll")]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr handle);
protected override bool ReleaseHandle()
{
return CloseHandle(handle);
}
fileSeeker function:
public static void fileSeeker(string paramFrom, bool copySub)
{
DirectoryInfo dir = new DirectoryInfo(paramFrom);
DirectoryInfo[] dirs = dir.GetDirectories();
try
{
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(paramFrom, file.Name);
try
{
Console.WriteLine("Accessing: " + temppath);
}
catch
{
Console.WriteLine("Cant Access to " + temppath);
}
}
if (copySub)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(paramFrom, subdir.Name);
fileSeeker(subdir.FullName, copySub);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
}
Thanks for your help !
If it's failing here, FileInfo[] files = dir.GetFiles();, chances are the account you impersonated doesn't have permission to the dir path on the Win7 machine where this is running, make sure that this account has access to the source path first, the impersonation code seems fine

C#: Start process as the "real" administrator with hard coded privileges

I need to install different setups silently with administrator privileges.
I have to hard code the privileges because the users donĀ“t know username and password to install the setups themselfes.
I have tried two different approaches.
ProcessStartInfo with UserName, Password and UseShellExecute = false.
User Impersonation with
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser(...);
In both scenarios windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator) returns false
and my setups do not run because of insufficient rights.
Strange behavior: LogonUser always returns true, even with invalid credentials.
Here is the impersonation class:
namespace BlackBlade.Utilities
{
/// <summary>
/// Quelle: http://www.blackbladeinc.com/en-us/community/blogs/archive/2009/08/10/runas-in-c.aspx
/// </summary>
public class SecurityUtilities
{
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser(string lpszUserName, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
public delegate void RunAsDelegate();
public static void RunAs(RunAsDelegate methodToRunAs, string username, string password)
{
string userName;
string domain;
if (username.IndexOf('\\') > 0)
{
//a domain name was supplied
string[] usernameArray = username.Split('\\');
userName = usernameArray[1];
domain = usernameArray[0];
}
else
{
//there was no domain name supplied
userName = username;
domain = ".";
}
RunAs(methodToRunAs, userName, password, domain);
}
public static void RunAs(RunAsDelegate methodToRunAs, string username, string password, string domain)
{
IntPtr userToken;
WindowsIdentity adminIdentity = null;
WindowsImpersonationContext adminImpersonationContext = null;
try
{
if (LogonUser(username, string.IsNullOrEmpty(domain) ? "." : domain, password, 9, 0, out userToken))
{
//the impersonation suceeded
adminIdentity = new WindowsIdentity(userToken);
adminImpersonationContext = adminIdentity.Impersonate();
// todo: Entfernen.
WindowsPrincipal p = new WindowsPrincipal(adminIdentity);
MessageBox.Show(p.IsInRole(WindowsBuiltInRole.Administrator).ToString());
//run the delegate method
//methodToRunAs();
}
else
throw new Exception(string.Format("Could not impersonate user {0} in domain {1} with the specified password.", username, domain));
}
catch (Exception se)
{
int ret = Marshal.GetLastWin32Error();
if (adminImpersonationContext != null)
adminImpersonationContext.Undo();
throw new Exception("Error code: " + ret.ToString(), se);
}
finally
{
//revert to self
if (adminImpersonationContext != null)
adminImpersonationContext.Undo();
}
}
}
}
Add a manifest to the process you are starting with RunAs to request elevation.
Edit: First, start a process using your known administrator credentials, either with LogonUser/CreateProcessAsUser or with CreateProcessWithLogon. Then check for real admin rights (maybe UAC is turned off) and if necessary, have this process (running as non-elevated administrator) start another copy of itself with ShellExecuteEx using the runas verb. This is the only way. UAC was explicitly designed to prohibit elevation without user confirmation.
Users will have to confirm the elevation, unless UAC is turned off. For better user experience (less scary message box) get a code signing certificate and sign this executable.
Use Group Policy to roll out the MSI or EXE installer.
Alternatively use Task Scheduler to run the installer as the Local System account.
Have you tried setting dwLogonType to 2 instead of 9?
http://msdn.microsoft.com/en-us/library/windows/desktop/bb540756(v=vs.85).aspx
Here's a code sample which works for me:
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;
WindowsImpersonationContext impersonationContext;
[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);

C# Web service: want to execute shell command as Admin (or higher priv.)

I have a web service which needs to execute a command on the server it's sitting on. Specifically, I'm running the "net start [certain service]" command. The problem lies in the permissions... the web service is running as NETWORK SERVICE, which doesn't have the appropriate permissions to execute this command. Is there a way (possibly using Windows.Security) such that I can execute this as a higher privileged user.
** The command executes fine when ran locally, but this needs to be executed through the service (the point of the service...)
When attempting to impersonate a user, (using MSDN example, http://msdn.microsoft.com/en-us/library/chf6fbt4.aspx):
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
static public string Impersonate(string userName, string domainName, string password)
{
IntPtr tokenHandle = new IntPtr(0);
IntPtr dupeTokenHandle = new IntPtr(0);
string output = "";
try
{
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
output += "Set Token to ptrzero";
tokenHandle = IntPtr.Zero;
output += "getting return value";
//Call LogonUser to obtain a handle to an access token
bool returnValue = LogonUser(userName, domainName,
password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref tokenHandle);
output += "LogonUser called";
if (!returnValue)
{
int ret = Marshal.GetLastWin32Error();
output += "\n LogonUser failed with error code: " + ret.ToString();
}
else
output += "\nLogonUser succeeded!";
//check the identity:
output += "\n current: " + WindowsIdentity.GetCurrent().Name;
WindowsIdentity newId = new WindowsIdentity(tokenHandle);
WindowsImpersonationContext impersonatedUser = newId.Impersonate();
//Check:
output += "\n after: " + WindowsIdentity.GetCurrent().Name;
}
catch (Exception ex)
{
output += ex.ToString();
}
return output;
}
I call the function to perform a shell execution, (Prior to execution I check if the current user is correct; which says the "current user" is my administrative-privileged account), but it still won't execute the same commands.
You should impersonate an admin user: Run Code as a different user (C#)
By the way, you shouldn't need to shell out to the net command. The ServiceController class can start and stop services.

Categories

Resources