473,549 Members | 2,715 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.GetFi les fail with "Logon failure: unknown user
name or bad password", stack trace is Exception stack
trace: at System.IO.__Err or.WinIOError(I nt32 errorCode,
String str) at
System.IO.Direc tory.InternalGe tFileDirectoryN ames(String
fullPath, String userPath, Boolean file) at
System.IO.Direc tory.InternalGe tFiles(String path, String
userPath, String searchPattern) at
System.IO.Direc tory.GetFiles(S tring 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
SecurityImperso nation = 2;

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

// Call LogonUser to
obtain a handle to an access token.
bool returnValue =
LogonUser(userN ame, domainName, password,
(int)
LogonType.LOGON 32_LOGON_NEW_CR EDENTIALS, (int)

LogonProvider.L OGON32_PROVIDER _DEFAULT, ref
tokenHandle);

if (false == returnValue)
{
int ret =
Marshal.GetLast Win32Error();
throw new
System.Componen tModel.Win32Exc eption(ret, GetErrorMessage
(ret));
}

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

if (false == retVal)
{
CloseHandle
(tokenHandle);
throw new
ApplicationExce ption("Exceptio n 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 (dupeTokenHandl e);

WindowsImperson ationContext impersonatedUse r =
newId.Impersona te();

try
{
do stuff;
}
catch {}

// Stop impersonating the
user.
impersonatedUse r.Undo();

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

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

using System;
using System.IO;
using System.Runtime. InteropServices ;
using System.Security ;
using System.Security .Principal;
using System.Reflecti on;

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

[DllImport("kern el32.dll")]
public extern static bool CloseHandle(Int Ptr hToken);

static void Main(s)
{
Class1 c = new Class1();
if(c.Impersonat e("someuserOnRe moteSrv", "RemoteSrv" , "hisPwd"))
{
string[] dirs = Directory.GetFi les(@"\\RemoteS rv\xxxx", "*");
foreach (string dir in dirs)
Console.WriteLi ne(dir);
c.impersonation Context.Undo();
}
else
Console.WriteLi ne("Impersonati on failed");
}

public bool Impersonate(str ing userName, string domain, string password)
{
WindowsIdentity tempWindowsIden tity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
// request default security provider a logon token with
LOGON32_LOGON_N EW_CREDENTIALS,
// token returned is impersonation token, no need to duplicate
if(LogonUser(us erName, domain, password, 9, 0, ref token) != 0)
{
tempWindowsIden tity = new WindowsIdentity (token);
impersonationCo ntext = tempWindowsIden tity.Impersonat e();
// close impersonation token, no longer needed
CloseHandle(tok en);
if (impersonationC ontext != null)
return true;
}
return false; // Failed to impersonate.
}

WindowsImperson ationContext impersonationCo ntext;
}
}

Willy.

"Chris" <an*******@disc ussions.microso ft.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.GetFi les fail with "Logon failure: unknown user
name or bad password", stack trace is Exception stack
trace: at System.IO.__Err or.WinIOError(I nt32 errorCode,
String str) at
System.IO.Direc tory.InternalGe tFileDirectoryN ames(String
fullPath, String userPath, Boolean file) at
System.IO.Direc tory.InternalGe tFiles(String path, String
userPath, String searchPattern) at
System.IO.Direc tory.GetFiles(S tring 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
SecurityImperso nation = 2;

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

// Call LogonUser to
obtain a handle to an access token.
bool returnValue =
LogonUser(userN ame, domainName, password,
(int)
LogonType.LOGON 32_LOGON_NEW_CR EDENTIALS, (int)

LogonProvider.L OGON32_PROVIDER _DEFAULT, ref
tokenHandle);

if (false == returnValue)
{
int ret =
Marshal.GetLast Win32Error();
throw new
System.Componen tModel.Win32Exc eption(ret, GetErrorMessage
(ret));
}

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

if (false == retVal)
{
CloseHandle
(tokenHandle);
throw new
ApplicationExce ption("Exceptio n 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 (dupeTokenHandl e);

WindowsImperson ationContext impersonatedUse r =
newId.Impersona te();

try
{
do stuff;
}
catch {}

// Stop impersonating the
user.
impersonatedUse r.Undo();

// Free the tokens.
if (tokenHandle !=
IntPtr.Zero)
CloseHandle
(tokenHandle);
if (dupeTokenHandl e !=
IntPtr.Zero)
CloseHandle
(dupeTokenHandl e);
}
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*******@disc ussions.microso ft.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
1335
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 requires network privileges. Since both these settings cannot be acheived in service(Local system
3
2765
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 an Asp.Net site to be able to open/access a file that's on an Smb share (ie. "Windows Share", "NetBios Share", etc.). I cannot use the "ASPNET"...
2
1795
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 "reports" and uses impersonation of the ReportWriter account in its own Web.config file in that directory. ReportWriter is an account on the machine...
4
1163
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 working example or good article of impersonation for a windows application? Any help is appreciated. Thanks,
1
3167
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 references an EXE file sitting in c:\windows\system32\ . Now if I use a Windows App and access the webservice everything goes smoothly.
3
1011
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 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....
11
2839
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
1783
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 database to check I created local users and assigned each of them a different default DB in SQL Server, then, in the windows service I impersonate...
3
1463
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 Authentication. In order to make this work, we have to impersonate a user account with access to the web service and set the Credential property on the web...
0
7956
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7469
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6040
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5087
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3498
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3480
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1935
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
757
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.