31 July, 2012

Windows Smart Card Subsystem and Remote Sessions

Situation

1. When you have an eToken usb device which is connected to a PC somewhere in your home or office and you want to use this token via a remote session. For instance. you're in another city with your favourite notebook. You use built-in Windows Remote Desktop  Connection to access some applications required the usb token. Here we have an RDP session.
2. At work you have a VMware View infrastructure that uses PCoIP protocol. You added a usb passthrough device to a specific virtual machine. It means that your token connected directly  to the ESXi host. This is the only possible way to make a token visible in a virtual machine that I know (directly connected tokens on the client side doesn't work in PCoIP). Then a user opens VMware View client and wants to access the token through some special applications.



Problem

Microsoft Smart Card subsystem blocks access to any locally attached usb tokens or smart card readers in a remote session. Theoretically, you should attach required devices on the client side, but it's not cool and often is not acceptable. I've seen this problem using such protocols as RDP or PCoIP (let's call them session protocols), whereas everything works fine via VNC or Radmin, because these products use their own methods to connect directly to the local session of PC or virtual machine.

Solving

I tried to find an answer in the Internet fields. I looked through many forums finding any helpful information. So, I decided to solve the issue by my own.
First thing that I did was to emulate the situation. I took a usb eToken and attached it to a virtual machine on VMware ESXi host. After that, I had to add one usb controller and my usb device to the VM in vCenter. Next, I opened view client and connected to my vm. I used eTokens by Aladdin-rd. There are special drivers for eTokens - PKI client 5.1 SP 1. It can be downloaded from the official site.
After we have the token and required drivers, it's possible to test the issue. If open eToken Prperties in local session and go to Managing Readers, we'll see this:


But if we do it in a remote session, we'll get 0 readers instead of 2, because eToken service couldn't get any information from a Windows smart card subsystem. Let's have a look on a smart card architecture in Windows:


It is logical that the problem is somewhere in the core of the architecture, somewhere in WinSCard.dll. But let's begin from the top of the iceberg. eToken Properties is an application included in driver pack eToken PKI Client. We should have a look at an import section:


That's it. The most interesting and valuable in etProps.exe's import section are these functions from WinSCard.dll. After a quick view in MSDN, it's easy to find a necessary function: SCardEstablishContext. There is also a valuable remark to this function:
"If the client attempts a smart card operation in a remote session, such as a client session running on a terminal server, and the operating system in use does not support smart card redirection, this function returns ERROR_BROKEN_PIPE."
Good. Now, we know that it is the function that should be debuged. I prefer to use WinDbg from Debugging Tools. I debuged this function in remote and local sessions and got the next result. Function SCardEstablishContext calls internal InTSMethodWithContext that then also calls undocumented WinStationIsSessionRemoteable from winsta.dll which checks if we work in local or remote session. It's a bad idea to modify winsta.dll - for some programs it's useful to know the real type of session. So, lets patch WinSCard.dll. Function InTSMethodWithContext returns 1 if we work in remote session and 0 if in local. I decided to put "xor eax, eax" in the end of function instead of coping the real value of out WinStationIsSessionRemoteable argument.


Then in hex editor I replaced "0F B6 45 FF" to "33 C0 90 90" with 1C40 offset. Almost done. Finally, the original Windows system file C:\Windows\System32\WinSCard.dll should be replaced by patched and that's it.

After these manipulations I've got a workable Windows Smart Card subsystem and any eTokens work well as in a local session as in a remote one via RDP or PCoIP.

UPD: Don't forget about Windows File Protection mechanisms in Windows. You should turn if off or replace a required file in cache as well. Otherwise, our modified file will be replaced by the original in a background.

UPD: Here is a patch. I tested it only with XP ProSP3/32, However, it should work with 7 Pro/32 too.

UPD: The last version of the path is available at lifayk.com. Here is a direct link: http://lifayk.com/files/scpatch0.3.zip

121 comments:

  1. Hello, can u help me to patch my WinSCard.dll or send me your?

    ReplyDelete
    Replies
    1. What problems do you have?

      Delete
    2. I have exactly 1st situation from your note. But i don’t have experience to debug WinSCard.dll , i download windbg, but cant open dll. My Server OS Win2003 SP2. Maybe you can send me patched WinSCard.dll file or send detailed instruction how to patch dll? Thanks for your reply!

      Delete
    3. This comment has been removed by the author.

      Delete
    4. Instructions are in this topic. I did this on a client side, so I don't know if it works with Win Server. Unfortunately, I don't have any Windows system right now, but you can send me your original dll or I can write a tiny patch program.

      Delete
    5. opps! you said, you did this patch only on client side? not on server???
      but i thought and did it on a server side =\

      Delete
    6. Yes. But the subsystem should be the same. In 2 weeks I'll get all my virtual machines and will be able to check WinServ, too.

      Delete
    7. My eTokens were attached through a ESXi host to virtual workstations running Windows 7 32-bit. Usually eTokens are used on the client side, not server.

      Delete
    8. Hmm, let introduce some clearness.

      I have Windows 2008 Server with bank-client & eTokens installed on it. Also i have client (winXP) computer which connected to win2008 via RemoteDesktop.
      Where i should patch winScard file? I've done it on server side already, but it didn't get any effect to client - it still can't see any eTokens via RemoteDesktop.

      Also i tried to patch client-side winScard file on WindowsXP, but i stuck with problem that i can't find WinStationsIsRemoteable function in my local winSTA.dll.

      And finally - where i need to apply patched file in my situation: on client or on server ?

      Thanks!

      Delete
    9. You need to patch on a machine where eTokens are attached. So, in your case, on the Server. I haven't tried it with Windows 2k8, but I thinks it should be the same.

      Delete
    10. nope! it doesnt! =(
      As i said already - i've patched WinSCard.dll on my Windows Server 2008 R2 x64, and it still doesn't detect any server-side etokent in terminal connection =(
      Some details 'bout my winSCard.dll file:
      file size: 217600
      offsets:
      0D58: 0F -> 33
      0D59: B6 -> C0
      0D5A: 44 -> 90
      0D5B: 24 -> 90
      0D5C: 30 -> 90


      btw, Visual DuxDebugger - pretty nice & free! =)

      Delete
  2. Hello. May I ask you to share fixed dll? I also have the same issue, but no expertize in dll edit.

    Thank you

    ReplyDelete
  3. привет! Я под Windows 2008 R2 Server x64 не смог получить нужного результата, хотя под отладчиком нашел место проверки ...
    Вместо единички обнулил EAX, но все равно в локальном входе все ОК, а в терминале Etoken не видится =(
    Не сталкивался, в ходе своих поисков, может еще где-то проверка есть?
    Полдня убил на ковыряние, но воз и ныне там =(

    ReplyDelete
    Replies
    1. загасился походу автор

      Delete
    2. Печально, блин. Тема-то очень нужная.

      Delete
    3. согласен! а мёртвая..

      Delete
  4. It seems that I need to write a patch tool

    ReplyDelete
    Replies
    1. It would be really great! I had checked my winSCard.dll right after red this article first time and see completely different values. OS is Win 2008 R2.

      Delete
    2. Hello!
      I have Win2008R2 too, try this "values" =) and post your result here!

      file size: 217600
      offsets:
      0D58: 0F -> 33
      0D59: B6 -> C0
      0D5A: 44 -> 90
      0D5B: 24 -> 90
      0D5C: 30 -> 90

      Delete
    3. I have the same file. I did this modification, and replaced dll in system32. Did a reboot, and check with bank client. No way, smartcard doesn't visible there.

      Delete
    4. Amironox, didn't you forget about Windows SFC?

      Delete
  5. Hello folks. Lifayk thank you for sharing such useful information. I have the same problem with Windows 2003 Server x32. However, after reading your post, I couldn't find the mentioned bytes' succession to do the substitution. I tried it on Windows 2003 server and Windows XP prof, but without success. There is no "0F B6 45 FF" byte-string in winscard.dll. I think my boss would appreciate (in money) your help in this question. He seems very obsessed by the idea of running a certain program on a corporate terminal server wich uses HASP HL keys. Please contact me 1 2 2 at 5 5 5 5 0 . ru

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. If anyone finds the offset for the 64bit version of this file please post so we can patch...

    ReplyDelete
    Replies
    1. 64bit WIN7 Enterp \Windows\SysWOW64\WinSCard.dll
      Search for 0F B6 44 24 30 -> 33 C0 90 90 90

      offset D50

      replace and enjoy

      Delete
  8. Здравствуйте. У кого-нибудь получилось пропатчить файл для Windows XP prof Sp3?
    Не могу найти указанную последовательность данных. Может кто-то выложит пропатченную dll-ку.

    ReplyDelete
    Replies
    1. Откуда ей там взяться. Она только на серверных версиях с RDP.

      Delete
  9. Как я понял автор статьи описывает данный способ на примере Windows 7 32bit.
    Попробовав на win 7, я действительно нашел последовательность данных описанных в данной статье.
    После замены файла, и настройки терминального доступа в win 7, результаты следующие: Если к примеру зайти в начале локально на комп.с win 7 под доменной учеткой то e-token виден, и не выходя из сеанса подключится уже через rdp под той-же учетной записью, то e-token тоже будет виден и с ним можно работать через rdp.
    Но если изначально просто подключаться через rdp то e-token не виден.
    Хотелось бы уточнить, получалось ли у кого-нибудь полноценная работа с e-token через rdp? И если да, то на какой OC?

    ReplyDelete
  10. Hi, All.
    I'd like to repeat one more time. I did above with MS Windows 7 Pro 32-bits. All machines had locally attached eTokens. Users were able to do everything with tokens and machines. WinSCard.dll is a system library and there shouldn't be any problems with accounts and sessions because it doesn't interrelated. I mean that the machines could be successfully restarted and tokens worked fine. All connection to the machines were through RDP or PCoIP.
    I had a look at other OSs. In case with Win 7/2008 the situation is quite common, they use the same subsystem. However, Win XP/2003 use different Telnet Server and the situation is not obvious and requires additional analysing.
    I started to write a patch tool for all Windows versions. Now it works only with 7/2008 32-bits. I hope I'll shortly manage to find some free time to analyse the issues with other OSs and finish the tool.

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Can you tell about the availability patch?

      Delete
    3. Try this: http://goo.gl/iMbkrN

      Delete
  11. What do you mean with 1c40 offset i find "0F B6 45 FF" I can replace it to "33 C0 90 90" but I dont know what to do with the offset

    ReplyDelete
    Replies
    1. "Offset" is on the left side in any hex-editor. It means the step from the beginning of a file. There can be more then one mentioned byte sequence in the file, so you need to be sure, that you change the right one.

      Delete
  12. Hi, lifayk... thanks for your work here... But I realy need this patch for XP... (rdesktop with seamlessrdp mode is mandatory here, and XP works great in this combination)

    thanx

    ReplyDelete
    Replies
    1. XP/2003 Terminal subsystem works differently. However, I think it should be possible. Hope, I'll make a new post for this soon.

      Delete
  13. Hi!
    Thanks for this information, it is useful!
    But can you do a patch to modify file WinSCard.dll for different OS.
    Specially interesting in Windows 7 Pro, Enterprise, Ultimate x86 and x64.
    If you need all original files, I can send these to you.

    Thanks in advance!

    ReplyDelete
    Replies
    1. Yeah, can you send me original files. I don't have many of mentioned above OSs.

      Delete
    2. Thanks for reply and able to help!
      In this archive
      http://rghost.ru/private/48213921/ea35d41040a14226b09a00fd8943e9af
      there are two files: one for x32 system (Windows 7 SP1 x32 Pro, Ent, Ult - there is the same) and the second for x64 systems (Windows 7 SP1 x64 Pro, Ent, Ult and Windows Server 2008 R2 SP2, also there is the same.

      Please. help in this question.

      Delete
  14. I find "0F B6 45 FF" and replace to "33 C0 90 90", but no luck, can't see any smart card or etoken while using RDP connection.

    My OS is: Microsoft Windows 7 Pro 6.1.7601 Service Pack 1
    OS Language: Ru
    SFC: disabled

    Could you please give an advice, what is the cause?

    ReplyDelete
    Replies
    1. 32 or 64 bit? What is the number of virtual readers for eTokens do you see in eTokens Properties?

      Delete
    2. Thank you for your reply.

      32 bit.

      While Console session I can see 6 readers (3 Aktiv Co. IFD Handler
      and 2 Aladdin IFD Handler and Aladdin VR Handler ).

      I cant't see any reader via RDP session.

      Installed PKI client version 5 SP1
      Aktiv Co. IFD Handler - RuToken key reader

      Delete
    3. It turns out that there is a RPC/DCOM configuration that influences a session situation. It's very interesting. I'm busy for 2-3 weeks, but then I'll investigate it further and publish a patch (it's done already).

      Delete
    4. Thank you for your efforts. Is it possible to test the patch (If it's done already)? And what is the problem with RPC/DCOM?

      Delete
  15. For XP SP3 you can replace all occurences of 6800100000FF15C0113B72 by 90909090909090909033C0. So winscard.dll would consider any RDP session as local console session ( GetSystemMetrics(0x1000) -> nopnopnopnopnopnopnopnopnop xor eax, eax )

    ReplyDelete
    Replies
    1. thank you sir! this one works for windows xp sp3!

      Delete
  16. Has anyone got the pattern + offset + replacement for Windows 2003 Server sp2?

    ReplyDelete
  17. Hi!
    Will be a good news for us?
    Thanks in advance!

    ReplyDelete
    Replies
    1. Try this: http://goo.gl/iMbkrN
      I tested it only with XP, but should work with 7 too.
      Please, tell me if the patch works.

      Delete
    2. Hello, no worked Win7 SP1
      => unknown WinSCard.dll version or already patched!
      http://www.sendspace.com/file/ejh8np

      Delete
    3. This is a 64-bit version. The patch doesn't support such systems yet. Anyway, I'll try to add some.

      Delete
  18. Sorry for a long response..
    I tested on Windows 7 x32 and Windows XP SP3.
    On XP, it was disabled SFC like in this thread http://forums.comodo.com/general-discussion-off-topic-anything-and-everything-b1.0/-t22736.0.html with deleting sfc.dll and sfc_os.dll in windows recovery boot option. After this, i put in Windows\system32 patched winscard.dll (CRC-32: 39984d9e).
    I connected to this Windows XP from RDP, and etoken is visible, and all it is ok.

    http://higgs.rghost.ru/private/51198595/f87dbf5348622fb4b0763e2e0eac4151/image.png

    On Windows 7 x32, I changed to patched winscard.dll (CRC-32: 083f662d), but etoken it is not visible in etoken properties, and connect with vpn client is not possible.

    http://rghost.ru/private/51198545/79989c939e24b4caad897058bc57a7bb/image.png

    Thanks for your work
    Please, make this patch to work on windows 7 X64 also, because on Windows Server 2008R2 SP2, winscard.dll is also like winscard.dll on Windows 7 X64 SP1 (CRC-32: df8cdc58)

    ReplyDelete
    Replies
    1. Thanks for your feedback! I didn't test on Win7, thus I see a reason now ;)
      I'll fix the Win7x32 issue first and then add x64 support.

      Delete
    2. I was on holiday. Will work on this in the weekend.

      Delete
  19. I would be so happy if you can make this happen!

    ReplyDelete
    Replies
    1. Almost done on Win7. There was a Windows update at some point, so it's not so obvious now, as I described in the post :(

      Delete
  20. Replies
    1. Not yet, unfortunately. Still can't find what has been changed. However, I feel I'm close.

      Delete
  21. Ok. I got it. Writing the patch now. I'll post it today or tomorrow.

    ReplyDelete
    Replies
    1. Hi! I encountered the same problem. I reversed a list of functions to intercept or patch to work correctly on Win 7, but it does not work if the target process is started from the terminal session (it's ok for Console session). Can you write the list of functions to intercept?

      Delete
    2. What do you mean by "functions to intercept"? Have you tried the new version 0.2 of the patch? It's available at lifayk.com.

      Delete
    3. yes,but the hash does not match

      => unknown WinSCard.dll version or already patched!

      Delete
    4. Win 7 Ultimate x32 with all updates

      WinSCard.dll md5: 3C33562F4FAE3D58E47F662DCE07675E
      SCardSvr.dll md5: 8FC518FFE9519C2631D37515A68009C4

      may be the best idea would be not to check the hashes of files, but do a search for masks?

      Delete
    5. Could you send these files to me please?

      Delete
    6. http://www.sendspace.com/file/u5o117

      Could you tell what fucntion/code you're trying to modify in scardsvr.dll file ?

      Delete
    7. or upload please your version of scardsvr.dll

      Delete
    8. I assume you don't have a service pack installed. Try the scpatch 0.3. It works with your version now.

      Delete
  22. The patch is available at my new site: lifayk.com

    ReplyDelete
  23. Replies
    1. Run out of memory. Fixed it.

      Delete
  24. http://lifayk.com/files/scpatch0.3.zip

    ReplyDelete
    Replies
    1. Added the link to the post above as an update.

      Delete
  25. I tested on Windows 7 x64 SP1.
    It works!

    Thank you very much!

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. After turning of System File Protection on Windows 7 x64, I still cannot copy the modified .dlls back to system32. See access denied error below. Same error in GUI/Explorer.

      C:\Users\john\Desktop\scpatch0.3>copy *.dll c:\windows\system32\
      SCardSvr.dll
      Overwrite c:\windows\system32\SCardSvr.dll? (Yes/No/All): Yes
      Access is denied.
      WinSCard.dll
      Overwrite c:\windows\system32\WinSCard.dll? (Yes/No/All): Yes
      Access is denied.
      0 file(s) copied.

      Delete
    3. By default, your are not the owner of these files. You need to make yourself an owner. Also, the file that you want to overwrite can be used by another application, so you can rename it, but not delete.

      Delete
    4. I have taken ownership of WinScard.dll and SCardSvr.dll and successfully copied them to System32 on Windows 7 64k. Your patch worked in the SafeNet GUI interface in a Remote Desktop Session. The token shows as if it is loaded. However Adobe Acrobat and an iText program do not see the token as loaded. Microsoft Word DOES see the token loaded and can sign. This is a SafeNet 5100 USB Token. I wonder what Microsoft Office 2010 crypto interface it is using and why the others cannot.
      Thanks for all your work.
      John

      Delete
  26. Thank lifayk, any news on w2k12 r2?

    ReplyDelete
    Replies
    1. Do you need it? :)
      Right now, there are many interesting things going on around and I don't have time for tokens. However, I will try to add this os asap. Youl'll find it at www.lifayk.com

      Delete
  27. Hello, need support Win 8, and Win 2012 r2
    scardsvr.dll winscard.dll https://www.sendspace.com/file/1aatfy

    ReplyDelete
  28. Hi Lifayk and everybody. We need this patch to support Windows 8.1 x64. I'm ready to pay this work, anybody can do this patch?

    ReplyDelete
    Replies
    1. I'm on it. Hope it's not diff so much.

      Delete
    2. Nice. Can you please write me email to anatoly.pashin@gmail.com so we can discuss ETA and price?

      Delete
    3. Still no reply from you. Ping please.

      Delete
  29. This comment has been removed by the author.

    ReplyDelete
  30. I also have problems with win7 64, ask for help

    ReplyDelete
  31. I found a typo in your article, the real function name to patch is:
    InTSRedirectModeWithContext

    Also I tried to patch version for Windows 8.1, but it uses different technique to detect the session is TS or not.

    ReplyDelete
  32. Any update on supporting Windows 2012?

    Thanks in advance.

    ReplyDelete
  33. Thanks for sharing this with us. But I can't get it to work. Found the function InTSRedirectModeWithContext, patched it, but now the service wont start.

    Windows 7 Pro x64
    WinSCard.dll version: 6.1.7601.17514

    ReplyDelete
  34. Any update on supporting windows 8.1 PRO x64 or windows 10 pro x64.

    Thanks

    ReplyDelete
  35. Hello! Lifayk please support version Windows 2012R2 х64. Very needed...

    ReplyDelete
  36. Thank you so much. Worked fine on a Windows 2008R2 x64 machine. RuToken and ETokens now available through RDP connection.

    ReplyDelete
  37. Привет а можете скинуть пропатченную dll для Win7 sp1 буду примного благодарен

    ReplyDelete
    Replies
    1. лови, модифицированные dll и сам патч выложенный тут ранее автором темы:
      http://rghost.ru/private/6nQXpgGsG/c152a8d0aeb8f4f7fbb20400ba441936

      Delete
    2. Будь добр, перезалей архив.

      Заранее спасибо.

      Delete
  38. hi lifayk,
    I'm trying to make this mod manually, but i'm still with this problem,
    can you send-me a patch?
    You site is off at this time.
    My os is Windows 7 x64 SP1 Version 6.1.7601
    My email is erley.adam@gmail.com
    Best regards.

    ReplyDelete
  39. archive pass scpatch
    http://my-files.ru/i9kr0d
    http://files.d-lan.dp.ua/download?file=43049f224103ea1fa35335b61ca9254a
    https://www.sendspace.com/file/sdrw6q
    http://www92.zippyshare.com/v/dEa24iXj/file.html
    http://filesupload.ru/download/free/zmpmalll5q8x
    http://www.filehost.ro/3172066580/SCpatch0_3_rar/

    ReplyDelete
    Replies
    1. Hi alex ever file is password protect is it possible to download ? are there a price to pay ? how much cost the patch for windows 2012 r2 64 bit ?
      best regards Antonello ventre

      Delete
  40. Hi Lifayk
    Thanks for the great work.
    I have Windows Server 2012R2 and when I start your tool it throws the error unknown WinSCard.dll version!
    Thanks again and Best Regards
    Andreas

    ReplyDelete
  41. Кто патчил Windows 8.1 PRO? Поделитесь патчеными WinSCard.dll версия 6.3.9600.17415.
    Размер х86 - 169984, х64 - 242176. Нужны и под х86, и под х64. Заранее благодарен. В х86 версии замена ряда "0F B6 45 FF" на "33 C0 90 90" не принесла результата, в х64 ряд обнаружен не был.

    ReplyDelete
  42. Hi Lifayk
    Could you please assist with Windows 2012R2 ?
    Need it rellay urgent. My E-Mail is : andy1976@gmx.de

    Thanks and best Regards
    Andreas

    ReplyDelete
  43. Any news regarding Win 2012R2 ?

    Thanks

    ReplyDelete
  44. Hi Lifayk,

    Your site seems to be down. I'm trying to enable Smartcard from inside RDP in Windows 7 32 bit. ..
    thanks,
    M.

    ReplyDelete
  45. This comment has been removed by the author.

    ReplyDelete
  46. Windows 2003 R2
    winscard.dll
    021CF 40 => 90
    07734 68 00 10 00 00 FF 15 9C 11 2C 72 85 => 90 90 90 90 90 90 90 90 90 90 90 33
    scardsvr.exe
    07827 05 => 00

    ReplyDelete
  47. Hi there

    could someone help me with Windows 2012 R2 ?

    Thanks
    Andreas

    ReplyDelete
  48. I NEED! Windows 2008 R2 X64 :)

    ReplyDelete
  49. This comment has been removed by the author.

    ReplyDelete
  50. Dll for Windows Server 2008R2

    http://my-files.ru/x74bmd

    ReplyDelete
  51. Any chance for patch for windows 7 64-bit, please?

    ReplyDelete
    Replies
    1. my email igorlan@onet.pl

      Delete
    2. http://my-files.ru/x74bmd this dll for windows server & windows 7 x64 (working java only) edit bat file for your user

      Delete
  52. Hi alex ever file is password protect is it possible to download ? are there a price to pay ? how much cost the patch for windows 2012 r2 64 bit ?
    best regards Antonello ventre

    ReplyDelete
  53. Hello , is there any solution for Windows Server 2012 r2 ?

    ReplyDelete
  54. On the off chance that an essayist uses any sort of relieving data or actualities, then it prompts put a negative impression to client's mind. It allows to others to raise question on your composition ability. So keep your written work far from questions.
    LENOVO WinServ 2012 R2 Foundation

    ReplyDelete