473,387 Members | 1,863 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Impersonation and UNC shares in a windows service

Hello all,
Here is my problem. I have a windows service (C#) that is
supposed to move files from/to the local drive to/from a
UNC share (\\domainserver\share). The service is running
on a Win3k server not connected to a domain, as a local
user. The service impersonates a local user (on
domainserver) that has full permissions to that share. Any
File.Move, File.Copy operations are successfull. Any
Directory.GetFiles fail with "Logon failure: unknown user
name or bad password", stack trace is Exception stack
trace: at System.IO.__Error.WinIOError(Int32 errorCode,
String str) at
System.IO.Directory.InternalGetFileDirectoryNames( String
fullPath, String userPath, Boolean file) at
System.IO.Directory.InternalGetFiles(String path, String
userPath, String searchPattern) at
System.IO.Directory.GetFiles(String path, String
searchPattern). The call succeeds if I run the service
under a local account with the same user name/pwd or if
the server is connected to the domain and the service runs
as any domain account.
The impersonation code is similar with the samples from
MSDN (sorry about the formatting):
public static void ImpersonateUser(string domainName,
string userName, string password)
{
IntPtr tokenHandle = new IntPtr(0);
IntPtr dupeTokenHandle = new IntPtr
(0);
try
{
// Get the user token for
the specified user, domain, and password using the
// unmanaged LogonUser
method.

const int
SecurityImpersonation = 2;

tokenHandle = IntPtr.Zero;
dupeTokenHandle =
IntPtr.Zero;

// Call LogonUser to
obtain a handle to an access token.
bool returnValue =
LogonUser(userName, domainName, password,
(int)
LogonType.LOGON32_LOGON_NEW_CREDENTIALS, (int)

LogonProvider.LOGON32_PROVIDER_DEFAULT, ref
tokenHandle);

if (false == returnValue)
{
int ret =
Marshal.GetLastWin32Error();
throw new
System.ComponentModel.Win32Exception(ret, GetErrorMessage
(ret));
}

//Duplicate the token
bool retVal =
DuplicateToken(tokenHandle, SecurityImpersonation, ref
dupeTokenHandle);

if (false == retVal)
{
CloseHandle
(tokenHandle);
throw new
ApplicationException("Exception thrown in trying to
duplicate token.");
}

// The token that is
passed to the following constructor must
// be a primary token in
order to use it for impersonation.
WindowsIdentity newId =
new WindowsIdentity(dupeTokenHandle);

WindowsImpersonationContext impersonatedUser =
newId.Impersonate();

try
{
do stuff;
}
catch {}

// Stop impersonating the
user.
impersonatedUser.Undo();

// Free the tokens.
if (tokenHandle !=
IntPtr.Zero)
CloseHandle
(tokenHandle);
if (dupeTokenHandle !=
IntPtr.Zero)
CloseHandle
(dupeTokenHandle);
}
catch(Exception ex)
{
throw ex;
}
}
}

Thanks a lot for any help or ideas,
Chris
Jul 21 '05 #1
3 5132
This works for me.

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
using System.Reflection;

namespace ImpersonateTest
{
class Class1
{
[DllImport("advapi32.dll")]
public static extern int LogonUser(String lpszUsername, String lpszDomain,
String lpszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

[DllImport("kernel32.dll")]
public extern static bool CloseHandle(IntPtr hToken);

static void Main(s)
{
Class1 c = new Class1();
if(c.Impersonate("someuserOnRemoteSrv", "RemoteSrv", "hisPwd"))
{
string[] dirs = Directory.GetFiles(@"\\RemoteSrv\xxxx", "*");
foreach (string dir in dirs)
Console.WriteLine(dir);
c.impersonationContext.Undo();
}
else
Console.WriteLine("Impersonation failed");
}

public bool Impersonate(string userName, string domain, string password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
// request default security provider a logon token with
LOGON32_LOGON_NEW_CREDENTIALS,
// token returned is impersonation token, no need to duplicate
if(LogonUser(userName, domain, password, 9, 0, ref token) != 0)
{
tempWindowsIdentity = new WindowsIdentity(token);
impersonationContext = tempWindowsIdentity.Impersonate();
// close impersonation token, no longer needed
CloseHandle(token);
if (impersonationContext != null)
return true;
}
return false; // Failed to impersonate.
}

WindowsImpersonationContext impersonationContext;
}
}

Willy.

"Chris" <an*******@discussions.microsoft.com> wrote in message
news:00****************************@phx.gbl...
Hello all,
Here is my problem. I have a windows service (C#) that is
supposed to move files from/to the local drive to/from a
UNC share (\\domainserver\share). The service is running
on a Win3k server not connected to a domain, as a local
user. The service impersonates a local user (on
domainserver) that has full permissions to that share. Any
File.Move, File.Copy operations are successfull. Any
Directory.GetFiles fail with "Logon failure: unknown user
name or bad password", stack trace is Exception stack
trace: at System.IO.__Error.WinIOError(Int32 errorCode,
String str) at
System.IO.Directory.InternalGetFileDirectoryNames( String
fullPath, String userPath, Boolean file) at
System.IO.Directory.InternalGetFiles(String path, String
userPath, String searchPattern) at
System.IO.Directory.GetFiles(String path, String
searchPattern). The call succeeds if I run the service
under a local account with the same user name/pwd or if
the server is connected to the domain and the service runs
as any domain account.
The impersonation code is similar with the samples from
MSDN (sorry about the formatting):
public static void ImpersonateUser(string domainName,
string userName, string password)
{
IntPtr tokenHandle = new IntPtr(0);
IntPtr dupeTokenHandle = new IntPtr
(0);
try
{
// Get the user token for
the specified user, domain, and password using the
// unmanaged LogonUser
method.

const int
SecurityImpersonation = 2;

tokenHandle = IntPtr.Zero;
dupeTokenHandle =
IntPtr.Zero;

// Call LogonUser to
obtain a handle to an access token.
bool returnValue =
LogonUser(userName, domainName, password,
(int)
LogonType.LOGON32_LOGON_NEW_CREDENTIALS, (int)

LogonProvider.LOGON32_PROVIDER_DEFAULT, ref
tokenHandle);

if (false == returnValue)
{
int ret =
Marshal.GetLastWin32Error();
throw new
System.ComponentModel.Win32Exception(ret, GetErrorMessage
(ret));
}

//Duplicate the token
bool retVal =
DuplicateToken(tokenHandle, SecurityImpersonation, ref
dupeTokenHandle);

if (false == retVal)
{
CloseHandle
(tokenHandle);
throw new
ApplicationException("Exception thrown in trying to
duplicate token.");
}

// The token that is
passed to the following constructor must
// be a primary token in
order to use it for impersonation.
WindowsIdentity newId =
new WindowsIdentity(dupeTokenHandle);

WindowsImpersonationContext impersonatedUser =
newId.Impersonate();

try
{
do stuff;
}
catch {}

// Stop impersonating the
user.
impersonatedUser.Undo();

// Free the tokens.
if (tokenHandle !=
IntPtr.Zero)
CloseHandle
(tokenHandle);
if (dupeTokenHandle !=
IntPtr.Zero)
CloseHandle
(dupeTokenHandle);
}
catch(Exception ex)
{
throw ex;
}
}
}

Thanks a lot for any help or ideas,
Chris

Jul 21 '05 #2
Thanks for the quick reply Willy. The only difference I
see is that you're not duplicating the token. I'll give it
a try tomorrow and let you know how it works out.

Chris
Jul 21 '05 #3
Chris, It doesn't really mather, the DuplicateToken is only needed when the
token obtained when calling Logon user is not an impersonation token.
It works also when impersonating using the token obtained by DuplicateToken.

Willy.

"Chris" <an*******@discussions.microsoft.com> wrote in message
news:27****************************@phx.gbl...
Thanks for the quick reply Willy. The only difference I
see is that you're not duplicating the token. I'll give it
a try tomorrow and let you know how it works out.

Chris

Jul 21 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Johyson | last post by:
Hi, I am using a windows service which does two things 1. It calls an exe which is a screen scraping program and needs to interact with the desktop. 2. It calls an web service, which...
3
by: Granger Godbold | last post by:
I've found a solution to this that I think I like, but I thought it wise to put it out for all to see so people could punch holes in it as they wished. (Is there a better way?) I want a page in...
2
by: Seth Darr | last post by:
OK I am at my wits end and I hope that someone can help me. I've got an ASP.NET web app that generates dynamic excel spreadsheets via COM. It does this work in a seperate subdirectory called...
4
by: Brent Burkart | last post by:
I have a directory synchronization service that requires access to network shares. I am getting access denied errors. It looks like I need to implement impersonation. Can anyone direct me to a...
1
by: Jarred | last post by:
Howdy All, I've been having a bit of a problem that I can't seem to get a grip on at the moment and I'm hoping someone may be able to give me a quick hand :) What I have is a Webservice that...
3
by: Chris | last post by:
Hello all, Here is my problem. I have a windows service (C#) that is supposed to move files from/to the local drive to/from a UNC share (\\domainserver\share). The service is running on a Win3k...
11
by: Phil | last post by:
Hi, I've currently setup a local user as described in: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnne...
4
by: David Cablalero | last post by:
I have a windows service which every night checks a SQL Server database for some data and business rules. The application can access different DBs with the same structure, to tell the service which...
3
by: headware | last post by:
We have a web app that is running under Integrated Windows Authentication. It must consume to a web service we are publishing on another server, also running under Integrated Windows...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.