如何在没有智能卡的情况下向智能卡读卡器发送命令(而不是发送给智能卡)?

19

前言:

我有一个双接口智能卡读卡器,除了发送APDU命令到卡片和接收APDU响应外,它还具有一些扩展功能。

例如,在其文档中提到,您可以使用以下命令获取读卡器的固件版本:

GET_FIRMWARE_VERSION: FF 69 44 42 05 68 92 00 05 00

在其工具中,有一个用于此功能的按钮,它正常工作:

enter image description here

我甚至嗅探了USB端口,以查看我的PC和我的读卡器之间的连接在此功能中交换的内容:

命令: enter image description here

回复: enter image description here

问题:

我想使用其他工具或通过代码获取我的读卡器版本(或者发送其他扩展命令),但必须将卡插入读卡器才能发送命令,否则我会收到未检测到卡片的异常,而我不想向卡片发送命令!(读卡器工具在读卡器的插槽中没有任何卡时已成功回答GET_FIRMWARE_VERSION)

我迄今为止所做的:

1.我尝试了一些工具,包括OpenSCToolPyAPDUTool和另一个读卡器的工具。 2.我编写了以下Python脚本以发送扩展命令。

#--- Importing required modules.
import sys
import time
sys.path.append("D:\\PythonX\\Lib\\site-packages")
from smartcard.scard import *
import smartcard.util
from smartcard.System import readers


#---This is the list of commands that we want to send device
cmds =[[,0xFF,0x69,0x44,0x42,0x05,0x68,0x92,0x00,0x04,0x00],]


#--- Let's to make a connection to the card reader
r=readers()
print "Available Readers :",r
print
target_reader = input("--- Select Reader (0, 1 , ...): ")
print

while(True):
    try:
        print "Using :",r[target_reader]
        reader = r[target_reader]
        connection=reader.createConnection()
        connection.connect()
        break
    except:
        print "--- Exception occured! (Wrong reader or No card present)"
        ans = raw_input("--- Try again? (0:Exit/1:Again/2:Change Reader)")
        if int(ans)==0:
            exit()
        elif int(ans)==2:
            target_reader = input("Select Reader (0, 1 , ...): ")

#--- An struct for APDU responses consist of Data, SW1 and SW2
class stru:
    def __init__(self):
        self.data = list()
        self.sw1 = 0
        self.sw2 = 0

resp = stru()

def send(cmds):
    for cmd in cmds:

        #--- Following 5 line added to have a good format of command in the output.
        temp = stru() ;
        temp.data[:]=cmd[:]
        temp.sw1=12
        temp.sw2=32
        modifyFormat(temp)
        print "req: ", temp.data

        resp.data,resp.sw1,resp.sw2 = connection.transmit(cmd)
        modifyFormat(resp)
        printResponse(resp)

def modifyFormat(resp):
    resp.sw1=hex(resp.sw1)
    resp.sw2=hex(resp.sw2)   
    if (len(resp.sw2)<4):
        resp.sw2=resp.sw2[0:2]+'0'+resp.sw2[2]
    for i in range(0,len(resp.data)):
        resp.data[i]=hex(resp.data[i])
        if (len(resp.data[i])<4):
            resp.data[i]=resp.data[i][0:2]+'0'+resp.data[i][2]

def printResponse(resp):
    print "res: ", resp.data,resp.sw1,resp.sw2


send(cmds)
connection.disconnect()

输出:

>>> ================================ RESTART ================================
Available Readers : ['CREATOR CRT-603 (CZ1) CCR RF 0', 'CREATOR CRT-603 (CZ1) CCR SAM 0']

--- Select Reader (0, 1 , ...): 0

Using : CREATOR CRT-603 (CZ1) CCR RF 0
--- Exception occured! (Wrong reader or No card present)
--- Try again? (0:Exit/1:Again/2:Change Reader)

>>> ================================ RESTART ================================
Available Readers : ['CREATOR CRT-603 (CZ1) CCR RF 0', 'CREATOR CRT-603 (CZ1) CCR SAM 0']

--- Select Reader (0, 1 , ...): 1

Using : CREATOR CRT-603 (CZ1) CCR SAM 0
--- Exception occured! (Wrong reader or No card present)
--- Try again? (0:Exit/1:Again/2:Change Reader)

但两者都存在上述问题!

问题:

1- 在没有可用卡片的情况下如何向读卡器发送扩展命令?

2- 为什么我在嗅探到的数据中看不到命令头?(请注意,由于头是所有扩展命令的预设固定值,我认为读卡器工具不会在GET_FIRMWARE_VERSION命令中发送头,而只发送数据!但它是怎么做到的?)


更新:

通过试错我发现了一些有用的东西。

假设:

  • 伪APDU固定头 = FF 69 44 42
  • GET_READER_FIRMWARE_VERSION的伪APDU数据字段 = 68 92 00 04 00
  • CHANGE_SAM_SLOT的伪APDU数据字段 = 68 92 01 00 03 XX 00 00 (我的读卡器有两个SAM插槽,因此XX可以是0102
  • SELECT APDU命令 = 00 A4 04 00 00

好的,我编写了以下Java程序:

import java.util.List;
import java.util.Scanner;
import javax.smartcardio.Card;
import javax.smartcardio.CardChannel;
import javax.smartcardio.CardException;
import javax.smartcardio.CardTerminal;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
import javax.smartcardio.TerminalFactory;
import javax.xml.bind.DatatypeConverter;

public class TestPCSC {

    public static void main(String[] args) throws CardException {

        TerminalFactory tf = TerminalFactory.getDefault();
        List< CardTerminal> terminals = tf.terminals().list();
        System.out.println("Available Readers:");
        System.out.println(terminals + "\n");

        Scanner scanner = new Scanner(System.in);
        System.out.print("Which reader do you want to send your commands to? (0 or 1 or ...): ");
        String input = scanner.nextLine();
        int readerNum = Integer.parseInt(input);
        CardTerminal cardTerminal = (CardTerminal) terminals.get(readerNum);
        Card connection = cardTerminal.connect("DIRECT");
        CardChannel cardChannel = connection.getBasicChannel();

        System.out.println("Write your commands in Hex form, without '0x' or Space charaters.");
        System.out.println("\n---------------------------------------------------");
        System.out.println("Pseudo-APDU Mode:");
        System.out.println("---------------------------------------------------");
        while (true) {
            System.out.println("Pseudo-APDU command: (Enter 0 to send APDU command)");
            String cmd = scanner.nextLine();
            if (cmd.equals("0")) {
                break;
            }
            System.out.println("Command  : " + cmd);
            byte[] cmdArray = hexStringToByteArray(cmd);
            byte[] resp = connection.transmitControlCommand(CONTROL_CODE(), cmdArray);
            String hex = DatatypeConverter.printHexBinary(resp);
            System.out.println("Response : " + hex + "\n");
        }

        System.out.println("\n---------------------------------------------------");
        System.out.println("APDU Mode:");
        System.out.println("---------------------------------------------------");

        while (true) {
            System.out.println("APDU command: (Enter 0 to exit)");
            String cmd = scanner.nextLine();
            if (cmd.equals("0")) {
                break;
            }
            System.out.println("Command  : " + cmd);
            byte[] cmdArray = hexStringToByteArray(cmd);
            ResponseAPDU resp = cardChannel.transmit(new CommandAPDU(cmdArray));
            byte[] respB = resp.getBytes();
            String hex = DatatypeConverter.printHexBinary(respB);
            System.out.println("Response : " + hex + "\n");
        }

        connection.disconnect(true);

    }

    public static int CONTROL_CODE() {
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.indexOf("windows") > -1) {
            /* Value used by both MS' CCID driver and SpringCard's CCID driver */
            return (0x31 << 16 | 3500 << 2);
        } else {
            /* Value used by PCSC-Lite */
            return 0x42000000 + 1;
        }

    }

    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

}

在上述程序中,我可以使用connection.transmitControlCommandcardChannel.transmit()方法向读卡器发送命令。重点是,使用第一种方法发送到读卡器的所有命令都被视为伪APDU命令,因此不应该使用伪APDU头部!而使用第二种方法发送到读卡器的所有命令都被视为常规APDU命令,因此如果我需要通过第二种方法发送伪APDU命令,则必须添加伪APDU头部。
让我们看看非接触式读卡器的输出:
run:
Available Readers:
[PC/SC terminal ACS ACR122 0, 
PC/SC terminal CREATOR CRT-603 (CZ1) CCR RF 0,
PC/SC terminal CREATOR CRT-603 (CZ1) CCR SAM 0]

Which reader do you want to send your commands to? (0 or 1 or ...): 1
Write your commands in Hex form, without '0x' or Space charaters.

---------------------------------------------------
Pseudo-APDU Mode:
---------------------------------------------------
Pseudo-APDU command: (Enter 0 to send APDU command)
00A4040000
Command  : 00A4040000
Response : 6800
//Based on reader's documents, 0x6800 means "Class byte is not correct"
//As I have a regular java card in the RF field of my  reader, I conclude that 
//this response is Reader's response (and not card response)

Pseudo-APDU command: (Enter 0 to send APDU command)
6892000400
Command  : 6892000400
Response : 433630335F435A375F425F31353038323100039000

Pseudo-APDU command: (Enter 0 to send APDU command)
FF694442056892000400
Command  : FF694442056892000400
Response : 6800
//Pseudo-APDU commands doesn't work in Pseudo-APDU mode if I add the Pseudo-APDU header to them. 

Pseudo-APDU command: (Enter 0 to send APDU command)
00A4040000
Command  : 00A4040000
Response : 6800

Pseudo-APDU command: (Enter 0 to send APDU command)
0

---------------------------------------------------
APDU Mode:
---------------------------------------------------
APDU command: (Enter 0 to exit)
00A4040000
Command  : 00A4040000
Response : 6F198408A000000018434D00A50D9F6E061291921101009F6501FF9000

APDU command: (Enter 0 to exit)
6892000400
Command  : 6892000400
Response : 6E00
//This is the response of my card. I can't receive Firmware version in APDU mode using this command without Pseudo-APDU header. 

APDU command: (Enter 0 to exit)
FF694442056892000400
Command  : FF694442056892000400
Response : 433630335F435A375F425F31353038323100099000
//I successfully received Firmware version in APDU mode using the fixed Pseudo-APDU header.

APDU command: (Enter 0 to exit)
00A4040000
Command  : 00A4040000
Response : 6F198408A000000018434D00A50D9F6E061291921101009F6501FF9000

APDU command: (Enter 0 to exit)
0
BUILD SUCCESSFUL (total time: 1 minute 36 seconds)

还有什么问题吗?

是的,有两个问题!:

1-以上程序只在第一次运行时正常工作。我的意思是,如果我停止运行并重新运行它,第二个方法会抛出异常:

run:
Available Readers:
[PC/SC terminal ACS ACR122 0, PC/SC terminal CREATOR CRT-603 (CZ1) CCR RF 0, PC/SC terminal CREATOR CRT-603 (CZ1) CCR SAM 0]

Which reader do you want to send your commands to? (0 or 1 or ...): 1
Write your commands in Hex form, without '0x' or Space charaters.

---------------------------------------------------
Pseudo-APDU Mode:
---------------------------------------------------

Pseudo-APDU command: (Enter 0 to send APDU command)
00A4040000
Command  : 00A4040000
Response : 6800

Pseudo-APDU command: (Enter 0 to send APDU command)
FF694442056892000400
Command  : FF694442056892000400
Response : 6800

Pseudo-APDU command: (Enter 0 to send APDU command)
6892000400
Command  : 6892000400
Response : 433630335F435A375F425F31353038323100049000

Pseudo-APDU command: (Enter 0 to send APDU command)
00A4040000
Command  : 00A4040000
Response : 6800

Pseudo-APDU command: (Enter 0 to send APDU command)
0

---------------------------------------------------
APDU Mode:
---------------------------------------------------
APDU command: (Enter 0 to exit)
00A4040000
Command  : 00A4040000
Exception in thread "main" javax.smartcardio.CardException: sun.security.smartcardio.PCSCException: Unknown error 0x16
    at sun.security.smartcardio.ChannelImpl.doTransmit(ChannelImpl.java:219)
    at sun.security.smartcardio.ChannelImpl.transmit(ChannelImpl.java:90)
    at TestPCSC.main(TestPCSC.java:58)
Caused by: sun.security.smartcardio.PCSCException: Unknown error 0x16
    at sun.security.smartcardio.PCSC.SCardTransmit(Native Method)
    at sun.security.smartcardio.ChannelImpl.doTransmit(ChannelImpl.java:188)
    ... 2 more
Java Result: 1
BUILD SUCCESSFUL (total time: 39 seconds)

如您所见,我不能再使用第二种方法,需要将读卡器断电并再次通电以使其正常工作。

2-接触界面(我指的是SAM读卡器)总是抛出上述异常!我的意思是第二种方法根本不起作用(无论是第一次运行还是第二次、第三次等等)

请注意,我尝试了不同的读卡器,似乎这不仅限于该读卡器。一些ACS读卡器也存在类似或完全相同的重新运行问题

有人有任何想法吗?

另外一个问题,Python是否有像Java一样发送Pseudo-APDU的相等方法?

最后,从读卡器的角度来看,“connection.transmitControlCommand”和“cardChannel.transmit()”方法有什么区别?


不能确定,但通常读者在计算机上安装了特定的读卡器库,可以与PCSC的驱动程序并行使用。在这种情况下,读卡器制造商的GUI可能依赖于这些库,因为它们可能提供更多的读卡器特定功能。我不确定你遇到的透传问题有多少是由于智能卡读卡器的驱动程序或PCSC堆栈本身引起的。不过读卡器制造商应该知道。 - Maarten Bodewes
1
你应该能够通过依赖查看器检查不同工具使用的库。 - Maarten Bodewes
1
@MaartenBodewes 谢谢您,亲爱的博德维斯先生。我已经更新了问题。关于特定于读取器的库,我认为这不是我的情况所在。所有我读取器拥有的工具都是一个便携式可执行文件(没有任何.sys文件或.dll库)。无论如何,我在Windows命令行中使用了tasklist \M命令,并返回了ntdll.dll,wow64.dll,wow64win.dll,wow64cpu.dll用于此可执行文件进程。 - Ebrahim Ghasemi
我还使用“进程监视器”(一种来自_SysInternals_公司的工具)监控了该工具的进程,并发现它仅加载了一些Windows/内核dll库,包括“WinSCard.dll”。实际上,它没有任何特殊的库。 - Ebrahim Ghasemi
@MaartenBodewes 亲爱的 Maarten,可以邀请您看一下这个房间吗?链接 - Ebrahim Ghasemi
显示剩余3条评论
2个回答

2
当您停止“智能卡”服务时,工具是否仍会返回固件版本?如果是,则该工具可能使用原始IOCTL命令(DeviceIoControl)与驱动程序通信。
请看这个问题。作者说你需要将SCARD_PROTOCOL_UNDEFINED设置为协议参数。
SCardConnect(hSC,
             readerState.szReader,
             SCARD_SHARE_DIRECT,
             SCARD_PROTOCOL_UNDEFINED,
             &hCH,
             &dwAP
            );

我刚刚尝试了一下,至少在Windows 10上似乎可以工作。即使没有插入卡片,也可以进行通信。不过我没有测试其他Windows版本。


亲爱的阿明,很抱歉我无法再访问读取器进行检查。 :) - Ebrahim Ghasemi
哦,太遗憾了。 - arminb
1
@Abraham 我更新了我的答案。我能够通过将 SCARD_PROTOCOL_UNDEFINED 作为协议参数传递来成功地在没有插入卡的情况下与读卡器进行通信。 - arminb
1
太好了!感谢你更新答案并分享了你的经验,亲爱的阿明。 - Ebrahim Ghasemi

0

readers() 是可用读卡器的数组索引

reader = r[target_reader]

转换

reader = r[int(target_reader)]

输出

Available Readers : ['JAVACOS Virtual Contact Reader 0', 'JAVACOS Virtual Contactless Reader 1', 'OMNIKEY CardMan 3x21 0']
--- Select Reader (0, 1 , ...): 2
Using : OMNIKEY CardMan 3x21 0
ATR :  3B 9E 94 80 1F 47 80 31 A0 73 BE 21 13 66 86 88 02 14 4B 10 19

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接