Windows Impersonation: A Flaw in the Ointment

两盒软妹~` 提交于 2019-12-03 06:33:38

Thanks to input from Harry Johnston (in comments attached to the question) and Phil Harding (in separate communication) I was able to determine that SQL Server connection pooling was the culprit here. Since pooling is determined by uniqueness of the connection string, by slightly varying the connection string (e.g. reversing order of parameters within, or even just adding a space on the end) I then observed the behaviors I expected.

===== TEST WITH SAME CONN STRING: True
BEGIN impersonation
Local user: MyDomain\msorens
DB reports: MyDomain\testuser
END impersonation
Local user: MyDomain\msorens
DB reports: MyDomain\testuser <<<<< still impersonating !!

===== TEST WITH SAME CONN STRING: False
BEGIN impersonation
Local user: MyDomain\msorens
DB reports: MyDomain\testuser
END impersonation
Local user: MyDomain\msorens
DB reports: MyDomain\msorens  <<<<< this is what I wanted to get

I dug into the internals of the connection pooling, and it turns out that Windows credentials are not considered a part of the connection pooling key at all. Only SQL logins would be taken into account.

So if there is an available connection that was opened under user A and you are now impersonating user B, it will still use it and SQL will see you as user A. The reverse is also true.

The approach of changing the connection string slightly for the two different users is fine. You might do this if you have a "normal" user and then you need to impersonate for some "elevated" user. Of course, you don't want a different string for every user of your application - otherwise you might as well disable connection pooling completely.

When tweaking your connection string, you might consider appending the impersonated username to either the Application Name or Workstation ID fields. This would have the benefit of setting up a separate pool for each impersonated user.

I have found that the login type LOGON32_LOGON_NETWORK_CLEARTEXT does not have a problem with connections being re-used across impersonation contexts and works as expected without varying the connection string.

According to this thread, the "cleartext" part of this login type seems to be local to the server. I only keep the token alive for the duration of the database query or set of queries, so the token is very short-lived. Using this login type for long-lived tokens may or may not be a security risk.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!