Unable to impersonate user in an elapsed Timer event - c#

Within a windows service I am facing an issue with impersonating a user.
The impersonation finds place in a System.Timers.Timer Elapsed event.
The timer ticks every 3 seconds. When the imersonation fails and I get "Unable to impersonate user" I do a retry by restarting the timer and it continues and impersonation goes on.
After 3 to 4 days of running this service the impersonation fails again and a retry doesn't work and the application is stuck within the elapsed event.
Is it possible that the Timer ran out of threads?(Threadpool)
How can I prevent a failed impersonation or how do I handle this?
Impersonation code :
[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);
private static IntPtr tokenHandle = new IntPtr(0);
private static WindowsImpersonationContext impersonatedUser;
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
// If you incorporate this code into a DLL, be sure to demand that it
// runs with FullTrust.
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public void Impersonate(string domainName, string userName, string password)
{
//try
{
// Use the unmanaged LogonUser function to get the user token for
// the specified user, domain, and password.
const int LOGON32_PROVIDER_DEFAULT = 0;
// Passing this parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
tokenHandle = IntPtr.Zero;
// ---- Step - 1
// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser(userName,domainName,password,LOGON32_LOGON_INTERACTIVE,LOGON32_PROVIDER_DEFAULT,ref tokenHandle);
// tokenHandle - new security token
if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(ret);
}
// ---- Step - 2
WindowsIdentity newId = new WindowsIdentity(tokenHandle);
// ---- Step - 3
impersonatedUser = newId.Impersonate();
}
}
// Stops impersonation
public void Undo()
{
impersonatedUser.Undo();
// Free the tokens.
if (tokenHandle != IntPtr.Zero)
CloseHandle(tokenHandle);
}
Timer code:
void polling_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
StopPolling();
//doing some stuff some impersonation
StartPolling();
}
catch (Exception ex)
{
retries++;
if (retries < 10)
{
StartPolling();
}
}
}

Related

Accessing Third Party Network drive when using Azure Websites

I am having problems trying to read a file that is stored on a network drive when hosting my website/request on a azure website.
The code works testing on a local machine and it also works on a Dedicated server that we have with another client and have full control of but it gets the following error when we try to read the file.
Access to the path '\xxx.xxx.xxx.xxx\abc\abc.xml' is denied.
I wanted to know if Azure was locked down to prevent this behaviour that I didn't know about. Maybe ports closed or something.
The code I am using
if (impersonate.impersonateValidUser("username", "domain.com", "password"))
{
message = "impersonate ok";
if (!System.IO.File.Exists(file))
{
message = "no file";
impersonate.undoImpersonation();
}
using (StreamReader reader = File.OpenText(file))
{
message = "";
XmlSerializer deserializer = new XmlSerializer(typeof(TextModeSchema));
schema = (TextModeSchema)deserializer.Deserialize(reader);
reader.Close();
}
}
which is using a basic Impersonate class that we use in alot of places
public class Impersonate : IDisposable
{
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_LOGON_NETWORK = 3;
public const int LOGON32_LOGON_BATCH = 4;
public const int LOGON32_LOGON_SERVICE = 5;
public const int LOGON32_LOGON_UNLOCK = 7;
public const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8;
public const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
public const int LOGON32_PROVIDER_DEFAULT =0;
public const int LOGON32_PROVIDER_WINNT35 =1;
public const int LOGON32_PROVIDER_WINNT40 =2;
public const int LOGON32_PROVIDER_WINNT50 = 3;
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);
public bool impersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_NEW_CREDENTIALS,
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);
return false;
}
public void undoImpersonation()
{
impersonationContext.Undo();
}
public void Dispose()
{
impersonationContext.Undo();
GC.Collect();
}
}
If this is not allowed on azure, does anyone know of a way we can get around it without having to set up a full Virtual machine? I would like to keep with a azure website/webapp ideally.
Is this on a web role, worker role or a web application? I know that in case of a role, the remote host in your scenario has to be on the same private network than you role (It may also be true for a web app). Also, we had a similar scenario where we decided to use Azure Files which allows mounting shares on a role which you might want to try. http://blogs.msdn.com/b/windowsazurestorage/archive/2014/05/12/introducing-microsoft-azure-file-service.aspx

Impersonation causing unhandled exception

I have a C# windows application that I need to impersonate a userid other than the one that the user logged on with when I access files on a file share. I use impersonation to switch to this user and then switch back. I also need to revert back to the logged on user to access local files. I get a System.ExecutionEngineException that is not being caught by the application and it just stops. Here is the code. Any ideas why I am getting this error or suggestions on how to do it better.
Edit: The application is using the XAF framework by DevExpress.
public static class Impersonation
{
#region Fields
public static WindowsImpersonationContext newUser;
public static string domain;
public static string userName;
public static string password;
#endregion
// group type enum
private enum SECURITY_IMPERSONATION_LEVEL : int
{
SecurityAnonymous = 0,
SecurityIdentification = 1,
SecurityImpersonation = 2,
SecurityDelegation = 3
}
// obtains user token
[DllImport("advapi32.dll", SetLastError = true)]
private 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)]
private extern static bool CloseHandle(IntPtr handle);
// creates duplicate token handle
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
#region Methods
public static void RevertUser()
{
newUser.Undo();
}
#region ImpersonateApexApplicationUser
/// <summary>
/// Attempts to impersonate a user. If successful, returns
/// a WindowsImpersonationContext of the new users identity.
/// </summary>
/// <param name="sUsername">Username you want to impersonate</param>
/// <param name="sDomain">Logon domain</param>
/// <param name="sPassword">User's password to logon with</param></param>
/// <returns></returns>
public static void ImpersonateApexApplicationUser()
{
// initialize tokens
IntPtr pExistingTokenHandle = new IntPtr(0);
IntPtr pDuplicateTokenHandle = new IntPtr(0);
pExistingTokenHandle = IntPtr.Zero;
pDuplicateTokenHandle = IntPtr.Zero;
try
{
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
if (!LogonUser(userName, domain, Encryption.Decrypt(password), LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle))
throw new Exception(string.Format("LogonUser() failed with error code {0}", Marshal.GetLastWin32Error()));
else
if (!DuplicateToken(pExistingTokenHandle, (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, ref pDuplicateTokenHandle))
{
int errorCode = Marshal.GetLastWin32Error();
CloseHandle(pExistingTokenHandle); // close existing handle
throw new Exception(string.Format("DuplicateToken() failed with error code: {0}", errorCode));
}
else
{
// create new identity using new primary token
WindowsIdentity newId = new WindowsIdentity(pDuplicateTokenHandle);
newUser = newId.Impersonate();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
// close handle(s)
if (pExistingTokenHandle != IntPtr.Zero)
CloseHandle(pExistingTokenHandle);
if (pDuplicateTokenHandle != IntPtr.Zero)
CloseHandle(pDuplicateTokenHandle);
}
}
#endregion
}
I call it like this once at the beginning of the program:
Impersonation.domain = "xxxx";
Impersonation.userName = "xxxx;
Impersonation.password = "xxxx";
Impersonation.ImpersonateApexApplicationUser();
and then:
Impersonation.ImpersonateApexApplicationUser();
//file share access code
Impersonation.RevertUser();

How to logon programmatically on a Windows machine

It is possible to use the logonuser function for logging onto a domain.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa378184(v=vs.85).aspx
I want to logon programatically from C# onto a windows machine which is not part of any domain. How to achieve this?
I am using the following Program to logon :
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
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);
internal void validateusercredentials(string username, string password, string hostname)
{
assert.isnotnull(username);
intptr tokenhandle = new intptr(0);
windowsidentity windowsid = null;
try
{
const int logon32_provider_default = 0;
const int logon32_logon_network = 3;
tokenhandle = intptr.zero;
bool success = logonuser(username, ".", password, logon32_logon_network,
logon32_provider_default, ref tokenhandle);
console.writeline("the return value of logon user is " + success);
if (!success)
{
int lastwindowserror = marshal.getlastwin32error();
if (lastwindowserror == error_logon_failure)
{
string message = string.format("invalid credentials supplied for user {0}", username);
console.writeline(lastwindowserror);
throw new invalidcredentialexception(message);
}
}
}
catch (exception e)
{
console.writeline(e.message);
trace.traceerror(e.message);
throw;
}
finally
{
if (tokenhandle != intptr.zero)
{
closehandle(tokenhandle);
}
if (windowsid != null)
{
windowsid.dispose();
windowsid = null;
}
}
}
If the machine is not part of your domain, you cannot use your domain credentials.
If you have a local account, you can instead use the local name of the computer as domain name and your local user and password as user and password.

How to make the ActiveDirectoryMembershipProvider accept an empty password?

We are developing a web application that uses forms authentication and the ActiveDirectoryMembershipProvider to authenticate users against the Active Directory. We soon found out that the provider does not allow a blank/empty password to be specified, even though this is perfectly legal in the Active Directory (provided a preventative password policy is not in place).
Courtesy of reflector:
private void CheckPassword(string password, int maxSize, string paramName)
{
if (password == null)
{
throw new ArgumentNullException(paramName);
}
if (password.Trim().Length < 1)
{
throw new ArgumentException(SR.GetString("Parameter_can_not_be_empty", new object[] { paramName }), paramName);
}
if ((maxSize > 0) && (password.Length > maxSize))
{
throw new ArgumentException(SR.GetString("Parameter_too_long", new object[] { paramName, maxSize.ToString(CultureInfo.InvariantCulture) }), paramName);
}
}
Short of writing our own custom Provider, is there any way to override this functionality using the magic of .NET?
I don't beleive you could change this behaviour without creating a derived class and overiding every method that calls the private CheckPassword method. I would not recomend this option however, i would recomend that you review your design and question whether it is approriate to allow blank passwords in your application. Whilst they are valid in AD it is unusual for this to be allowed in practice and it does impact other things in a windows network, e.g. i think the default settings for network file shares disallow any user with a blank password from connecting to the share.
You could perhaps look at using impersonation but i don't know if you will have the same issue. If it's to authorise a user, then you could use impersonation to try and "impersonate" the user on the machine. I don't know if it helps but I was doing something similar to this the other week. Have put the code below if any of this helps.. :)
using System;
using System.Runtime.InteropServices;
public partial class Test_Index : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e)
{
IntPtr ptr = IntPtr.Zero;
if (LogonUser("USERNAME", "", "LEAVE-THIS-BLANK", LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, ref ptr))
{
using (System.Security.Principal.WindowsImpersonationContext context = new System.Security.Principal.WindowsIdentity(ptr).Impersonate())
{
try
{
// Do do something
}
catch (UnauthorizedAccessException ex)
{
// failed to do something
}
// un-impersonate user out
context.Undo();
}
}
else
{
Response.Write("login fail");
}
}
#region imports
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public extern static bool DuplicateToken(IntPtr existingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr duplicateTokenHandle);
#endregion
#region logon consts
// logon types
const int LOGON32_LOGON_INTERACTIVE = 2;
const int LOGON32_LOGON_NETWORK = 3;
const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
// logon providers
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_PROVIDER_WINNT50 = 3;
const int LOGON32_PROVIDER_WINNT40 = 2;
const int LOGON32_PROVIDER_WINNT35 = 1;
#endregion }

Open a shared file under another user and domain?

I have a C# console application that needs to read a shared file on a machine in another domain.
When the application tries to access the file an exception occurs as the local user does not have permission to access the shared resource.
Currently I overcome this problem manually by open the shared folder from the run and put the username and password into the windows authentication dialog then run the application.
How can I do it programmatically?
a) p/invoke LogonUser with LOGON32_LOGON_NEW_CREDENTIALS and create a new WindowsIdentity with the new token, then use normal file access.
b) p/invoke WNetAddConnection3. Be advised that this makes your remote share accessible to every other process on your machine.
c) WMI via System.Management and CIM_DataFile; you won't even need p/invoke. System.Management lets you specify credentials for remote machine.
I used the point "a" as Anton suggested, I developed two versions for one class, the first one using the Win32 APIs, and the second uses the WindowsIdentity class.
Version 1:
class UserImpersonation : IDisposable
{
[DllImport("advapi32.dll")]
public 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)]
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);
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
WindowsImpersonationContext wic;
string _userName;
string _domain;
string _passWord;
public UserImpersonation(string userName, string domain, string passWord)
{
_userName = userName;
_domain = domain;
_passWord = passWord;
}
public bool ImpersonateValidUser()
{
WindowsIdentity wi;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUser(_userName, _domain, _passWord, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
wi = new WindowsIdentity(tokenDuplicate);
wic = wi.Impersonate();
if (wic != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
{
CloseHandle(token);
}
if (tokenDuplicate != IntPtr.Zero)
{
CloseHandle(tokenDuplicate);
}
return false;
}
#region IDisposable Members
public void Dispose()
{
if (wic != null)
{
wic.Dispose();
}
RevertToSelf();
}
#endregion
}
Version2 (from MSDN with small changes):
class UserImpersonation2 : IDisposable
{
[DllImport("advapi32.dll")]
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 static extern bool CloseHandle(IntPtr handle);
WindowsImpersonationContext wic;
IntPtr tokenHandle;
string _userName;
string _domain;
string _passWord;
public UserImpersonation2(string userName, string domain, string passWord)
{
_userName = userName;
_domain = domain;
_passWord = passWord;
}
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
public bool ImpersonateValidUser()
{
bool returnValue = LogonUser(_userName, _domain, _passWord,
LOGON32_LOGON_INTERACTIVE, 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);
return false;
}
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);
wic = newId.Impersonate();
// Check the identity.
Console.WriteLine("After impersonation: "
+ WindowsIdentity.GetCurrent().Name);
return true;
}
#region IDisposable Members
public void Dispose()
{
if(wic!=null)
{
wic.Undo();
}
if (tokenHandle != IntPtr.Zero)
{
CloseHandle(tokenHandle);
}
}
#endregion
}
How to use (both are the same):
const string file = #"\\machine\test\file.txt";
using (UserImpersonation user = new UserImpersonation("user", "domain", "password"))
{
if (user.ImpersonateValidUser())
{
StreamReader reader = new StreamReader(file);
Console.WriteLine(reader.ReadToEnd());
reader.Close();
}
}
From memory you'll need to use a Windows API call and login as a user on the other domain. See this link for an example.
Another idea could be to use the RunAs command line argument to read the file and save it into a file on your local domain/server.

Categories