Версия ПО: Единый Клиент 2.6 — 2.9, Единая Библиотека 2.0.0.1500 — 2.1.3.1900
Токены: Любые
Проблема:
При подключении по RDP к удалённому компьютеру с установленным «Единым Клиентом JaCarta» запуск приложения завершается ошибкой:
Единый Клиент 2.6 — 2.7 — «Невозможно запустить приложение. Невозможно проинициализировать cryptoki библиотеку ‘jcPKCS11-2.dll’».
Единый Клиент 2.8 – «Служба управления смарт-картами не запущена. Для продолжения работы необходимо её запустить».
Единый Клиент 2.9 – «Невозможно подключиться к службе управления смарт-картами».
При этом, служба смарт-карт на удалённом компьютере запущена. Внутри RDP-сессии служба смарт-карт также определяется, как запущенная.
Причина:
- Не запущена служба смарт-карт на локальной машине. Архитектурой RDP-сессии, разработанной Microsoft, не предусмотрено использование ключевых носителей, подключенных к удалённому компьютеру, поэтому в RDP-сессии удалённый компьютер использует службу смарт-карт локального компьютера. Из этого следует что, запуска службы смарт-карт внутри RDP-сессии недостаточно для нормальной работы.
- Служба управления смарт-картами на локальном компьютере запущена, но недоступна для программы внутри RDP-сессии из-за настроек Windows и/или RDP-клиента.
Решение:
- Запустите службу смарт-карт на локальной машине, с которой вы инициируете сеанс удалённого доступа. Настройте её автоматический запуск при старте компьютера.
- Разрешите использование локальных устройств и ресурсов во время удалённого сеанса (в частности, смарт-карт). Для этого, в диалоге «Подключение к удалённому рабочему столу» в параметрах выберите вкладку «Локальные ресурсы», далее в группе «Локальные устройства и ресурсы» нажмите кнопку «Подробнее…», а в открывшемся диалоге выберите пункт «Смарт-карты» и нажмите «ОК», затем «Подключить».
- Убедитесь в сохранности настроек RDP-подключения. По умолчанию они сохраняются в файле Default.rdp в каталоге «Мои Документы» Проследите, чтобы в данном файле присутствовала строчка «redirectsmartcards:i:1».
- Убедитесь в том, что на удалённом компьютере, к которому вы осуществляете RDP-подключение, не активирована групповая политика
[Computer ConfigurationAdministrative TemplatesWindows ComponentsTerminal ServicesClientServer data redirectionDo not allow smart card device redirection] -[Конфигурация компьютераадминистративные шаблоныкомпоненты windowsслужбы удалённых рабочих столовузел сеансов удалённых рабочих столовперенаправление устройств и ресурсовНе разрешать перенаправление устройства чтения смарт-карт]
Если она включена (Enabled), то отключите её, и перегрузите компьютер. - Если у вас установлена Windows 7 SP1 или Windows 2008 R2 SP1 и вы используете RDC 8.1 для соединения с компьютерами под управлением Windows 8 и выше, то вам необходимо установить обновление для операционной системы https://support.microsoft.com/en-us/kb/2913751
Примечание:
Если вы используете RDP-клиенты сторонних производителей, например, работая в среде Linux, то они должны поддерживать корректное перенаправление запросов из RDP-сессии на локальную службу смарт-карт с учётом версии RDP-сервера, к которому осуществляется подключение.
Внимание!
Работа в сессии RDP с ключевым носителем, подключённым непосредственно к серверу, не является корректной.
- Remove From My Forums
-
Question
-
Hi all,
I don’t understand why this code don’t give the tru infos about the HSM
/***/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;namespace ConsoleApplication2
{
class Program
{
[StructLayout(LayoutKind.Sequential)]
public struct CK_VERSION {
public byte major;
public byte minor;
}
[StructLayout(LayoutKind.Sequential)]
public struct CK_INFO
{
public CK_VERSION cryptokiVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)]
public string manufacturerID;
public UInt32 flags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)]
public string libraryDescription;
public CK_VERSION libraryVersion;
}
[DllImport(«D:/Program Files/Eracom/ProtectToolkit C SDK/bin/sw/cryptoki.dll», SetLastError = true)]
//[MarshalAs(UnmanagedType.U4)]
private static extern UInt32 C_GetInfo(out CK_INFO pInfo);
// [MarshalAs(UnmanagedType.U4)]static void Main(string[] args)
{
CK_INFO info = new CK_INFO();
C_GetInfo(out info);
Console.WriteLine(«le byte majeur est : «+info.cryptokiVersion.major);
Console.ReadLine();
Console.WriteLine(«le byte mineur est : » + info.cryptokiVersion.minor);
Console.ReadLine();
Console.WriteLine(«le manufacturier est :» + info.manufacturerID);
Console.ReadLine();
Console.WriteLine(«la description de la librairie est :» + info.libraryDescription);
Console.ReadLine();
Console.WriteLine(«la versiontion de la librairie est (maj):» + info.libraryVersion.major);
Console.ReadLine();
Console.WriteLine(«la versiontion de la librairie est (min):» + info.libraryVersion.minor);
Console.ReadLine();
}
}
}/***/
regards
Can’t sign data with Rutoken ECP 2.0
OpenSC version 0.16.0_pre1.
How to repoduce:
pkcs15-init --erase-card -p rutoken_ecp
pkcs15-init --create-pkcs15
pkcs15-init --store-pin --label "hexum" --id 02
pkcs15-init -G rsa/2048 --auth-id 02 --label "homeserver" --public-key-label "homeserver.pub"
pkcs15-tool -D
...
Private RSA Key [homeserver]
Object Flags : [0x3], private, modifiable
Usage : [0x4], sign
Access Flags : [0x1D], sensitive, alwaysSensitive, neverExtract, local
ModLength : 2048
Key ref : 1 (0x1)
Native : yes
Path : 3f001000100060020001
Auth ID : 02
ID : 3b22ad5f956a4a51e46a5f426afbe280d86ac509
MD:guid : {e7600859-c83f-627c-7317-8e2cda8cabba}
...
pkcs11_spy.txt
pkcs11-tool -l -s -m SHA256-RSA-PKCS --id 3b22ad5f956a4a51e46a5f426afbe280d86ac509 -i i --module /usr/lib64/pkcs11-spy.so
Using slot 1 with a present token (0x1)
Logging in to "Rutoken ECP (hexum)".
Please enter User PIN:
Using signature algorithm SHA256-RSA-PKCS
error: PKCS11 function C_SignFinal failed: rv = CKR_GENERAL_ERROR (0x5)
Aborting.
file i — random 256 byte file.
Attached pkcs11_spy.txt — file with psy log.
Please guide me to do further diagnostics.
Please try signing a file of 245 bytes (or even smaller), and report the result.
Actually, based in the algorithm you selected, try a 32-byte file and report the result.
Thank you for answer!
I’ve run singing with 32 byte long file.
ls -lh 32b_random
-rw-r--r-- 1 hexum hexum 32 фев 28 11:42 32b_random
OPENSC_DEBUG=9 pkcs11-tool -l -s -m SHA256-RSA-PKCS --id 3b22ad5f956a4a51e46a5f426afbe280d86ac509 -i 32b_random --module /usr/lib64/pkcs11-spy.so
pkcs11_spy_32b.txt
Error has not changed.
Strange place in console debug output.
debug9_log.txt
0x7fe0bbf3f700 20:51:28.234 [opensc-pkcs11] iso7816.c:126:iso7816_check_sw: Unknown SWs; SW1=69, SW2=89
0x7fe0bbf3f700 20:51:28.234 [opensc-pkcs11] card.c:434:sc_unlock: called
0x7fe0bbf3f700 20:51:28.234 [opensc-pkcs11] card-rtecp.c:382:rtecp_cipher: APDU transmit failed: Card command failed
First, with pkcs11-tool you don’t need to use pkcs11-spy. Second, it appears that you fail to unlock the token, somehow. The way I interpret the log, PIN unlocking fails. I’ll let somebody more experienced than myself take it from here.
When I use wrong pin error CKR_PIN_INCORRECT rises insted of CKR_GENERAL_ERROR.
So the error in other place.
Try master.
«It works for me» with actual master and token «Aktiv Rutoken ECP», ATR:3B 8B 01 52 75 74 6F 6B 65 6E 20 44 53 20 C1
The used token is 2-3 years old — not sure.
I’ve installed latest version and repeated all steps.
The error kept the same.
Using reader with a card: Aktiv Rutoken ECP 00 00
3b:8b:01:52:75:74:6f:6b:65:6e:20:44:53:20:c1
I do not see any outstanding difference in two logs.
There is my command sequence.:
./build/bin/pkcs15-init --erase-card
./build/bin/pkcs15-init -C --label "OT-RuToken" -P --auth-id 02 --so-pin "87654321" --so-puk "" --pin "12345678" --finalize
./build/bin/pkcs15-init -G rsa/1024 --pin 12345678 --auth-id 02 --label "RSA 1024"
./build/bin/pkcs15-init -G rsa/2048 --pin 12345678 --auth-id 02 --label "RSA 2048"
./build/bin/pkcs11-tool --module ./build/lib/opensc-pkcs11.so -l -s -m SHA256-RSA-PKCS --id 3228192c204855dbde29c5aca174194c8ce08a01 -i ../test-data/data-24bytes.txt
./build/bin/pkcs11-tool --module ./build/lib/opensc-pkcs11.so -M
./build/bin/pkcs11-tool --module ./build/lib/opensc-pkcs11.so -l -s -m SHA256-RSA-PKCS --id 81e0a95372252e485dd7a2eac201ec7115a3f70a -i ../test-data/data-256bytes.txt
Try to add —finalize to your init token command.
Try to add —finalize to your init token command.
Absolutly right. Use ‘—finalize’ to set card state with allowed sign.
Thats work!
I did not add it at pin creation state. I’ve just run pkcs15-init --finalize
with that I had and magic happened.
Now I can sign data and pass ssh authentication.
I still can add new keys. What thing was finalized? What is the purpose of this option?
What thing was finalized?
Not sure about details for RuToken, but finalized activates the ACLs of the files, objects, … that were created during init/personalization phase. Without it you still can access (create, update, … not use) objects without authentication (by PIN for ex.).
Normally, in this state the crypto operations are not allowed.
Please, close the issue, if you consider that it was resolved.
Strange… PIN was asked every time.
Error CKR_GENERAL_ERROR is not clear for end user. Is there a way to clarify error message in case of not completed finalization?
Not sure about details for RuToken, but finalized activates the ACLs of the files, objects, …
Of course, It’s true for Rutoken ECP
Error CKR_GENERAL_ERROR is not clear for end user. Is there a way to clarify error message in case of not completed finalization?
Could you please propose PKCS#11 error code for this case? (see page 110: C_SignFinal Return values)
CKR_CRYPTOKI_NOT_INITIALIZED is best match I think.
But it’s so sad to be limited with this spec. Furthermore it doesn’t not define this constant meaning…
The best thing we can do is to print something like «You need to finalize token initialization. Please run pkcs11-tool —finalize to do so.»
@hexum
I am afraid you are asking too much. Sign operation returns something like ‘internal-error’, in better case ‘not-allowed’. With there, on the upper framework level to guess that the token is not initialized…
@sfff
Could you please propose PKCS#11 error code for this case?
Not only. You need to find an appropriate sc-error to associate it with SW 6989, returned by card, and then to associate this sc-error with CKR_XX.
Actually I do not see appropriate sc-error,
but it’s true — we always can add a new one and associate it with some CKR NOT-INITIALIZED.
If it will be done, we can start page with error description. I found nothing about error CKR_CRYPTOKI_NOT_INITIALIZED on the Internet.
@hexum
CKR_CRYPTOKI_NOT_INITIALIZED is best match I think.
Unfortunately, PKCS#11 Spec Page 63:
CKR_CRYPTOKI_NOT_INITIALIZED: This value can be returned by any function other than
C_Initialize and C_GetFunctionList. It indicates that the function cannot be executed because the
Cryptoki library has not yet been initialized by a call to C_Initialize.
@viktorTarasov
Not only. You need to find…
Yes of course. Thanks for details.
I will reopen this when I will be able to support development with patch.