System.IO alternative user credentials? Is it possible?

G

Guest

I am trying to figure out how to pass set of credentials to System.IO

Challenge is:
App is running under one set of credentials, but via GUI user have a chance
to enter another set. I would like to be able to use supplied credentials
with System.IO versus using default credentials that app is running under.

So far I am forced to use WMI which is less convenient and slower then
System.IO, but it's providing me with "Connection Options"

Any suggestions are welcome
 
G

Guest

You need to call the LogonUser api function in advapi.dll in the windows api
to get a security token (as an IntPtr), then you need to call DuplicateToken
(cant remember the dll but I think its Kernal32.dll) to make it a primary
token which you can then use to start impersonating the user with the
WindowsIdentity class in the framework. When impersonating, all the code the
runs under the windows identity your impersonating until you call
ImpersonationContext.Undo

I know this isnt a full answer but it should be enough to run a few
fruitfull searches


Ciaran O'Donnell
 
K

Kevin Spencer

Here's a managed class (Impersonator) I wrote that presents a fairly easy
impersonation interface. It employs the Windows API, including both
kernel32.dll and advapi32.dll, but does not expose the unmanaged activity.
It simply has 2 methods and 2 constructors:

Impersonator() // Parameterless constructor

// Constructor. Attempts to impersonate user with domain credentials
Impersonator(string domain, string userName, string password)

// Attempts to impersonate user with domain credentials
ImpersonateValidUser(string domain, string userName, string password)

UndoImpersonation() // Reverts to original process Identity

The UndoImpersonation() method is called by the Finalizer, in case it is not
called in the code.

******************************************************************
/// <summary>
/// Provides Impersonation capability.
/// </summary>
/// <remarks>This class can impersonate any user in a domain. The
/// parameterized Constructor will attempt to impersonate a User according
to
/// the Domain, User Name, and Password passed to it. In addition, the
/// <var>ImpersonateValidUser()</var> can impersonate, or change the
impersonation
/// from one user to another. The <var>UndoImpersonation()</var> method
reverts the
/// application impersonation context to its original state.</remarks>
/// <permission cref="System.Security.Permissions">Requires FullTrust
/// for this assembly</permission>
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public class Impersonator
{
private bool _Impersonated = false;
/// <summary type="System.Boolean">
/// Is this process impersonating?
/// </summary>
public bool Impersonated
{
get { return _Impersonated; }
}


// Set up Impersonation via InterOp
private const int LOGON32_LOGON_INTERACTIVE = 2;
private const int LOGON32_PROVIDER_DEFAULT = 0;

//need to import from COM via InteropServices to do the impersonation when
saving the details
private System.Security.Principal.WindowsImpersonationContext
ImpersonationContext;

[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport("advapi32.dll", CharSet=CharSet.Auto)]
private static extern int LogonUser(String lpszUserName, String
lpszDomain,String lpszPassword,int dwLogonType, int dwLogonProvider,ref
IntPtr phToken);

[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport("advapi32.dll",
CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
private extern static int DuplicateToken(IntPtr hToken, int
impersonationLevel, ref IntPtr hNewToken);

[DllImport("kernel32.dll",
CharSet=System.Runtime.InteropServices.CharSet.Auto)]
private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr
lpSource,
int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr
*Arguments);

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
private extern static bool CloseHandle(IntPtr handle);

/// <summary mod="unsafe static" type="System.String">
/// Formats and returns an error message
/// corresponding to the input <paramref name="errorCode"/>.
/// </summary>
/// <param name="errorCode">A Win32 Error code</param>
/// <returns>The string translation of the <paramref
name="errorCode"/></returns>
public unsafe static string GetErrorMessage(int errorCode)
{
int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;

//int errorCode = 0x5; //ERROR_ACCESS_DENIED
//throw new System.ComponentModel.Win32Exception(errorCode);

int messageSize = 255;
String lpMsgBuf = "";
int dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS;

IntPtr ptrlpSource = IntPtr.Zero;
IntPtr prtArguments = IntPtr.Zero;

int retVal = FormatMessage(dwFlags, ref ptrlpSource, errorCode, 0, ref
lpMsgBuf, messageSize, &prtArguments);
if (0 == retVal)
{
throw new Exception("Failed to format message for error code " +
errorCode + ". ");
}
return lpMsgBuf;
}

/// <summary>
/// Constructor. Initializes <var>Domain</var>, <var>UserName</var>, and
/// <var>Password</var>
/// </summary>
/// <param name="domain">Domain of impersonated User account</param>
/// <param name="userName">User name of impersonated User
account</param>
/// <param name="password">Password of impersonated User account</param>
public Impersonator(string domain, string userName, string password)
{
ImpersonateValidUser(userName, domain, password);
}

/// <summary>
/// Constructor.
/// </summary>
public Impersonator()
{
}

/// <summary type="System.Boolean">
/// Impersonate a User
/// </summary>
/// <param name="userName">User Name of User to impersonate</param>
/// <param name="domain">Domain of User to impersonate</param>
/// <param name="password">Password of User to impersonate</param>
/// <returns>true if Successful, false if not</returns>
public bool ImpersonateValidUser(String userName, String domain, String
password)
{
WindowsIdentity _TempWindowsIdentity;
IntPtr _Token = IntPtr.Zero;
IntPtr _TokenDuplicate = IntPtr.Zero;

try
{
if (_Impersonated) UndoImpersonation();

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();
if (ImpersonationContext != null)
_Impersonated = true;
else
_Impersonated = false;
}
else
_Impersonated = false;
}
else
_Impersonated = false;
return _Impersonated;
}
catch (Exception ex)
{
Utilities.HandleError(ex);
return false;
}
}


/// <summary>
/// Revert back to local identity
/// </summary>
public void UndoImpersonation()
{
if (ImpersonationContext != null) ImpersonationContext.Undo();
ImpersonationContext = null;
}

/// <summary mod="~">
/// Destructor. Ensures that Impersonation is cancelled.
/// </summary>
~Impersonator()
{
UndoImpersonation();
}
}

--
HTH,

Kevin Spencer
Microsoft MVP
Chicken Salad Surgery

What You Seek Is What You Get.
 
G

Guest

W.O.W. (!)

Thanks. It will take me a little while to dog through the code. I do not
like to use code I done completely understand, and it's a lot of new idea
here for me to dig through.

Thank you


Kevin Spencer said:
Here's a managed class (Impersonator) I wrote that presents a fairly easy
impersonation interface. It employs the Windows API, including both
kernel32.dll and advapi32.dll, but does not expose the unmanaged activity.
It simply has 2 methods and 2 constructors:

Impersonator() // Parameterless constructor

// Constructor. Attempts to impersonate user with domain credentials
Impersonator(string domain, string userName, string password)

// Attempts to impersonate user with domain credentials
ImpersonateValidUser(string domain, string userName, string password)

UndoImpersonation() // Reverts to original process Identity

The UndoImpersonation() method is called by the Finalizer, in case it is not
called in the code.

******************************************************************
/// <summary>
/// Provides Impersonation capability.
/// </summary>
/// <remarks>This class can impersonate any user in a domain. The
/// parameterized Constructor will attempt to impersonate a User according
to
/// the Domain, User Name, and Password passed to it. In addition, the
/// <var>ImpersonateValidUser()</var> can impersonate, or change the
impersonation
/// from one user to another. The <var>UndoImpersonation()</var> method
reverts the
/// application impersonation context to its original state.</remarks>
/// <permission cref="System.Security.Permissions">Requires FullTrust
/// for this assembly</permission>
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public class Impersonator
{
private bool _Impersonated = false;
/// <summary type="System.Boolean">
/// Is this process impersonating?
/// </summary>
public bool Impersonated
{
get { return _Impersonated; }
}


// Set up Impersonation via InterOp
private const int LOGON32_LOGON_INTERACTIVE = 2;
private const int LOGON32_PROVIDER_DEFAULT = 0;

//need to import from COM via InteropServices to do the impersonation when
saving the details
private System.Security.Principal.WindowsImpersonationContext
ImpersonationContext;

[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport("advapi32.dll", CharSet=CharSet.Auto)]
private static extern int LogonUser(String lpszUserName, String
lpszDomain,String lpszPassword,int dwLogonType, int dwLogonProvider,ref
IntPtr phToken);

[SuppressUnmanagedCodeSecurityAttribute()]
[DllImport("advapi32.dll",
CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
private extern static int DuplicateToken(IntPtr hToken, int
impersonationLevel, ref IntPtr hNewToken);

[DllImport("kernel32.dll",
CharSet=System.Runtime.InteropServices.CharSet.Auto)]
private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr
lpSource,
int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr
*Arguments);

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
private extern static bool CloseHandle(IntPtr handle);

/// <summary mod="unsafe static" type="System.String">
/// Formats and returns an error message
/// corresponding to the input <paramref name="errorCode"/>.
/// </summary>
/// <param name="errorCode">A Win32 Error code</param>
/// <returns>The string translation of the <paramref
name="errorCode"/></returns>
public unsafe static string GetErrorMessage(int errorCode)
{
int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;

//int errorCode = 0x5; //ERROR_ACCESS_DENIED
//throw new System.ComponentModel.Win32Exception(errorCode);

int messageSize = 255;
String lpMsgBuf = "";
int dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS;

IntPtr ptrlpSource = IntPtr.Zero;
IntPtr prtArguments = IntPtr.Zero;

int retVal = FormatMessage(dwFlags, ref ptrlpSource, errorCode, 0, ref
lpMsgBuf, messageSize, &prtArguments);
if (0 == retVal)
{
throw new Exception("Failed to format message for error code " +
errorCode + ". ");
}
return lpMsgBuf;
}

/// <summary>
/// Constructor. Initializes <var>Domain</var>, <var>UserName</var>, and
/// <var>Password</var>
/// </summary>
/// <param name="domain">Domain of impersonated User account</param>
/// <param name="userName">User name of impersonated User
account</param>
/// <param name="password">Password of impersonated User account</param>
public Impersonator(string domain, string userName, string password)
{
ImpersonateValidUser(userName, domain, password);
}

/// <summary>
/// Constructor.
/// </summary>
public Impersonator()
{
}

/// <summary type="System.Boolean">
/// Impersonate a User
/// </summary>
/// <param name="userName">User Name of User to impersonate</param>
/// <param name="domain">Domain of User to impersonate</param>
/// <param name="password">Password of User to impersonate</param>
/// <returns>true if Successful, false if not</returns>
public bool ImpersonateValidUser(String userName, String domain, String
password)
{
WindowsIdentity _TempWindowsIdentity;
IntPtr _Token = IntPtr.Zero;
IntPtr _TokenDuplicate = IntPtr.Zero;

try
{
if (_Impersonated) UndoImpersonation();

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();
if (ImpersonationContext != null)
_Impersonated = true;
else
_Impersonated = false;
}
else
_Impersonated = false;
}
else
_Impersonated = false;
return _Impersonated;
}
catch (Exception ex)
{
Utilities.HandleError(ex);
return false;
}
}


/// <summary>
/// Revert back to local identity
/// </summary>
public void UndoImpersonation()
{
if (ImpersonationContext != null) ImpersonationContext.Undo();
ImpersonationContext = null;
}

/// <summary mod="~">
/// Destructor. Ensures that Impersonation is cancelled.
/// </summary>
~Impersonator()
{
UndoImpersonation();
}
}

--
HTH,

Kevin Spencer
Microsoft MVP
Chicken Salad Surgery

What You Seek Is What You Get.

Ciaran O''Donnell said:
You need to call the LogonUser api function in advapi.dll in the windows
api
to get a security token (as an IntPtr), then you need to call
DuplicateToken
(cant remember the dll but I think its Kernal32.dll) to make it a primary
token which you can then use to start impersonating the user with the
WindowsIdentity class in the framework. When impersonating, all the code
the
runs under the windows identity your impersonating until you call
ImpersonationContext.Undo

I know this isnt a full answer but it should be enough to run a few
fruitfull searches


Ciaran O'Donnell
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top