473,625 Members | 3,222 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Occasional SecurityExcepti on when impersonating a user on a new thread

I'm wrestling with a problem that I'm hoping someone can help me with.

I have a web application written in VS.2003 and running on version 1.1
of the .NET Framework on XP pro and Windows server 2003 that connects
to a SQL server database and authenticates itself using windows
authentication. The web application is configured to impersonate a
local user account that has been granted access to the database.
Here's the impersonation snip from the web.config.
<identity impersonate="tr ue" userName="<user name>"
password="<pass word>" />

For certain long running tasks we create a new thread so that the task
can completed asynchronously. When the new thread is created it has
the user context of the local aspnet account. We therefore must let
the new thread impersonate the local user so that the thread will be
able to access the database. This works most of the time but sometimes
I get a SecurityExcepti on with the following message: 'Unable to
impersonate user'.

The most effective way for me to reproduce this error has been open
two browsers on two separate computers and point them to a page that
executes a long running task in a separate thread and refresh the
page, first on one computer and then immediately on the second
computer. I repeat this about 10-15 times and I'll usually end up with
a handful of securityexcepti ons (which I log in the event log).

I've found two knowledge base articles that seem to focus on this
issue. The first one is here: http://support.microsoft.com/kb/842790.
I've tried 2 out of 3 workarounds mentioned in that article and
neither helped. The third workaround, calling RevertToSelf, is not a
viable option for me since the main thread will then no longer be able
to access the database. The second article is here: http://support.microsoft.com/kb/319615
but it only applies to version 1.0 of the framework.

I've tried numerous things in a weak attemtp to fix this issue. One
thing I tried was calling the DuplicateToken method in advapi32.dll,
passing the token of the impersonated user on the main thread and
using the duplicated token for impersonation on the new thread. That
unfortunately didn't work but it might be of interest that the
DuplicateToken method failed (returned false) occasionally, probably
because of the same conditions that cause the impersonation to fail
with a securityexcepti on.

Here's a simplified example of the code that is being executed:

public class LongRunningTask
{
private IntPtr userToken;
private WindowsImperson ationContext impersonationCo ntext;

public void StartTask()
{
//
// This is executed on the main thread
//
IntPtr userToken = WindowsIdentity .GetCurrent().T oken;
LongRunningTask task = new LongRunningTask (userToken);
Thread thread = new Thread(new ThreadStart(tas k.ExecuteTask)) ;
thread.Name = "Task running thread";
thread.Priority = ThreadPriority. Lowest;
thread.IsBackgr ound = false;
thread.Start();
}

public LongRunningTask ()
{
}

public LongRunningTask (IntPtr userToken)
{
this.userToken = userToken;
}

public void ExecuteTask()
{
//
// This is executed on the new thread
//
ImpersonateCall ingThread();
// ... do work
UndoImpersonati on();
}

private void ImpersonateCall ingThread()
{
this.impersonat ionContext =
WindowsIdentity .Impersonate(th is.userToken);
}

private void UndoImpersonati on()
{
if (impersonationC ontext != null)
{
impersonationCo ntext.Undo();
}
}
}

May 18 '07 #1
4 2322
Curious,
Why don't you just use SQL server authentication? If the connection string
is valid, it won't matter what the identity is of the calling thread.
Peter
--
Site: http://www.eggheadcafe.com
UnBlog: http://petesbloggerama.blogspot.com
Short urls & more: http://ittyurl.net


"EirĂ*kur Fannar Torfason" wrote:
I'm wrestling with a problem that I'm hoping someone can help me with.

I have a web application written in VS.2003 and running on version 1.1
of the .NET Framework on XP pro and Windows server 2003 that connects
to a SQL server database and authenticates itself using windows
authentication. The web application is configured to impersonate a
local user account that has been granted access to the database.
Here's the impersonation snip from the web.config.
<identity impersonate="tr ue" userName="<user name>"
password="<pass word>" />

For certain long running tasks we create a new thread so that the task
can completed asynchronously. When the new thread is created it has
the user context of the local aspnet account. We therefore must let
the new thread impersonate the local user so that the thread will be
able to access the database. This works most of the time but sometimes
I get a SecurityExcepti on with the following message: 'Unable to
impersonate user'.

The most effective way for me to reproduce this error has been open
two browsers on two separate computers and point them to a page that
executes a long running task in a separate thread and refresh the
page, first on one computer and then immediately on the second
computer. I repeat this about 10-15 times and I'll usually end up with
a handful of securityexcepti ons (which I log in the event log).

I've found two knowledge base articles that seem to focus on this
issue. The first one is here: http://support.microsoft.com/kb/842790.
I've tried 2 out of 3 workarounds mentioned in that article and
neither helped. The third workaround, calling RevertToSelf, is not a
viable option for me since the main thread will then no longer be able
to access the database. The second article is here: http://support.microsoft.com/kb/319615
but it only applies to version 1.0 of the framework.

I've tried numerous things in a weak attemtp to fix this issue. One
thing I tried was calling the DuplicateToken method in advapi32.dll,
passing the token of the impersonated user on the main thread and
using the duplicated token for impersonation on the new thread. That
unfortunately didn't work but it might be of interest that the
DuplicateToken method failed (returned false) occasionally, probably
because of the same conditions that cause the impersonation to fail
with a securityexcepti on.

Here's a simplified example of the code that is being executed:

public class LongRunningTask
{
private IntPtr userToken;
private WindowsImperson ationContext impersonationCo ntext;

public void StartTask()
{
//
// This is executed on the main thread
//
IntPtr userToken = WindowsIdentity .GetCurrent().T oken;
LongRunningTask task = new LongRunningTask (userToken);
Thread thread = new Thread(new ThreadStart(tas k.ExecuteTask)) ;
thread.Name = "Task running thread";
thread.Priority = ThreadPriority. Lowest;
thread.IsBackgr ound = false;
thread.Start();
}

public LongRunningTask ()
{
}

public LongRunningTask (IntPtr userToken)
{
this.userToken = userToken;
}

public void ExecuteTask()
{
//
// This is executed on the new thread
//
ImpersonateCall ingThread();
// ... do work
UndoImpersonati on();
}

private void ImpersonateCall ingThread()
{
this.impersonat ionContext =
WindowsIdentity .Impersonate(th is.userToken);
}

private void UndoImpersonati on()
{
if (impersonationC ontext != null)
{
impersonationCo ntext.Undo();
}
}
}

May 18 '07 #2
Well, you see, I work for an ISV and this problem relates to a product of
ours. Many years ago when we were working on the initial release we decided
that using windows authentication was the best way to go for a number of
reasons. One of the reasons is that its more secure. Another one is that SQL
server by default does not have SQL server authentication enabled and
enabling it might be seen as a security risk by some customers.

If we were to switch to using SQL server authentication then that would
require us to alter support materials (like the operations guide) and of
course modify our installer which currently takes care of creating a local
user account for the product and granting it access to the database.

"Peter Bromberg [C# MVP]" wrote:
Curious,
Why don't you just use SQL server authentication? If the connection string
is valid, it won't matter what the identity is of the calling thread.
Peter
--
Site: http://www.eggheadcafe.com
UnBlog: http://petesbloggerama.blogspot.com
Short urls & more: http://ittyurl.net


"EirĂ*kur Fannar Torfason" wrote:
I'm wrestling with a problem that I'm hoping someone can help me with.

I have a web application written in VS.2003 and running on version 1.1
of the .NET Framework on XP pro and Windows server 2003 that connects
to a SQL server database and authenticates itself using windows
authentication. The web application is configured to impersonate a
local user account that has been granted access to the database.
Here's the impersonation snip from the web.config.
<identity impersonate="tr ue" userName="<user name>"
password="<pass word>" />

For certain long running tasks we create a new thread so that the task
can completed asynchronously. When the new thread is created it has
the user context of the local aspnet account. We therefore must let
the new thread impersonate the local user so that the thread will be
able to access the database. This works most of the time but sometimes
I get a SecurityExcepti on with the following message: 'Unable to
impersonate user'.

The most effective way for me to reproduce this error has been open
two browsers on two separate computers and point them to a page that
executes a long running task in a separate thread and refresh the
page, first on one computer and then immediately on the second
computer. I repeat this about 10-15 times and I'll usually end up with
a handful of securityexcepti ons (which I log in the event log).

I've found two knowledge base articles that seem to focus on this
issue. The first one is here: http://support.microsoft.com/kb/842790.
I've tried 2 out of 3 workarounds mentioned in that article and
neither helped. The third workaround, calling RevertToSelf, is not a
viable option for me since the main thread will then no longer be able
to access the database. The second article is here: http://support.microsoft.com/kb/319615
but it only applies to version 1.0 of the framework.

I've tried numerous things in a weak attemtp to fix this issue. One
thing I tried was calling the DuplicateToken method in advapi32.dll,
passing the token of the impersonated user on the main thread and
using the duplicated token for impersonation on the new thread. That
unfortunately didn't work but it might be of interest that the
DuplicateToken method failed (returned false) occasionally, probably
because of the same conditions that cause the impersonation to fail
with a securityexcepti on.

Here's a simplified example of the code that is being executed:

public class LongRunningTask
{
private IntPtr userToken;
private WindowsImperson ationContext impersonationCo ntext;

public void StartTask()
{
//
// This is executed on the main thread
//
IntPtr userToken = WindowsIdentity .GetCurrent().T oken;
LongRunningTask task = new LongRunningTask (userToken);
Thread thread = new Thread(new ThreadStart(tas k.ExecuteTask)) ;
thread.Name = "Task running thread";
thread.Priority = ThreadPriority. Lowest;
thread.IsBackgr ound = false;
thread.Start();
}

public LongRunningTask ()
{
}

public LongRunningTask (IntPtr userToken)
{
this.userToken = userToken;
}

public void ExecuteTask()
{
//
// This is executed on the new thread
//
ImpersonateCall ingThread();
// ... do work
UndoImpersonati on();
}

private void ImpersonateCall ingThread()
{
this.impersonat ionContext =
WindowsIdentity .Impersonate(th is.userToken);
}

private void UndoImpersonati on()
{
if (impersonationC ontext != null)
{
impersonationCo ntext.Undo();
}
}
}
May 18 '07 #3
"EirĂ*kur Fannar Torfason" <EirĂ*kur Fannar
To******@discus sions.microsoft .comwrote in message
news:23******** *************** ***********@mic rosoft.com...
One of the reasons is that its more secure.
In what way(s) is Windows authentication more secure than SQL Server
authentication. ..?
--
http://www.markrae.net

May 18 '07 #4
I expect you'll correct me if I'm wrong, but it's my understanding that with
SQL server authentication, the credentials are sent over the network for each
connection attempt as opposed to a token when windows authentication is used.
It's also my understanding that the password is encrypted using a very weak
encryption algorithm, at least with SQL server 2000 which is the version that
the majority of our customers are running. But I'll happily listen to anyone
with expert knowledge on SQL Server security. In fact, that's exactly what we
did when we made our original decision. We listened to a very helpful,
intelligent man from Microsoft Consulting Services who told us that from a
security point of view, windows authentication was the way to go.

None of this however has anything to do with my original post.

"Mark Rae" wrote:
"EirĂ*kur Fannar Torfason" <EirĂ*kur Fannar
To******@discus sions.microsoft .comwrote in message
news:23******** *************** ***********@mic rosoft.com...
One of the reasons is that its more secure.

In what way(s) is Windows authentication more secure than SQL Server
authentication. ..?
--
http://www.markrae.net

May 18 '07 #5

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

Similar topics

0
1432
by: | last post by:
I have been learning really hard to understand this .NET security thing, but I still get overwhelmed with the abstractness. The hardest part is to understand *when* you get an SecurityException and *how* I would translate this into a simple-user-friendly messagebox. And *when* you get a PolicyException and I also want to translate this into a simple-user-friendly messagebox. The idea is then to start up some...
1
6803
by: Sam | last post by:
I have a desktop VB.Net application I developed locally. I uploaded it to a file server we have and the .Net Framework is installed on the file server. When I try to run the executable from the network drive, I get, "System.Security.SecurityException." When I Open the solution from the network drive, I get, "The project location is not fully trusted by the .Net runtime. And then when I click ok and try to run in debug mode I get...
1
6539
by: phark52 | last post by:
My main app calls LoadLibrary() to load a DLL, which calls CreateThread(). This does NOT return NULL and I get a thread ID. However, ThreadProc never gets executed when this code is in the DLL. It works fine in the standalone EXE source. I put example code below. #define MB(msg) MessageBox(0, msg, "", MB_OK|MB_ICONINFORMATION); DWORD APIENTRY tproc() {
1
4441
by: edge | last post by:
hi, here it is my problem. My console app, reads a text file where it grabs username/password. Next, my app creates a .BAT file to trigger the command ftp:\\user:password@ftphomeaddress. Then, I use Process() to start the batch. In my local machine, the app runs just fine. But the users
4
1307
by: Garrett | last post by:
Hi all, I am trying to access folders on an Active Directory network share in my ASP code. In my config file I have the following: <identity impersonate="true" userName="OURDOMAIN\myusername" password="mypass"/>
0
970
by: Michael | last post by:
Re: system.security.securityexception The program I have written requires "Full Trust" to run and will throw a security exception if a user tries to load it while working in the Intranet Zone, i.e., on a LAN. I am trying to trap the error, and advise the user via a messagebox to request the LAN administrator to set up the user machine to allow "full trust" thus permitting the code to run.
2
6081
by: Leonardo Arena | last post by:
We have an Index Server on Win2k Server SP4 indexing about 250.000 docs. We have written an ASP.NET serch page, setup a new virtual directory, and set to use .NET framework 2.0. On the server is installed also .NET framework 1.0, for the rest of the Intranet. The search page is setup to impersonate the user running the query in order to return only the documents that the user have access to. However most of the times, after a number of...
3
4584
by: Geoff McElhanon | last post by:
I have been struggling with a security issue that occurs under .NET 2.0, but does not occur under .NET 1.1. Essentially I am trying to open up a performance counter on a remote server and monitor its value. In .NET 1.1 this worked fine, however under .NET 2.0 it fails when I am not an administrator on the remote server. To provide a lean demonstration of the issue, I created the following class: ============================
2
2176
by: Chuck B | last post by:
I'm trying to run a modified version of the example in this Microsoft article: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfmicrosoftwin32registrykeyclassopenremotebasekeytopic.asp The only changes I've made to the code is that instead of using "HKEY_CURRENT_USER\Environment" as my registry path I'm using "HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows" and setting OpenRemoteBaseKey to open...
0
8192
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8637
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8358
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8502
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7188
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5571
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2621
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
1
1805
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1504
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.