Giter Club home page Giter Club logo

Comments (82)

frankmorgner avatar frankmorgner commented on July 18, 2024 1
  • According to the SC-HSM user manual (I only had v2.4 at hand), SELECT doesn't seem to support a variable value for Le and MUST be 0x00 (or absent if P2 == 0x0C).
  • Le also MUST be exactly 0x00 for Generate Session PIN (INS=0x5A), General Authenticate (INS=86), Import DKEK (INS=52), Manage PKA (INS=54)
  • Interestingly, the Le for Enumerate Objects (sc_hsm_list_files), Generate Asymmetric Key Pair (sc_hsm_generate_keypair), Wrap Key (sc_hsm_wrap_key) similarly MUST be 0x000000 (i.e. extended length)

All of the above commands are explicitly setting the Le to 0 (and encode extended lenght if needed) except the select command, which instead calls the iso7816 driver for selecting. A quick way for fixing this, would be to force Le = 0 in the select:

diff --git a/src/libopensc/card-sc-hsm.c b/src/libopensc/card-sc-hsm.c
index e68975077..a236a2cbc 100644
--- a/src/libopensc/card-sc-hsm.c
+++ b/src/libopensc/card-sc-hsm.c
@@ -151,6 +151,8 @@ static int sc_hsm_select_file_ex(sc_card_t *card,
 	sc_hsm_private_data_t *priv = (sc_hsm_private_data_t *) card->drv_data;
 	sc_file_t *file = NULL;
 	sc_path_t cpath;
+	size_t card_max_recv_size = card->max_recv_size;
+	size_t reader_max_recv_size = card->reader->max_recv_size;
 
 	if (file_out == NULL) {				// Versions before 0.16 of the SmartCard-HSM do not support P2='0C'
 		rv = sc_hsm_select_file_ex(card, in_path, forceselect, &file);
@@ -184,7 +186,11 @@ static int sc_hsm_select_file_ex(sc_card_t *card,
 				&& in_path->aid.len == sc_hsm_aid.len
 				&& !memcmp(in_path->aid.value, sc_hsm_aid.value, sc_hsm_aid.len))) {
 		if (!priv || (priv->dffcp == NULL) || forceselect) {
+			/* Force use of Le = 0x00 in iso7816_select_file as required by SC-HSM */
+			card->max_recv_size = card->reader->max_recv_size = 256;
 			rv = (*iso_ops->select_file)(card, in_path, file_out);
+			card->max_recv_size = card_max_recv_size;
+			card->reader->max_recv_size = reader_max_recv_size;
 			LOG_TEST_RET(card->ctx, rv, "Could not select SmartCard-HSM application");
 
 			if (priv) {
@@ -213,14 +219,24 @@ static int sc_hsm_select_file_ex(sc_card_t *card,
 			*file_out = file;
 			return SC_SUCCESS;
 		} else {
+			/* Force use of Le = 0x00 in iso7816_select_file as required by SC-HSM */
+			card->max_recv_size = card->reader->max_recv_size = 256;
 			sc_path_t truncated;
 			memcpy(&truncated, in_path, sizeof truncated);
 			truncated.len = in_path->len - 2;
 			memcpy(truncated.value, in_path->value+2, truncated.len);
-			return (*iso_ops->select_file)(card, &truncated, file_out);
+			rv = (*iso_ops->select_file)(card, &truncated, file_out);
+			card->max_recv_size = card_max_recv_size;
+			card->reader->max_recv_size = reader_max_recv_size;
+			return rv;
 		}
 	}
-	return (*iso_ops->select_file)(card, in_path, file_out);
+	/* Force use of Le = 0x00 in iso7816_select_file as required by SC-HSM */
+	card->max_recv_size = card->reader->max_recv_size = 256;
+	rv = (*iso_ops->select_file)(card, in_path, file_out);
+	card->max_recv_size = card_max_recv_size;
+	card->reader->max_recv_size = reader_max_recv_size;
+	return rv;
 }

An alternative would be to explicitly implement the APDU encoding for SELECT in sc-hsm instead of forwarding to iso7816.

I hope the above suggestion fixes the problem.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024 1

from opensc.

Jakuje avatar Jakuje commented on July 18, 2024

We will probably need some more logs to see what is going on there and why it fails.

If you mean the wiki by the documnetation, you can fix it already using a PR to https://github.com/OpenSC/Wiki/blob/master/Compiling-on-Cygwin.md as described in the footer of wiki.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

I will provide the logs ASAP.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

Is a PR possible by just creating a new branch and pull or do i need special permission?

from opensc.

Jakuje avatar Jakuje commented on July 18, 2024

Is a PR possible by just creating a new branch and pull or do i need special permission?

With normal GIthub workflow you should be good. You should be able to do the simple edits through the web UI too, which will end up in forking the project, creating a new branch with the changes and opening a new PR there.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

Ah, ok: need to fork, that was the question.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

Ok, PR has been created, logs following.

from opensc.

Jakuje avatar Jakuje commented on July 18, 2024

Thanks! What about the debug logs? Do they show something useful?

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

Sorry, due to usage of 0.22 on my current Win11 system (work) i have to compile on another machine. I suppose logs coming late this evening.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

Apollogizes. SC-reader in second laptop unexpected not working anymore. Very annoying. Logs following, sorry again.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

Apollogizes. SC-reader in second laptop unexpected not working anymore. Very annoying. Logs following, sorry again.

Still no progress, somehow reader seems broken :( ASAP logs follow.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

@Jakuje Attached the logs.

from opensc.

Jakuje avatar Jakuje commented on July 18, 2024

Thanks! @CardContact do you see something obvious in the log that could be incompatible with SC-HSM in recent OpenSC versions?
From the log, I see this is version 3.4

P:841; T:0x42949672976 13:34:46.036 [opensc-pkcs11] card.c:382:sc_connect_card: card info name:'SmartCard-HSM version 3.4', type:26000, flags:0x0, max_send/recv_size:238/254

and what is failing is in pkcs15 emulator pulling of the CVC:

P:841; T:0x42949672976 13:34:46.066 [opensc-pkcs11] pkcs15-sc-hsm.c:1283:sc_pkcs15emu_sc_hsm_init: called
P:841; T:0x42949672976 13:34:46.066 [opensc-pkcs11] card.c:850:sc_select_file: called; type=1, path=e82b0601040181c31f0201::
P:841; T:0x42949672976 13:34:46.067 [opensc-pkcs11] card.c:885:sc_select_file: returning with: 0 (Success)
P:841; T:0x42949672976 13:34:46.067 [opensc-pkcs11] card.c:850:sc_select_file: called; type=0, path=2f02
P:841; T:0x42949672976 13:34:46.067 [opensc-pkcs11] apdu.c:550:sc_transmit_apdu: called
P:841; T:0x42949672976 13:34:46.067 [opensc-pkcs11] card.c:471:sc_lock: called
P:841; T:0x42949672976 13:34:46.067 [opensc-pkcs11] card.c:513:sc_lock: returning with: 0 (Success)
P:841; T:0x42949672976 13:34:46.067 [opensc-pkcs11] apdu.c:515:sc_transmit: called
P:841; T:0x42949672976 13:34:46.067 [opensc-pkcs11] apdu.c:363:sc_single_transmit: called
P:841; T:0x42949672976 13:34:46.068 [opensc-pkcs11] apdu.c:367:sc_single_transmit: CLA:0, INS:A4, P1:0, P2:0, data(2) 0x7ffff79d0
P:841; T:0x42949672976 13:34:46.068 [opensc-pkcs11] reader-pcsc.c:325:pcsc_transmit: reader 'Alcor Micro USB Smart Card Reader 0'
P:841; T:0x42949672976 13:34:46.068 [opensc-pkcs11] reader-pcsc.c:326:pcsc_transmit: 
Outgoing APDU (8 bytes):
00 A4 00 00 02 2F 02 FE ...../..

P:841; T:0x42949672976 13:34:46.068 [opensc-pkcs11] reader-pcsc.c:244:pcsc_internal_transmit: called
P:841; T:0x42949672976 13:34:46.082 [opensc-pkcs11] reader-pcsc.c:335:pcsc_transmit: 
Incoming APDU (2 bytes):
67 00 g.

P:841; T:0x42949672976 13:34:46.082 [opensc-pkcs11] apdu.c:382:sc_single_transmit: returning with: 0 (Success)
P:841; T:0x42949672976 13:34:46.082 [opensc-pkcs11] apdu.c:539:sc_transmit: returning with: 0 (Success)
P:841; T:0x42949672976 13:34:46.082 [opensc-pkcs11] card.c:523:sc_unlock: called
P:841; T:0x42949672976 13:34:46.082 [opensc-pkcs11] iso7816.c:128:iso7816_check_sw: Wrong length
P:841; T:0x42949672976 13:34:46.082 [opensc-pkcs11] iso7816.c:741:iso7816_select_file: returning with: -1206 (Wrong length)
P:841; T:0x42949672976 13:34:46.083 [opensc-pkcs11] card.c:872:sc_select_file: 'SELECT' error: -1206 (Wrong length)
P:841; T:0x42949672976 13:34:46.083 [opensc-pkcs11] pkcs15-sc-hsm.c:256:read_file: Could not select EF
P:841; T:0x42949672976 13:34:46.083 [opensc-pkcs11] pkcs15-sc-hsm.c:262:read_file: Could not read EF
P:841; T:0x42949672976 13:34:46.083 [opensc-pkcs11] pkcs15-sc-hsm.c:418:sc_pkcs15emu_sc_hsm_decode_cvc: Could not decode card verifiable certificate: -1401 (Invalid ASN.1 object)
P:841; T:0x42949672976 13:34:46.083 [opensc-pkcs11] pkcs15-sc-hsm.c:1333:sc_pkcs15emu_sc_hsm_init: Could not decode EF.C_DevAut: -1401 (Invalid ASN.1 object)

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

But as i stated out "OpenSC 0.23.0 on Windows 11_x64" works like expected with the same SC-HSM card.
Maybe forgot setting an extended APDU length on CygWin build, as i remember there was a problem when the APDU size was too small with some SCs / Readers.

Could someone else please check with another SC-vendor on CygWin, thanx!

from opensc.

Jakuje avatar Jakuje commented on July 18, 2024

oh, missed that part that it works with different build. The logs looks like communication with the card is working ok. Could it be some missing dependency in the cygwin making some functionality unusable (zlib? openssl?). Can you compare output of the configure or config.h from our CI builds and from you cygwin?

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

oh, missed that part that it works with different build. The logs looks like communication with the card is working ok. Could it be some missing dependency in the cygwin making some functionality unusable (zlib? openssl?). Can you compare output of the configure or config.h from our CI builds and from you cygwin?

I will do so, i assume something is wrong with openssl changing to new api calls. APX 1-2 days...

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

oh, missed that part that it works with different build. The logs looks like communication with the card is working ok. Could it be some missing dependency in the cygwin making some functionality unusable (zlib? openssl?). Can you compare output of the configure or config.h from our CI builds and from you cygwin?

I will do so, i assume something is wrong with openssl changing to new api calls. APX 1-2 days...

Still in the pipe ... Too much projects in parallel ...

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

oh, missed that part that it works with different build. The logs looks like communication with the card is working ok. Could it be some missing dependency in the cygwin making some functionality unusable (zlib? openssl?). Can you compare output of the configure or config.h from our CI builds and from you cygwin?

Can you please state out where the CI build takes place / source / config files are located? I think i will write you some .md README files afterwards. I found the docker-container for building but no description how thw CI builds are triggered (or maybe i am blind).

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

oh, missed that part that it works with different build. The logs looks like communication with the card is working ok. Could it be some missing dependency in the cygwin making some functionality unusable (zlib? openssl?). Can you compare output of the configure or config.h from our CI builds and from you cygwin?

Can you please state out where the CI build takes place / source / config files are located? I think i will write you some .md README files afterwards. I found the docker-container for building but no description how thw CI builds are triggered (or maybe i am blind).

Ha, found it, just familiar with GitLab CI, github uses .github folder which is at the first position where programmers never have a look at 💣

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

@Jakuje Went through the CI build process (scripts), i have too less knowledge about github actions / CI. In which environment (Linux VM / Docker) the build-process is initiated?

I have some questions about the Mingw CI building.

  • What exactly does the Windown Minidriver? I could not find information on github.
  • Some questions about build.sh regarding Mingw integration
if [ "$1" == "mingw" -o "$1" == "mingw32" ]; then
	mkdir -p src/minidriver/CNG
	wget https://raw.githubusercontent.com/open-eid/minidriver/master/cardmod.h -O src/minidriver/CNG/cardmod.h
	if [ "$1" == "mingw" ]; then
		HOST=x86_64-w64-mingw32
	elif [ "$1" == "mingw32" ]; then
		HOST=i686-w64-mingw32
	fi
	unset CC
	unset CXX
	CFLAGS="-I$PWD/src/minidriver/CNG -Wno-error=unknown-pragmas" \
	CPPFLAGS="-DNTDDI_VERSION=0x06010000" \
	./configure --host=$HOST --with-completiondir=/tmp --disable-openssl --disable-readline --disable-zlib --enable-minidriver --enable-notify --prefix=$PWD/win32/opensc || cat config.log;
	make -j 4 V=1
	# no point in running tests on mingw

Why build with openssl and zlib disabled? ./configure --host=$HOST --with-completiondir=/tmp --disable-openssl --disable-readline --disable-zlib --enable-minidriver

if [ "$1" == "mingw" -o "$1" == "mingw32" ]; then
	# pack installed files
	wine "C:/Program Files/Inno Setup 5/ISCC.exe" win32/OpenSC.iss
fi

Whats happening here?

If you could provide me the information i am able to process much faster.

from opensc.

Jakuje avatar Jakuje commented on July 18, 2024

What exactly does the Windown Minidriver? I could not find information on github.

This is how opensc is integrated into the windows authentication system and tools. If you use pkcs11-tool, you will not get in touch with this. Generally windows provides some of its own, but allows third party to install their own, which is what OpenSC do:
https://learn.microsoft.com/en-us/windows-hardware/drivers/smartcard/smart-card-minidriver-overview

Why build with openssl and zlib disabled?

We likely do not have the dependencies under mingw under ubuntu.

Whats happening here?

This is Inno Setup, which craetes Windows installers. Its downloaded in here

if [ ! -f "$(winepath 'C:/Program Files/Inno Setup 5/ISCC.exe')" ]; then
/sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_99.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :99 -ac -screen 0 1280x1024x16
export DISPLAY=:99.0
[ -d isetup ] || mkdir isetup
pushd isetup
[ -f isetup-5.5.6.exe ] || wget http://files.jrsoftware.org/is/5/isetup-5.5.6.exe
sleep 5 # make sure the X server is ready ?
wine isetup-5.5.6.exe /SILENT /VERYSILENT /SP- /SUPPRESSMSGBOXES /NORESTART
popd

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

What exactly does the Windown Minidriver? I could not find information on github.

This is how opensc is integrated into the windows authentication system and tools. If you use pkcs11-tool, you will not get in touch with this. Generally windows provides some of its own, but allows third party to install their own, which is what OpenSC do: https://learn.microsoft.com/en-us/windows-hardware/drivers/smartcard/smart-card-minidriver-overview

Understood.

But, can you please state out where and which container (dockerfile) will be started for the build / CI process. I do not find somehow. Additionally provide me with some helpful documentation links about the github CI so i am able to understand faster.

from opensc.

Jakuje avatar Jakuje commented on July 18, 2024

The mingw builds are defined here in the syntax defined for github actions, they run in ubuntu-latest container:

https://github.com/OpenSC/OpenSC/blob/master/.github/workflows/linux.yml#L76

But the scripts are independent from the github actions and could be executed locally with docker/podman as described here:

https://github.com/OpenSC/OpenSC/blob/master/containers/README.md

There is opensc-mingw Containerfile containing basically the same instructions, running the same scripts as github actions do run:

https://github.com/OpenSC/OpenSC/blob/master/containers/opensc-mingw/Containerfile

from opensc.

dengert avatar dengert commented on July 18, 2024

Can you provide opensc-debug log using the working version of OpenSC?
Your comment: #2944 (comment) may be close to the problem.

It could be a config option or some change in OpenSC that is being more conservative in 0.23.0 on setting the sizes.

In you log at line 1698:
card.c:382:sc_connect_card: card info name:'SmartCard-HSM version 3.4', type:26000, flags:0x0, max_send/recv_size:238/254

The max_send/recv_size:238/254 looks way to small.

On an older device with builtin reader on Ubuntu i see:
card.c:382:sc_connect_card: card info name:'SmartCard-HSM version 1.2', type:26000, flags:0x0, max_send/recv_size:1232/65534
The card and the reader can use extended APDUs i.e. greater then 255/256

Do you have a different reader?

Can you try try the same code on Windows 10? (Help isolate if w10 to w11 changed something about reasder capabilities)

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

Can you provide opensc-debug log using the working version of OpenSC? Your comment: #2944 (comment) may be close to the problem.

It could be a config option or some change in OpenSC that is being more conservative in 0.23.0 on setting the sizes.

In you log at line 1698: card.c:382:sc_connect_card: card info name:'SmartCard-HSM version 3.4', type:26000, flags:0x0, max_send/recv_size:238/254

The max_send/recv_size:238/254 looks way to small.

On an older device with builtin reader on Ubuntu i see: card.c:382:sc_connect_card: card info name:'SmartCard-HSM version 1.2', type:26000, flags:0x0, max_send/recv_size:1232/65534 The card and the reader can use extended APDUs i.e. greater then 255/256

I remember this is reader-driver-specific (i did this on a very old windows machine). The reader-hw settings are handled by OpenSC in Linux and CygWin similar? And if no what is the difference?

Do you have a different reader?

Yes, imported from our office, also i am able to compile on a different machine or VM. Results following.

Can you try try the same code on Windows 10? (Help isolate if w10 to w11 changed something about reasder capabilities)

Queued.

from opensc.

dengert avatar dengert commented on July 18, 2024

Google for: "alcor micro usb smart card reader"
There appears to be some updates for this reader for Windows.

Or try using device manager to look for new Windows 11 driver.

ALso try setting env OPENSC_DRIVER=sc-hsm to make sure OpenSC code trying to determine a card driver causes the the max_send_recv and max_recv_size to be set with with the strange numbers before the sc-hsm driver it tested.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

Google for: "alcor micro usb smart card reader" There appears to be some updates for this reader for Windows.

Or try using device manager to look for new Windows 11 driver.

ALso try setting env OPENSC_DRIVER=sc-hsm to make sure OpenSC code trying to determine a card driver causes the the max_send_recv and max_recv_size to be set with with the strange numbers before the sc-hsm driver it tested.

On Win11 with with CygWin installed in parallel on Win11 native OpenSC 0.23.0 works fine, CygWin OpenSC 0.23.0 compiles without problems but does not work, OpenSC version before works with compatibility OpenSSL (old) API calls only.

from opensc.

dengert avatar dengert commented on July 18, 2024

That's good. By current, you mean 0.24.0 that was just released Dec 13, 2023?

If there is nothing else, you can close the ticket.

from opensc.

dengert avatar dengert commented on July 18, 2024

Here is something else to try to see if problems are with reader sizes:

card-max_sizes.diff.txt

It will list the sizes in opensc-debug log will trying to match a driver.

OPENSC_DRIVER=sc-hsm is a run time option to tell OpenSC to only try the sc-hsm driver.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

Here is something else to try to see if problems are with reader sizes:

card-max_sizes.diff.txt

It will list the sizes in opensc-debug log will trying to match a driver.

I will apply patch tomorrow.

OPENSC_DRIVER=sc-hsm is a run time option to tell OpenSC to only try the sc-hsm driver.

Good to know, this should be in every users .bashrc or similar.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

0.23.0 and 0.24.0 same behaviour with or without OPENSC_DRIVER=sc-hsm environment variable set.

Also fresh Cygwin install with exact package versions from Cygwin install documentation.

$ pkcs11-tool -O
error: PKCS11 function C_GetSlotInfo failed: rv = CKR_DATA_INVALID (0x20)
Aborting.

Logs for 0.24.0 (Cygwin)

OPENSC_DRIVER=sc-hsm env set and card-size-output-patch applied.

opensc-debug-cygwin.txt

Logs for 0.24.0 (Win11)

opensc-debug-cygwin.txt

At line 541 we can see: this is the first time recv_size is > max_send/recv_size:238/254 compared to win11 logs.

P:84; T:8388 2023-12-15 20:44:37.426 [opensc-pkcs11] reader-pcsc.c:244:pcsc_internal_transmit: called
P:84; T:8388 2023-12-15 20:44:37.472 [opensc-pkcs11] reader-pcsc.c:335:pcsc_transmit: 
Incoming APDU (258 bytes):
7F 21 81 E4 7F 4E 81 9D 5F 29 01 00 42 0D 44 45 .!...N.._)..B.DE
44 49 43 43 30 34 30 30 30 30 31 7F 49 4F 06 0A DICC0400001.IO..
04 00 7F 00 07 02 02 02 02 03 86 41 04 41 37 F7 ...........A.A7.
5D 4F 73 22 80 F0 70 71 58 8F BC 0C CF 91 EE BF ]Os"..pqX.......
47 6C 2A 47 B4 4D 33 60 BC 7F 13 16 AA 6C 31 09 Gl*G.M3`.....l1.
1B 14 08 E8 57 96 13 3C 31 94 DA 83 1A AB DB 37 ....W..<1......7
82 82 04 34 A2 82 B0 EF 26 0F 30 DB 92 5F 20 10 ...4....&.0.._ .
44 45 43 43 30 34 30 31 37 30 32 30 30 30 30 30 DECC040170200000
7F 4C 10 06 0B 2B 06 01 04 01 81 C3 1F 03 01 01 .L...+..........
53 01 00 5F 25 06 02 00 01 01 01 03 5F 24 06 02 S.._%......._$..
03 01 00 02 01 5F 37 40 2D 42 E4 8A 9D 3D 8D 7F ....._7@-B...=..
36 48 BC CA 77 CB 04 3A 61 61 36 C2 C9 39 B8 71 6H..w..:aa6..9.q
F8 E5 5D 96 21 2F CE AA 5B 8E 85 BC 55 86 8B 4A ..].!/..[...U..J
4F 6B E9 A5 7E 8E B7 EC 4B 40 20 47 43 D9 A9 A5 Ok..~...K@ GC...
80 FE 92 87 6F 76 DF 8F 7F 21 81 E2 7F 4E 81 9B ....ov...!...N..
5F 29 01 00 42 0E 44 45 53 52 43 41 43 43 31 30 _)..B.DESRCACC10
90 00                                           ..

Now the question is: max_receive_size wrong set in 0.23 and 0.24?

I am not to deep in the binary transfer protocol, but i think in APDU multi-byte transfer 2 control registers P1 and P2 (1 word = 2 bytes) are used which adresses the payload-address-space from 0-65536 +- some bytes.

Important

Cygwin uses only 1 byte (max 238/254 bytes one payload) which in my oppinion indicates that setting or getting a) the readers or b) the cards properties in a wrong way. I started looking in the source code; i definately need more time to understand the fundamentals.

My proposal: i will patch version 0.22 Cygwin and compare the max_receive_size here and i assume it is > 254. But also the log-compare could give us a clue in which layer the bug resides in.

  1. APDU send: same in Cygwin and Win11
Outgoing APDU (17 bytes):
00 A4 04 00 0B E8 2B 06 01 04 01 81 C3 1F 02 01 ......+.........
FE          
  1. APDU recv: same
Incoming APDU (14 bytes):
6F 0A 82 01 78 85 05 00 01 05 03 04 90 00 o...x.........
  1. APDU send: same
Outgoing APDU (8 bytes):
00 A4 08 00 02 2F 00 FE ...../..
  1. APDU recv: same
Incoming APDU (2 bytes):
6A 86 j.
  1. APDU send: mismatch 1 byte

Left side: Cygwin Right side: Win11

Outgoing APDU (8 bytes):            Outgoing APDU (8 bytes):
00 A4 00 00 02 2F 02 FE ...../..    00 A4 00 00 02 2F 02 00 ...../..

@dengert do you have deeper protocol-insights about the binary data transfer? I have read the pkcs11 and pkcs15 specifications with a deeper focus on encrypting so i am the wrong man.

Argh, i actually see that the two logs are Cygwin: pkcs11-tool --list-slots and Win11: pkcs11-tool -O, please be aware of.

from opensc.

dengert avatar dengert commented on July 18, 2024

There are too many variables in this case. Cygwin, the reader, code changes in 23.

I tried installing Cygwin on my W11, and got as far as trying to use the Cygwin version of git which says: "Cloning into 'OpenSC'..." then ends with no error an no clone.

The reader appears to have have max send size of 255 and recv size of 256, which means no extended APDUs.

Commit aadd82b in card-sc-hsm.c aadd82b#diff-830e017fcc7ac0fc60f710cc6aced3b2531462147e2d4d08a1b02fbec468c812R1812-R1851
appears set the limits send: 255-17=238 (0xEE) and recv: 256-2= 254 (0xFE) from lines 1821 and 1822
"/* Assume that card supports sending with extended length APDU and without limit */"
" card->max_recv_size = 0;" but max extended recv with extended APDU would be 65K.

Is you w11 native or a VM?

Can you try using the 0.24.0 windows version: https://github.com/OpenSC/OpenSC?tab=readme-ov-file#downloads i.e. eliminating the use of for Cygwin.

Do you have a Linux, Linux VM or MacOS system?

Do you really need CygWin?

Try a reader that supports extended APDUs.

Is you card a newer version we have not seen before?
Was it initialized?

@CardContact @istr any comments?

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

There are too many variables in this case. Cygwin, the reader, code changes in 23.

I tried installing Cygwin on my W11, and got as far as trying to use the Cygwin version of git which says: "Cloning into 'OpenSC'..." then ends with no error an no clone.

The reader appears to have have max send size of 255 and recv size of 256, which means no extended APDUs.

I think this is not the case, the reader is able to handle APDU 64Kbyte (Thinkpad t490s integrated reader). On Win11 (here on the same machine also Cygwin is installed on) everything is working fine (See second Log output, but here i am not able to patch the min/max log output), also 0.22 works fine. I assume the sizes are 64k here.

Important

I will compile 0.22 with the min/max output on Cygwin (@dengert: same diff patchable?) and if min/max has 64k thats the evidence.

Commit aadd82b in card-sc-hsm.c aadd82b#diff-830e017fcc7ac0fc60f710cc6aced3b2531462147e2d4d08a1b02fbec468c812R1812-R1851 appears set the limits send: 255-17=238 (0xEE) and recv: 256-2= 254 (0xFE) from lines 1821 and 1822 "/* Assume that card supports sending with extended length APDU and without limit */" " card->max_recv_size = 0;" but max extended recv with extended APDU would be 65K.

Is you w11 native or a VM?

Native

Can you try using the 0.24.0 windows version: https://github.com/OpenSC/OpenSC?tab=readme-ov-file#downloads i.e. eliminating the use of for Cygwin.

0.24.0 Not working
0.23.0 Working

This seems like a change from 0.23 to 0.24 caused this. On Cagwin 0.23 also does not work, just 0.22 with old OpenSSL API calls.

Do you have a Linux, Linux VM or MacOS system?

Do you really need CygWin?

With Cygwin you are able to use command line ssh / scp without USB-redirection to VM. This sometimes does not work expecially with exactly this "internal" laptop SC-reader ;(

Try a reader that supports extended APDUs.

Is you card a newer version we have not seen before? Was it initialized?

@CardContact @istr any comments?

from opensc.

istr avatar istr commented on July 18, 2024

The diff is too large for me to give a quick answer to that. I see lots of changes in the pkcs15 logic between 0.22 and 0.24. And I am not acquainted in depth with the pkcs15 code.

What sounds suspicious to me is this statement:

Cygwin uses only 1 byte (max 238/254 bytes one payload) which in my opinion indicates that setting or getting a) the readers or b) the cards properties in a wrong way.

Given that everything works OK in Windows "native", this sounds like a specific compile-time problem with int / size_t stuff in Cygwin. I encountered something similar in a different context way back in the past with Cygwin. But that's just a shot in the dark.

@dengert is right to say that:

It could be a config option or some change in OpenSC that is being more conservative in 0.23.0 on setting the sizes.

git diff 0.22.0 0.24.0 src/libopensc/card.c (only the relevant chunk follows)

diff --git a/src/libopensc/card.c b/src/libopensc/card.c
index f2c6ca5a..817d2b51 100644
--- a/src/libopensc/card.c
+++ b/src/libopensc/card.c
@@ -943,25 +949,57 @@ int sc_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
        LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
 }
 
-int sc_read_record(sc_card_t *card, unsigned int rec_nr, u8 *buf,
-                  size_t count, unsigned long flags)
+int sc_read_record(sc_card_t *card, unsigned int rec_nr, unsigned int idx,
+                  u8 *buf ,size_t count, unsigned long flags)
 {
+       size_t max_le = sc_get_max_recv_size(card);
+       size_t todo = count;
        int r;
 
-       if (card == NULL) {
+       if (card == NULL || card->ops == NULL || buf == NULL) {
                return SC_ERROR_INVALID_ARGUMENTS;
        }
        LOG_FUNC_CALLED(card->ctx);
+       if (count == 0)
+               LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
 
        if (card->ops->read_record == NULL)
                LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
 
-       r = card->ops->read_record(card, rec_nr, buf, count, flags);
-       if (r == SC_SUCCESS) {
-               r = count;
+       /* lock the card now to avoid deselection of the file */
+       r = sc_lock(card);
+       LOG_TEST_RET(card->ctx, r, "sc_lock() failed");
+
+       while (todo > 0) {
+               size_t chunk = MIN(todo, max_le);
+
+               r = card->ops->read_record(card, rec_nr, idx, buf, chunk, flags);
+               if (r == 0 || r == SC_ERROR_FILE_END_REACHED)
+                       break;
+               if (r < 0 && todo != count) {
+                       /* the last command failed, but previous ones succeeded.
+                        * Let's just return what we've successfully read. */
+                       sc_log(card->ctx, "Subsequent read failed with %d, returning what was read successfully.", r);
+                       break;
+               }
+               if (r < 0) {
+                       sc_unlock(card);
+                       LOG_FUNC_RETURN(card->ctx, r);
+               }
+               if ((idx > SIZE_MAX - (size_t) r) || (size_t) r > todo) {
+                       /* `idx + r` or `todo - r` would overflow */
+                       sc_unlock(card);
+                       LOG_FUNC_RETURN(card->ctx, SC_ERROR_OFFSET_TOO_LARGE);
+               }
+
+               todo -= (size_t) r;
+               buf  += (size_t) r;
+               idx  += (size_t) r;
        }
 
-       LOG_FUNC_RETURN(card->ctx, r);
+       sc_unlock(card);
+
+       LOG_FUNC_RETURN(card->ctx, count - todo);
 }
 
 int sc_write_record(sc_card_t *card, unsigned int rec_nr, const u8 * buf,

Sorry that I cannot provide something better right now.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

@dengert is right to say that:

It could be a config option or some change in OpenSC that is being more conservative in 0.23.0 on setting the sizes.

But 0.23.0 is still working on Win64. 0.24.0 not. So here also has something changed.

from opensc.

istr avatar istr commented on July 18, 2024

But 0.23.0 is still working on Win64. 0.24.0 not. So here also has something changed.

Hm... 😞

In that case you might need to give git bisect a chance to hunt down the breaking change(s).

@clauspruefer It seems that you already have the necessary build infrastructure in place. Given the large number of changes between 0.22/0.23/0.24, I fear that using git bisect is the best way to get a handle on this.

from opensc.

dengert avatar dengert commented on July 18, 2024

The other lines that do not look correct are:

P:597; T:0x42949672976 21:12:00.964 [opensc-pkcs11] reader-pcsc.c:1148:detect_reader_features: Requesting reader features ... 
P:597; T:0x42949672976 21:12:00.967 [opensc-pkcs11] reader-pcsc.c:1155:detect_reader_features: Alcor Micro USB Smart Card Reader 0:SCardControl failed: 0x00000001

from https://github.com/OpenSC/OpenSC/blob/master/src/libopensc/reader-pcsc.c#L1148-L1156

0x00000001 does not look like a valid return code as stated in:
https://learn.microsoft.com/en-us/windows/win32/api/winscard/nf-winscard-scardcontrol
https://learn.microsoft.com/en-us/windows/win32/secauthn/authentication-return-values

This would point to Cygwin not handling the request for part_10 features correctly. This combined with some OpenSC change is causing the OpenSC to support extended APDUs for this reader.

The code never gets to: https://github.com/OpenSC/OpenSC/blob/master/src/libopensc/reader-pcsc.c#L1281-L1291
where two readers are handled.

Using git bisect sounds like a good idea.

Something else to try is modify the opensc.conf file to set reader max values as in example:
https://github.com/OpenSC/OpenSC/blob/master/etc/opensc.conf.example.in#L62-L111
This is more of a circumvention for this reader.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

@dengert @istr I also will add the log output in Cygwin/22.0 like tomorrow or in two days. Think this is very important to encircle the problem. Also i will try the bisect (never done before, sounds interesting) and have a bit more insight in the pkcs11 / pkcs15 transfer protocol, good night 🌃

from opensc.

dengert avatar dengert commented on July 18, 2024

I am able to reproduce the problem with Cygwin on W11 with my older 'SCM Microsystems SCx35xx v2.0 USB SC Reader 0' sc-hsm device and git clone from yesterday

Running under gdb with breakpoint at detect_reader_features
which show default is 255/256.
Then changed the reader structure to so larger 2550 and 25560
and continuing to run it lists out all the objects.

So problem is related to not setting large enough reader max values.

doug@DOUG22 /usr/local/bin
$ gdb --args ./pkcs11-tool -O
GNU gdb (GDB) (Cygwin 8.3.1-1) 8.3.1
Copyright (C) 2019 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-pc-cygwin".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.

For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./pkcs11-tool...
(gdb) b detect_reader_features
Function "detect_reader_features" not defined.
Make breakpoint pending on future shared library load? (y or [n]) y
Breakpoint 1 (detect_reader_features) pending.
(gdb) run
Starting program: /usr/local/bin/pkcs11-tool -O
[New Thread 24044.0xd6c]
[New Thread 24044.0xc48]
[New Thread 24044.0x4814]
[New Thread 24044.0x5044]

Thread 1 "pkcs11-tool" hit Breakpoint 1, detect_reader_features (
    reader=reader@entry=0xa00001d20, card_handle=16861477009170104320)
    at /usr/src/opensc.b/src/libopensc/reader-pcsc.c:1136
1136    /usr/src/opensc.b/src/libopensc/reader-pcsc.c: No such file or directory.
(gdb) where
#0  detect_reader_features (reader=reader@entry=0xa00001d20,
    card_handle=16861477009170104320)
    at /usr/src/opensc.b/src/libopensc/reader-pcsc.c:1136
#1  0x00000005f8502cbd in pcsc_detect_readers (ctx=0xa00001a40)
    at /usr/src/opensc.b/src/libopensc/reader-pcsc.c:1571
#2  0x00000005f84c36d3 in sc_ctx_detect_readers (ctx=ctx@entry=0xa00001a40)
    at /usr/src/opensc.b/src/libopensc/ctx.c:767
#3  0x00000005f84c40ab in sc_context_create (
    ctx_out=ctx_out@entry=0x5f43d8140 <context>, parm=parm@entry=0x7ffffc7e0)
    at /usr/src/opensc.b/src/libopensc/ctx.c:1008
#4  0x00000005f43a2ae5 in C_Initialize (pInitArgs=<optimized out>)
    at /usr/src/opensc.b/src/pkcs11/pkcs11-global.c:349
#5  0x00000001004142e9 in main (argc=<optimized out>, argv=0xa00001850)
    at /usr/src/opensc.b/src/tools/pkcs11-tool.c:1185
(gdb) p *reader
$1 = {ctx = 0xa00001a40, driver = 0x5f8637ca0 <pcsc_drv>,
  ops = 0x5f86a4d00 <pcsc_ops>, drv_data = 0xa00001e00,
  name = 0xa00001e80 "SCM Microsystems SCx35xx v2.0 USB SC Reader 0",
  vendor = 0x0, version_major = 0 '\000', version_minor = 0 '\000', flags = 3,
  capabilities = 0, supported_protocols = 0, active_protocol = 2,
  max_send_size = 255, max_recv_size = 256, atr = {
    value = ";\376\030\000\000\201\061\376E\200\061\201THSM1s\200!@\201\a\372\000\000\000\000\000\000\000\000", len = 24}, uid = {
    value = "\000\000\000\000\000\000\000\000\000", len = 0}, atr_info = {
    hist_bytes = 0x0, hist_bytes_len = 0, Fi = 0, f = 0, Di = 0, N = 0,
    FI = 0 '\000', DI = 0 '\000'}}
(gdb) set reader->max_send_size = 2550
(gdb) set reader->max_recv_size = 25560
(gdb) p *reader
$2 = {ctx = 0xa00001a40, driver = 0x5f8637ca0 <pcsc_drv>,
  ops = 0x5f86a4d00 <pcsc_ops>, drv_data = 0xa00001e00,
  name = 0xa00001e80 "SCM Microsystems SCx35xx v2.0 USB SC Reader 0",
  vendor = 0x0, version_major = 0 '\000', version_minor = 0 '\000', flags = 3,
  capabilities = 0, supported_protocols = 0, active_protocol = 2,
  max_send_size = 2550, max_recv_size = 25560, atr = {
    value = ";\376\030\000\000\201\061\376E\200\061\201THSM1s\200!@\201\a\372\000\000\000\000\000\000\000\000", len = 24}, uid = {
    value = "\000\000\000\000\000\000\000\000\000", len = 0}, atr_info = {
    hist_bytes = 0x0, hist_bytes_len = 0, Fi = 0, f = 0, Di = 0, N = 0,
    FI = 0 '\000', DI = 0 '\000'}}
(gdb) c
Continuing.
[New Thread 24044.0x25d4]
[New Thread 24044.0x5e40]
Using slot 0 with a present token (0x0)
Certificate Object; type = X.509 cert
  label:      Certificate
  subject:    DN: C=US, ST=IL, CN=Doug Engert/[email protected]
  serial:     73BECD28CD5657F812F68CEBB87406D75E62A8CE
  ID:         11
Public Key Object; RSA 2048 bits
... (and the rest of objects)

Modifying opensc.conf did not fix problem. may need to look at this closer.)

I too have had it for the night.

from opensc.

dengert avatar dengert commented on July 18, 2024

It looks like the problem is Windows (or at least W11) does not support PCSC part 10 (or parts of it).

If I replace https://github.com/OpenSC/OpenSC/blob/master/src/libopensc/reader-pcsc.c#L1156 with rcount = 0;
(rcount should have been set when defined) I can get past the return; and get these log messages:

P:3600; T:0x42949672976 20:26:26.797 [opensc-pkcs11] ../../../opensc/src/libopensc/reader-pcsc.c:1567:pcsc_detect_readers: SCM Microsystems SCx35xx v2.0 USB SC Reader 0:SCardConnect(SHARED): 0x00000000
P:3600; T:0x42949672976 20:26:26.797 [opensc-pkcs11] ../../../opensc/src/libopensc/reader-pcsc.c:1146:detect_reader_features: called
P:3600; T:0x42949672976 20:26:26.797 [opensc-pkcs11] ../../../opensc/src/libopensc/reader-pcsc.c:1148:detect_reader_features: Requesting reader features ...
P:3600; T:0x42949672976 20:26:26.799 [opensc-pkcs11] ../../../opensc/src/libopensc/reader-pcsc.c:1303:detect_reader_features: Assuming that the reader supports sending short length APDUs only
P:3600; T:0x42949672976 20:26:26.799 [opensc-pkcs11] ../../../opensc/src/libopensc/reader-pcsc.c:1316:detect_reader_features: Assuming that the reader supports receiving short length APDUs only

Which are bad assumptions.

aadd82b tries to fix up two readers, but reader being used in the issue is not one of them. And two readers would not be fixe if running CygWin. The readers should be in the opensc.conf file, along with any other readers with problems.

This also brings up the question, is this problem also in the Apvoyer release too?

And it is also looks not clear why https://github.com/OpenSC/OpenSC/blob/master/src/libopensc/reader-pcsc.c#L1370-L1376
does not find the max_send_size and max_recv_size in the opensc.conf.

Anyone else want to work on this problem? @istr

I really don't like CygWin.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

I am able to reproduce the problem with Cygwin on W11 with my older 'SCM Microsystems SCx35xx v2.0 USB SC Reader 0' sc-hsm device and git clone from yesterday

Running under gdb with breakpoint at detect_reader_features which show default is 255/256. Then changed the reader structure to so larger 2550 and 25560 and continuing to run it lists out all the objects.

So problem is related to not setting large enough reader max values.

Ah, as i expected, im sure Cygwin/22.0 will print the correct values.

@dengert But why does it work on Win11 native with 23.0 and NOT with 24.0? Also i will investigate when i have the time.

from opensc.

dengert avatar dengert commented on July 18, 2024

This "/usr/local/etc/opensc.conf work for me:

app default {
        debug = 21;
        debug_file = /tmp/opensc-debug.txt;

        reader_driver pcsc {
                max_send_size = 65535;
                max_recv_size = 65536;
        }
}

Yesterday I said opensc.conf did not work, but I did not have spaces around "=".

Today, with only mods to opensc.conf it works. This is using OpenSC 0.24.0 from git clone.

But I do not get the failure 0x00000001 that you do at https://github.com/OpenSC/OpenSC/blob/master/src/libopensc/reader-pcsc.c#L1153-L1156

Try the above opensc.conf with this mod which ignores the error:

diff --git a/src/libopensc/reader-pcsc.c b/src/libopensc/reader-pcsc.c
index d2dac438..9e9208b9 100644
--- a/src/libopensc/reader-pcsc.c
+++ b/src/libopensc/reader-pcsc.c
@@ -1137,7 +1137,7 @@ static void detect_reader_features(sc_reader_t *reader, SCARDHANDLE card_handle)
        sc_context_t *ctx = reader->ctx;
        struct pcsc_global_private_data *gpriv = (struct pcsc_global_private_data *) ctx->reader_drv_data;
        struct pcsc_private_data *priv = reader->drv_data;
-       DWORD rcount, i;
+       DWORD rcount = 0, i;
        u8 buf[256];
        LONG rv;
        const char *log_disabled = "but it's disabled in configuration file";
@@ -1153,7 +1153,6 @@ static void detect_reader_features(sc_reader_t *reader, SCARDHANDLE card_handle)
        rv = gpriv->SCardControl(card_handle, CM_IOCTL_GET_FEATURE_REQUEST, NULL, 0, buf, sizeof(buf), &rcount);
        if (rv != SCARD_S_SUCCESS) {
                PCSC_TRACE(reader, "SCardControl failed", rv);
-               return;
        }

        if ((rcount % sizeof(PCSC_TLV_STRUCTURE)) != 0

Why the difference in failure 0x0000001 and mine not failing?

  • Different CygWin packages. (I set it up two days ago.) When was your updated?

  • I am testing with older SC-HSM device

  • Difference in Windows. I have:

Device name	DOUG22
Processor	12th Gen Intel(R) Core(TM) i5-12600K   3.69 GHz
Installed RAM	32.0 GB (31.7 GB usable)
Device ID	A087B189-ECEE-4B65-8347-DB565AAB1C64
Product ID	00330-71290-00002-AAOEM
System type	64-bit operating system, x64-based processor
Pen and touch	No pen or touch input is available for this display
Edition	Windows 11 Pro
Version	22H2
Installed on	‎10/‎8/‎2022
OS build	22621.2861
Experience	Windows Feature Experience Pack 1000.22681.1000.0

Why native works and CygWin fails? Don't know, other then CygWin maybe internals maybe a problem. But it looks like OpenSC is calling the Windows pcsc DLL directly.

from opensc.

frankmorgner avatar frankmorgner commented on July 18, 2024

We could use the libccid data on the readers dwMaxCCIDMessageLength to add more special cases:

https://ccid.apdu.fr/ccid/section.html

not sure how to tackle this in a more generic way. maybe pyscard can be used for more debugging on the Windows side. Maybe also @LudovicRousseau has insights about how to get property data on Windows (or its limitations)

from opensc.

frankmorgner avatar frankmorgner commented on July 18, 2024

Am I right in assuming that the use case of the OP involves writing to the card? Meaning: Extended length support is required for the transaction in question.

In cardos, we simply assume that extended length is supported in this case:

#ifdef _WIN32
/* Windows does not support PCSC PART_10 and may have forced reader to 255/256
* https://github.com/OpenSC/OpenSC/commit/eddea6f3c2d3dafc2c09eba6695c745a61b5186f
* may have reset this. if so, will override and force extended
* Most, if not all, cardos cards do extended, but not chaining
*/
if (card->reader->max_send_size == 255 && card->reader->max_recv_size == 256) {
sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "resetting reader to use data_field_length");
card->reader->max_send_size = data_field_length - 6;
card->reader->max_recv_size = data_field_length - 3;
}

Maybe this would also be an option for sc-hsm

from opensc.

dengert avatar dengert commented on July 18, 2024

@clauspruefer I have been looking CygWin and dont have an answer to why
rv = gpriv->SCardControl(card_handle, CM_IOCTL_GET_FEATURE_REQUEST, NULL, 0, buf, sizeof(buf), &rcount); is failing.

I am waiting for you to try git bisect.

from opensc.

LudovicRousseau avatar LudovicRousseau commented on July 18, 2024

You can try to use get_PCSC_Part10_features.py

With my Gemalto PC Twin Reader reader I get:

± ./get_PCSC_Part10_features.py 
Reader: Gemalto PC Twin Reader
CM_IOCTL_GET_FEATURE_REQUEST results:
 FEATURE_GET_TLV_PROPERTIES: 0x42330012
  Supports Secure PIN Entry (SPE): no
FEATURE_GET_TLV_PROPERTIES results:
[1, 2, 0, 0, 3, 1, 0, 8, 18, 71, 101, 109, 84, 119, 105, 110, 45, 86, 50, 46, 48, 48, 45, 71, 70, 48, 51, 9, 1, 0, 11, 2, 230, 8, 12, 2, 55, 52, 10, 4, 0, 0, 1, 0]
[3, 1, 0, 8, 18, 71, 101, 109, 84, 119, 105, 110, 45, 86, 50, 46, 48, 48, 45, 71, 70, 48, 51, 9, 1, 0, 11, 2, 230, 8, 12, 2, 55, 52, 10, 4, 0, 0, 1, 0]
[8, 18, 71, 101, 109, 84, 119, 105, 110, 45, 86, 50, 46, 48, 48, 45, 71, 70, 48, 51, 9, 1, 0, 11, 2, 230, 8, 12, 2, 55, 52, 10, 4, 0, 0, 1, 0]
[9, 1, 0, 11, 2, 230, 8, 12, 2, 55, 52, 10, 4, 0, 0, 1, 0]
[11, 2, 230, 8, 12, 2, 55, 52, 10, 4, 0, 0, 1, 0]
[12, 2, 55, 52, 10, 4, 0, 0, 1, 0]
[10, 4, 0, 0, 1, 0]
 raw: [1, 2, 0, 0, 3, 1, 0, 8, 18, 71, 101, 109, 84, 119, 105, 110, 45, 86, 50, 46, 48, 48, 45, 71, 70, 48, 51, 9, 1, 0, 11, 2, 230, 8, 12, 2, 55, 52, 10, 4, 0, 0, 1, 0]
 PCSCv2_PART10_PROPERTY_wLcdLayout: 0 or 0x0000
 PCSCv2_PART10_PROPERTY_bTimeOut2: 0 or 0x0000
 PCSCv2_PART10_PROPERTY_sFirmwareID: GemTwin-V2.00-GF03
 PCSCv2_PART10_PROPERTY_bPPDUSupport: 0 or 0x0000
 PCSCv2_PART10_PROPERTY_wIdVendor: 2278 or 0x08E6
 PCSCv2_PART10_PROPERTY_wIdProduct: 13367 or 0x3437
 PCSCv2_PART10_PROPERTY_dwMaxAPDUDataSize: 65536 or 0x10000

The important line here is: PCSCv2_PART10_PROPERTY_dwMaxAPDUDataSize: 65536 or 0x10000

I guess that the Windows CCID driver does NOT support FEATURE_GET_TLV_PROPERTIES. But I have not tested.
Maybe non-Microsoft drivers may support FEATURE_GET_TLV_PROPERTIES.

from opensc.

dengert avatar dengert commented on July 18, 2024

@LudovicRousseau See below you may be correct.

The Windows SDK winsmcrd.h has:

#define SCARD_CTL_CODE(code)        CTL_CODE(FILE_DEVICE_SMARTCARD, \
                                            (code), \
                                            METHOD_BUFFERED, \
                                            FILE_ANY_ACCESS)
...
METHOD_BUFFERED = 0, FILE_ANY_ACCESS = 0

#define IOCTL_SMARTCARD_GET_FEATURE_REQUEST SCARD_CTL_CODE(3400)

and "Interoperability Specification for ICCs and Personal Computer Systems
Part 10 IFDs with Secure PIN Entry Capabilities" from 2012 Says:

Implementation Note for Windows:
Device_Success is implemented as SCARD_S_SUCCESS
Under Windows the control code must be defined as follows:
#define CM_IOCTL_GET_FEATURE_REQUEST SCARD_CTL_CODE(3400)

The above implies the Windows pcsc should work.

VirtualBox linux guests can read the FEATURE_GET_TLV_PROPERTIES.

But the "Microsoft Usbccid Smartcard Reader (WUDF)" is dated 6/21/2006. Maybe they never did implemented it.

https://answers.microsoft.com/en-us/windows/forum/all/download-windows-11-pro-microsoft-usbccid/0098e568-a196-4cff-9b31-dd13465b1777?page=1 with 173 "I have the same problem" and 13,089 views implies they never updated the driver, despite what the header files say and Microsoft are co-authors of the part10 document!

OpenSC may have worked without the FEATURE_GET_TLV_PROPERTIES because other OpenSC code was able get past the 255/256 limits. but some recent changes have forced the opensc to use 255/256

Waiting for @istr to try the git biscet to find out which commit fails.

from opensc.

istr avatar istr commented on July 18, 2024

@dengert Just to clarify

Waiting for @istr to try the git biscet to find out which commit fails.

I will not dig into that myself, because I do not have (easy) access to a Win / Cygwin build env right now.
My proposal was a hint for @clauspruefer what he could try to hunt down the breaking change.

from opensc.

dengert avatar dengert commented on July 18, 2024

Sorry, @clauspruefer said he would try the git bisect.

Look at comments in #2964 It looks like Windows PCSC and CCID driver do not support this call:
https://github.com/OpenSC/OpenSC/blob/master/src/libopensc/reader-pcsc.c#L1153 maybe returning rv = 0 or rv = 1 and since rcount is not initialized, it may not change and have other problems. So none of:
https://github.com/OpenSC/OpenSC/blob/master/src/libopensc/reader-pcsc.c#L1165-L1185
are ever set and the dwMaxAPDUDataSize is never read.

CygWin calls the Windows winscard.dll, and the problem is not just CygWin but the build by "continuous-integration/appveyor/pr" hasthe same problem.

Also looks like another mod set the default max_send_size=255 and max_recv=256 first. So even the check for "REINER SCT cyberJack" and "Secure Flash Card" may not be done either. We don't know what the max sizes on Windows is for any reader.

from opensc.

LudovicRousseau avatar LudovicRousseau commented on July 18, 2024

To use get_PCSC_Part10_features.py on Windows you need to replace SCARD_SHARE_DIRECT by SCARD_SHARE_SHARED and insert a card in the reader.

With the default/Windows CCID driver I get nothing.

With the Gemalto driver and the same Gemalto PC Twin Reader I get:

>python get_PCSC_Part10_features.py
Reader: Gemplus USB Smart Card Reader 0
CM_IOCTL_GET_FEATURE_REQUEST results:
 FEATURE_GET_TLV_PROPERTIES: 0x312140
 FEATURE_CCID_ESC_COMMAND: 0x312144
  Supports Secure PIN Entry (SPE): no
FEATURE_GET_TLV_PROPERTIES results:
 raw: [10, 4, 0, 0, 0, 0, 11, 2, 230, 8, 12, 2, 55, 52, 8, 18, 71, 101, 109, 84, 119, 105, 110, 45, 86, 50, 46, 48, 48, 45, 71, 70, 48, 51, 9, 1, 0]
 PCSCv2_PART10_PROPERTY_dwMaxAPDUDataSize: 0 or 0x0000
 PCSCv2_PART10_PROPERTY_wIdVendor: 2278 or 0x08E6
 PCSCv2_PART10_PROPERTY_wIdProduct: 13367 or 0x3437
 PCSCv2_PART10_PROPERTY_sFirmwareID: GemTwin-V2.00-GF03
 PCSCv2_PART10_PROPERTY_bPPDUSupport: 0 or 0x0000

Here we have PCSCv2_PART10_PROPERTY_dwMaxAPDUDataSize: 0 or 0x0000 which indicates "0: short APDU only." http://pcscworkgroup.com/Download/Specifications/pcsc10_v2.02.09.pdf

from opensc.

dengert avatar dengert commented on July 18, 2024

Started bisect on CyGwin (then went shopping) using these commands:

$ git bisect start HEAD 5497519ea6b4af596628f8f8f2f904bacaa3148f --  # tag 0.23.0 
$ git bisect run /tmp/test.sh
#!/bin/sh
cd /usr/src/opensc
git clean -xf
./bootstrap || exit 125
./configure  || exit 125
make -j 3 || exit 125
make install || exit 125
# the test program
OPENSC_DRIVER=sc-hsm /usr/local/bin/pkcs11-tool -O

and as expected got this hit:

aadd82bb071e574fc57263a103e3bf06ebbd8de7 is the first bad commit
commit aadd82bb071e574fc57263a103e3bf06ebbd8de7
Author: Ingo Struck (git commits) <[email protected]>
Date:   Sat Jan 21 22:15:10 2023 +0100

    Handle reader limits for SC Card unwrap operations

    Fixes #2514

 src/libopensc/card-sc-hsm.c            | 181 ++++++++++++++++++---------------
 src/libopensc/reader-pcsc.c            |  91 ++++++++++-------
 src/tests/fuzzing/fuzz_pkcs15_decode.c |   3 +-
 src/tests/fuzzing/fuzz_pkcs15_encode.c |   2 +-
 4 files changed, 159 insertions(+), 118 deletions(-)
bisect found first bad commit

@LudovicRousseau points out the Gemalto driver driver works, but not with the Microsoft CCID driver from 2006 which is being used in my case:

rv = gpriv->SCardControl(card_handle, CM_IOCTL_GET_FEATURE_REQUEST, NULL, 0, buf, sizeof(buf), &rcount);
returns rv = 0; rcount=0;
and reader already has defaults set for max_send_size = 255, max_recv_size = 256

 {ctx = 0xa00001b60, driver = 0x5f8631c80 <pcsc_drv>,
  ops = 0x5f869cd00 <pcsc_ops>, drv_data = 0xa00001f00,
  name = 0xa00001f80 "SCM Microsystems SCx35xx v2.0 USB SC Reader 0",
  vendor = 0x0, version_major = 0 '\000', version_minor = 0 '\000', flags = 3,
  capabilities = 0, supported_protocols = 0, active_protocol = 2,
  max_send_size = 255, max_recv_size = 256, atr = {
    value = ";\376\030\000\000\201\061\376E\200\061\201THSM1s\200!@\201\a\372\000\000\000\000\000\000\000\000", len = 24}, uid = {
    value = "\000\000\000\000\000\000\000\000\000", len = 0}, atr_info = {
    hist_bytes = 0x0, hist_bytes_len = 0, Fi = 0, f = 0, Di = 0, N = 0,
    FI = 0 '\000', DI = 0 '\000'}}

So none of the features are returned, and this like is never run:
int max_data = part10_detect_max_data(reader, card_handle);
and the defaults are left at 255/256.

Proposed solution

We have no control over the reader, its version, the windows version or device driver and the type of card. Also do not have control over these on any OS.
Add a flags to reader indicating where the sizes came from.
part10_detect_max_data set the reader sizes sizes set from default or from opensc.conf.

i.e. consider the max sizes as a best guess.

It would then allow a card driver or change the sizes if it knew they were too small, for example
if the driver requires extended APDU, because the card does not support chaining and/or get response.

If the driver does support chaining and/or get response but the driver (or apdu.c routines) could try extended and if it works, set new max sizes and fall back to 255/256 as last resort.

Also aadd82b is forcing the max size to be smaller because of a limit on read/write binary, but this then applies to all operations. Other card drivers handle this by temporarily changing the sizes when doing operations that requiring a smaller size.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

Sorry, @clauspruefer said he would try the git bisect.

Sorry guys, had to take a break. Project should have been closed on last sunday... But still ongoing... No sleep @ weekend.

from opensc.

dengert avatar dengert commented on July 18, 2024

Sorry guys, had to take a break.

No problem, it turned out running the git bisect with a script was easier then I thought it would be. The bisect took about 8 builds to find the commit but did it unattended.

Project should have been closed on last sunday...
Not sure what you mean. What you have found is a problem not just CygWin with a specific card, but a problem in native windows build and maybe other cards too.

Its the holidays and I too will have little time to work on this but there is a circumvention as listed above. Also see #2964.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

Sorry guys, had to take a break.

No problem, it turned out running the git bisect with a script was easier then I thought it would be. The bisect took about 8 builds to find the commit but did it unattended.

Project should have been closed on last sunday...
Not sure what you mean. What you have found is a problem not just CygWin with a specific card, but a problem in native windows build and maybe other cards too.

I mean my own project im currently working on 😄

Its the holidays and I too will have little time to work on this but there is a circumvention as listed above. Also see #2964.

Saw it already will try ASAP 🏃

Tip

Just a small proposal of handling all upcoming issues with the misbehaving readers.

Why not adding / setting the readers making problems to an exlusion list (config / structs / matrix), just setting the 65k manually for just those readers. No source code change for dependend problems (including testing) necessary. Furthermore if people reporting problems with a special reader: just add this reader to the config.

from opensc.

dengert avatar dengert commented on July 18, 2024

Just a small proposal of handling all upcoming issues with the misbehaving readers.

The problem is not necessarily the reader. The main problem apprears to be the windows CCID device driver from 2006 does needs updating. When the same reader is used on non windows machine it works fine. It works fine from a virtual guest machine with Windows host. (VirtualBox may be talking to the USB device and bypassing the windows CCID reader driver.)

The Part 10 IFDs with Secure PIN Entry Capabilities added support for dwMaxAPDUDataSize in November 2012. Unfortunately, many of my readers predate the initial release of Part_10.

Using Windows Device Manager, with your reader and card inserted can you look at "smart card reader", and look properties for the driver being used and its date. Form the initial post, the name is: "Alcor Micro USB Smart Card Reader"

The problem for the sc-hsm may be the commit in question sets the sizes less then the default for all operations for the card instead of only when doing specific ADPUs.

The circumvention was provide relief for users with this problem while continuing to use existing software. OpenSC only does releases about once a year. Most users only have one card. A more robust solution needs to be developed to work with future OS, readers and cards hopefully without having to list individual readers. One problem is across OSes and Virtual software vendors where the reader name seen in the guest in not the same as seen from the host.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

image

image

from opensc.

LudovicRousseau avatar LudovicRousseau commented on July 18, 2024

@dengert most of PCSC v2 part 10 is done by the driver, not the reader. It could work even with very old readers.

For example dwMaxAPDUDataSize is implemented here in my CCID driver.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

@dengert most of PCSC v2 part 10 is done by the driver, not the reader. It could work even with very old readers.

For example dwMaxAPDUDataSize is implemented here in my CCID driver.

And why does it work with the same Win CCID driver on 23.0 and not on 24.0?

from opensc.

dengert avatar dengert commented on July 18, 2024

For example dwMaxAPDUDataSize is implemented here in my CCID driver.

The problem is only on Windows. So your driver or pcsc-lite is not used. So the Windows problems may be in their PC/SC or some CCID driver.

And why does it work with the same Win CCID driver on 23.0 and not on 24.0?

On Windows rv = gpriv->SCardControl(card_handle, CM_IOCTL_GET_FEATURE_REQUEST, NULL, 0, buf, sizeof(buf), &rcount);
when I run it, returns rv = 0 and rcount = 0, so no feature are returned and some of the code following is executed which changes max sizes to 238/254.

The git bisect shows aadd82bb causes the problem.
It changes the max sizes in in reader-pcsc.c for sc-hsm to the 238/254 which means if short APDUs are used, the card may complain as seen in some debug logs that P1-P2 are in error, but I think it because the card wants to return more then 256 bytes of data using get-response, but the the host says it only wants 254. Le is usually 00 which says return 256 bytes or less and the host will then request more data using get response. If host only asks for 254, the card assumes host will not use get response. and returns an error. (I can not prove this at this time.)

See: #2944 (comment) in one of the logs is:
reader-pcsc.c:1155:detect_reader_features: Alcor Micro USB Smart Card Reader 0:SCardControl failed: 0x00000001
This then take a different path. and returns immediately. aadd82bb also has mods to sc-hsm that changed max sizes to less then 255/256 which can cause the same problem.

I can not do any real testing of this until after the holidays.

@clauspruefer if you wanted to use git to revert aadd82b and run you tests that would help show the problem is in aadd82b. But aadd82b also fixes issues symmetric key encryption, which needs to be addressed by temporarily setting the max sizes but only for some operations but not for all operations.

from opensc.

dengert avatar dengert commented on July 18, 2024

Found some time. Works with CygWin with this patch: sc-hsm-cygwin.diff.txt
when running: pkcs11-tool --test --login

card-sc-hsm.c now set the max_send_size to at least 256, so the card can return data, When it was 254, the card would return errors, as suggested in #2944 (comment)

The change to reader-pcsc.c was to make sure some of the tests where still run even if 0x0000001 was returned.
The card driver will still use extended APDUs in some cases. for example sign. as the reader still supports them and can handle 64K packets.

I would like @istr and @clauspruefer to give this a try.

I still don't understand all of what aadd82b is trying to do.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

I will give a try and report back.

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

Correct Version 0.24

$ pkcs11-tool -I
Cryptoki version 3.0
Manufacturer     OpenSC Project
Library          OpenSC smartcard framework (ver 0.24)
Using slot 0 with a present token (0x0)

Object List ok

  • one x.509 cert (for use with MIcrosoft CrytoAPI
  • one public SSH key (private hidden, no login given)
$ pkcs11-tool -O
Using slot 0 with a present token (0x0)
Certificate Object; type = X.509 cert
  label:      CP-RSA4096-sshKey
  subject:    DN: C=DE, ST=BW, L=Mannheim, O=clickIT, OU=Security, CN=c.pruefer.ssh/[email protected]
  serial:     8B65287CC95FDC3E
  ID:         01
Public Key Object; RSA 4096 bits
  label:      CP-RSA4096-sshKey
  ID:         01
  Usage:      encrypt, verify, verifyRecover
  Access:     local
Profile object 340144
  profile_id:          CKP_PUBLIC_CERTIFICATES_TOKEN (4)

@dengert Close issue or wait for istr reply?

from opensc.

dengert avatar dengert commented on July 18, 2024

The patch just proves one problem is making the max_recv_size to small and many commands would fail because the card would treat the 254 as an error. The card sill assumes it can use extended APDU and it does and the reader supports it. The problem on Windows is it can return dwMaxAPDUDataSize and the code then tries to force the 255/256 limits and further limited max_recv_size to 254 in sm-hsm.c

In other words, on windows OpenSC can not detect the reader sizes and should not set artificial limits. In the sc-hsm case the card drive to the most part assumes the reader will support extended APDU large enough for its needs. Other card drivers may fail back to using the 255/256 and use command chaining and get response to handle larger outgoing commands and incoming data.

Wait for @istr as there are still unanswered questions as to how to fix the symmetric key issue with read/write binary operations with odd number APDU instructions.

@clauspruefer
If you run with an opensc debug log and use pkcs11-tool --test --login, can you look for a simple sign operation.
With a 2048 bit RSA key which I have on my older token the easiest one would look like this:

Outgoing APDU (265 bytes):
80 68 02 20 00 01 00 00 01 FF FF FF FF FF FF FF .h. ............
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
...
4A 74 73 A1 C0 0B C1 02 00 

where 80 68 02 20 is the APDU, Lc 00 means extended APDU with length 01 00 for 256 bytes and the last two bytes are the extended Le 02 00 the max size to return.

With your 4096 bit key, the outgoing would be 521 bytes with Lc length of 02 00 and Le would still be 02 00 as it looks like the code just has a fixed size buffer and the card will return the actual size.

The response would look like:

Incoming APDU (258 bytes):
53 B5 AD 07 8B 71 8C F8 D1 A4 D6 57 6C 29 45 34 S....q.....Wl)E4
7B 1D 87 A5 82 67 E0 AC 6B 31 F0 07 AC F0 D4 8F {....g..k1......
...
90 00

But for 514 bytes different bytes, ending in 90 00

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

If you run with an opensc debug log and use pkcs11-tool --test --login, can you look for a simple sign operation.

On the run. I think it might also be helpful to check if i can gen a new key with sc-hsm-tool on another card, so i will try this first.

Important

Just using different card with existing RSA 4096 bit key.

Card / Key info

$ pkcs11-tool -l -O
Using slot 0 with a present token (0x0)
Logging in to "SmartCard-HSM (UserPIN)".
Please enter User PIN:
Private Key Object; RSA
label: Private Key
ID: 3b27dc55868a5802ddea5c32f46251d4c826341a
Usage: decrypt, sign, signRecover
Access: sensitive, always sensitive, never extractable, local
Public Key Object; RSA 4096 bits
label: Private Key
ID: 3b27dc55868a5802ddea5c32f46251d4c826341a
Usage: encrypt, verify, wrap
Access: none
Profile object 334720
profile_id: CKP_PUBLIC_CERTIFICATES_TOKEN (4)

Get signing mechs (Hardware)

$ pkcs11-tool -M

Using slot 0 with a present token (0x0)
Supported mechanisms:
RSA-PKCS, keySize={1024,4096}, hw, decrypt, sign, verify
RSA-PKCS-PSS, keySize={1024,4096}, hw, sign, verify

Sign with default (RSA-PKCS)

$ pkcs11-tool -l -s -m RSA-PKCS -d 3b27dc55868a5802ddea5c32f46251d4c826341a -i test-long.txt -o ./test.signed

test-long.txt

Outgoing APDU

Outgoing APDU (521 bytes):
80 68 01 20 00 02 00 00 01 FF FF FF FF FF FF FF .h. ............
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF ................
FF FF FF FF FF FF FF FF 00 74 65 73 74 2D 64 61 .........test-da
74 61 20 74 6F 20 62 65 20 73 69 67 6E 65 64 20 ta to be signed
66 6F 72 20 4F 70 65 6E 53 43 20 43 79 67 77 69 for OpenSC Cygwi
6E 20 74 65 73 74 2E 2E 2E 20 23 31 32 33 34 35 n test... #12345
36 37 38 39 30 0D 0A 02 00                      67890....

Incoming APDU

Incoming APDU (514 bytes):
4B BF E4 EC 76 E3 99 AD DE 3E B9 A3 F3 73 70 35 K...v....>...sp5
7F 7C F8 F0 68 B5 A6 5F 9F 24 F3 A1 7F 0C F8 22 .|..h.._.$....."
4B 89 23 80 78 28 05 B5 FC 7B 88 ED 6A 18 8A 64 K.#.x(...{..j..d
0B 21 81 90 8D 0A 32 C2 E0 D8 75 D8 7D D5 96 6B .!....2...u.}..k
DE B2 9B 28 16 48 63 B3 FC CB A7 DD 26 FE 0D 99 ...(.Hc.....&...
00 83 15 34 3B 74 3B 38 B8 AE 17 F8 53 72 33 A6 ...4;t;8....Sr3.
EB 05 07 62 18 0D EF B6 8A 8F 81 D3 FF C1 4A 52 ...b..........JR
76 8A E3 A0 C5 B7 B3 B2 7F 6C FA E2 24 65 40 11 v........l..$e@.
0B 44 CF 1C 5F 8C BF 5B 66 BC 6F BF E4 81 F6 42 .D.._..[f.o....B
D4 22 E7 F4 EA 02 5F A2 4A B1 93 06 0A 08 0E 96 ."...._.J.......
70 F5 05 0D 9D 04 2E 11 A7 2E 8B BA C4 B3 44 3B p.............D;
A5 CB 98 47 62 A4 D5 2C F7 19 2C 56 47 87 96 D9 ...Gb..,..,VG...
B5 F7 1C 9C 9E 59 5B D3 3A CA 0E 5D 45 72 4D 2A .....Y[.:..]ErM*
70 8E 2C 31 32 34 90 6E 28 6E CB 64 39 4E 49 CE p.,124.n(n.d9NI.
92 75 F4 5C 91 48 03 EC 88 39 5F 4B E7 CC B3 CB .u.\.H...9_K....
E7 32 DC 7F 08 21 5A 94 3F B5 C2 1B 39 66 BD 3B .2...!Z.?...9f.;
8F 56 59 28 40 9D F5 7B CC E1 F3 46 A0 71 BB 50 .VY(@..{...F.q.P
18 98 80 2C 6B 22 DD 24 33 2E 87 7D F2 8F 3C ED ...,k".$3..}..<.
9D 20 AE 83 21 66 FA 2B 78 C7 E2 F1 5D 4E AC DD . ..!f.+x...]N..
62 39 D8 0A EB 2F 84 7B 68 A3 AA 36 F3 81 64 29 b9.../.{h..6..d)
71 00 64 7B 7A 39 48 5C BE 23 53 55 C4 6B A5 85 q.d{z9H\.#SU.k..
3C 49 8D 17 87 E8 67 AA 87 9F 00 D5 D3 23 E8 F4 <I....g......#..
8B 00 19 F1 80 A0 FE 34 CA 95 63 13 E5 38 A1 C4 .......4..c..8..
AF 12 6A D0 BD 17 38 29 76 22 7C 12 7E 9F 4B E9 ..j...8)v"|.~.K.
EC 21 45 17 8C 93 41 04 D5 30 08 A2 1D AC 30 4B .!E...A..0....0K
C7 69 C3 EF 0F 7F 94 45 1A 6C 6B 1F 84 72 99 FB .i.....E.lk..r..
75 EF DD E0 B7 FE 76 90 B2 72 26 DD 79 70 47 C8 u.....v..r&.ypG.
9D DC 02 8F C7 30 4E 4E EE 44 0A 5E 91 95 3C C1 .....0NN.D.^..<.
95 4F D0 6E 88 7B A6 4C EB AB A9 21 54 C4 46 B9 .O.n.{.L...!T.F.
D7 C4 C8 96 88 5B B6 23 75 40 06 62 6D FE 24 DB .....[.#[email protected].$.
3E D1 1B D3 56 52 5F 34 E3 B4 A9 C1 C1 E6 EC 6A >...VR_4.......j
AE 0A D4 D8 74 3B D5 01 E2 22 49 65 90 FE 09 72 ....t;..."Ie...r
90 00

from opensc.

dengert avatar dengert commented on July 18, 2024

@istr and @CardContact

Thanks for running the test with 4K key. So we are close.

The main problem is Windows does not support gpriv->SCardControl(card_handle, CM_IOCTL_GET_FEATURE_REQUEST, NULL, 0, buf, sizeof(buf), &rcount); and combined with aadd82b this causes CygWin commands certutil.exe /v /SCinfo to fail.

C:\Users\doug>certutil.exe /v -SCinfo
The Microsoft Smart Card Resource Manager is running.
Current reader/card status:
Readers: 1
  0: SCM Microsystems SCx35xx v2.0 USB SC Reader 0
--- Reader: SCM Microsystems SCx35xx v2.0 USB SC Reader 0
--- Status: SCARD_STATE_PRESENT | SCARD_STATE_UNPOWERED
--- Status: The card is available for use.
---   Card: SmartCard-HSM
---    ATR:
        3b fe 18 00 00 81 31 fe  45 80 31 81 54 48 53 4d   ;.....1.E.1.THSM
        31 73 80 21 40 81 07 fa                            1s.!@...


=======================================================
Analyzing card in reader: SCM Microsystems SCx35xx v2.0 USB SC Reader 0
P:21636; T:26224 2024-01-04 10:59:35.388 [cardmod] PKCS#15 init failed.
P:21636; T:26224 2024-01-04 10:59:35.640 [cardmod] PKCS#15 init failed.
P:21636; T:26224 2024-01-04 10:59:35.892 [cardmod] PKCS#15 init failed.
...

Changes in aadd82b in reader-pcsc.c cause the defaults of the card max_send_size and max_recv_size to be set to zero.

I have some questions about aadd82b and existing card-sc-hsm.c code:

  • OpenSC has routines sc_get_max_send_size(card) and sc_get_max_recv_size(card) why are these not used? They test if card driver has set SC_CARD_CAP_APDU_EXT.
  • Why the card->max_recv_size = card->reader->max_recv_size - 2; ? Three card drivers do this and one says for SW1 and SW2. But that is not the case, the send and receive sizes are size of data sent and received. reader-pcsc.c takes care of this.
  • // 17 byte header and TLV because of odd ins in UPDATE BINARY and card->max_send_size = card->reader->max_send_size - 17; Why the - 17? sc_hsm_write_ef takes care of the TLV header bytes. And I assume the extra 10 bytes is for SM?
  • In any case the card->max_recv_size should not be less then 256 as the card appears to have problems if it is less the 256.

@clauspruefer Thanks for running the test with 4K key. So we are close.

from opensc.

dengert avatar dengert commented on July 18, 2024

Looks reasonable. I don't have the manual. Does the SC-HSM manual talk about Le = 00 with short APDUs and use of get-response? In which case OpenSC apdu.c would do the get response. Or does SC-HSM require the use of an extended reader?
The reader in question does support extended APDUs, as the circumvention of setting 65535/65535 works.

The main problem is OpenSC has no way on Windows to query the reader for is max sizes and the card-sc-hsm.c sets max sizes less then 255/256

from opensc.

frankmorgner avatar frankmorgner commented on July 18, 2024

The manual does not mention GET RESPONSE and also doesn't mention command chaining for anything else than device authentication. If I remember correctly, @CardContact already confirmed that there is no support for this and that extended length APDUs are indeed required in cases with big chunks of data.

from opensc.

frankmorgner avatar frankmorgner commented on July 18, 2024

I've created a PR, so that you can pick binaries from the CI pipeline for testing #2978

from opensc.

frankmorgner avatar frankmorgner commented on July 18, 2024

32 bit binaries are available here
https://ci.appveyor.com/project/frankmorgner/opensc/builds/48931227/job/xts017729w423c66/artifacts

64 bit binaries here
https://ci.appveyor.com/project/frankmorgner/opensc/builds/48931227/job/7v9lyv4ml9p1ftdk/artifacts

from opensc.

frankmorgner avatar frankmorgner commented on July 18, 2024

@clauspruefer would you mind testing the suggested fix, please?

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

from opensc.

frankmorgner avatar frankmorgner commented on July 18, 2024

With "the last patch" you mean #2978?

from opensc.

clauspruefer avatar clauspruefer commented on July 18, 2024

The diff attached to the comment from dengert: #2944 (comment)

from opensc.

frankmorgner avatar frankmorgner commented on July 18, 2024

then please Test the above pull request or binaries
#2944 (comment)

This should be the correct fix

from opensc.

dengert avatar dengert commented on July 18, 2024

The real problem is part10_find_property_by_tag PCSCv2_PART10_PROPERTY_dwMaxAPDUDataSize is not from the reader hardware but from PCSC, CCID and/or IFD software. Microsoft has not implemented it. It is only in PCSClite.
The code in reader-pcsc.c does not handle the failure correctly and dies not check for a few known readers.

As @LudovicRousseau said in: #2944 (comment) PCSClite implements PCSCv2_PART10_PROPERTY_dwMaxAPDUDataSize

It is not just a Cygwin problem, it is a problem for OpenSC code run on windows both which use reader-pcsc.c which will fail on Windows. It may affect other card drivers too.
If we really wanted it to work, we would add other readers to the list in reader-pcsc.c.

See: https://github.com/OpenSC/OpenSC/files/13796437/sc-hsm-cygwin.diff.txt which handles the failure better.

from opensc.

frankmorgner avatar frankmorgner commented on July 18, 2024

Sorry, but I disagree. The real problem (tm) seems to be that SELECT is called with Le!=0, which is caused by not having PCSCv2_PART10_PROPERTY_dwMaxAPDUDataSize at hand. We should be able to cope with PCSCv2_PART10_PROPERTY_dwMaxAPDUDataSize unset or even set incorrectly on all PC/SC platforms, but SELECT should always be issued with Le=0, as required by the SC-HSM specification.

from opensc.

dengert avatar dengert commented on July 18, 2024

My point in https://github.com/OpenSC/OpenSC/files/13796437/sc-hsm-cygwin.diff.txt is that when
SCardControl(card_handle, CM_IOCTL_GET_FEATURE_REQUEST,... fails at:
https://github.com/OpenSC/OpenSC/blob/master/src/libopensc/reader-pcsc.c#L1153

the 178 lines of code:
https://github.com/OpenSC/OpenSC/blob/master/src/libopensc/reader-pcsc.c#L1158-L1337
are not executed, which includes:

  • code to test for specific readers
  • pin pad info (probably why pin pad readers don't work in Windows)
  • part10_detect_pace_capabilities(reader, card_handle);
  • max_send_size = max_recv_size = part10_detect_max_data(reader, card_handle);
  • other code to set max_send_size and max_recv_size which may end in "Assuming that the reader supports sending short length APDUs only"

This results in a card driver like card-sc-hsm.c expects the reader in the token to support extended APDUs that the reader does not.

This lack of the features from PCSClite in the Windows implementation could be addressed if OpenSC took some of the changes from PCSClite to fill in info for readers. Or at least look in opensc.conf

This problem may be the same problem as in #3004 and other card drivers may have similar problems.

(I actually found that building OpenSC from github using Cygwin was easy and could debug using gdb)

from opensc.

frankmorgner avatar frankmorgner commented on July 18, 2024

Thats indeed another Problem for which ive created a seperate issue

from opensc.

Jakuje avatar Jakuje commented on July 18, 2024

What is the status of this issue? Was it fixed with #3006 ? Is it fixed with #2978 ?

from opensc.

dengert avatar dengert commented on July 18, 2024

I don't know.

from opensc.

frankmorgner avatar frankmorgner commented on July 18, 2024

both patches are needed to reliably fix this in all situations

from opensc.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.