1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
#!/usr/bin/python
# testing usb-ccid:
# run qemu with a usb-ccid device and a chardev connected to a socket
# on port 2001 (just to work with this script):
# qemu ... -chardev socket,server,host=0.0.0.0,port=2001,id=ccid,nowait -device usb-ccid,chardev=ccid
import socket
import struct
SCard_ATR, SCard_APDU, SCard_Remove = range(3)
default_atr=''.join([chr(x) for x in [0x3B, 0xB0, 0x18, 0x00, 0xD1, 0x81, 0x05, 0xB1, 0x40, 0x38, 0x1F, 0x03, 0x28]])
def insert_card(s, atr=default_atr):
send_msg(s, SCard_ATR, atr)
def send_msg(s, the_type, data):
s.send(struct.pack('ii', the_type, len(data)) + data)
def echoback(s):
while True:
msg = s.recv(10000)
the_type, the_len = struct.unpack('ii', msg[:8])
if the_len != len(msg) - 8:
print "length in header doesn't match message: header said %s, message minus 8 is %s" % (the_len, len(msg) - 8)
if the_type == SCard_ATR:
print "got ATR?? ignoring"
continue
if the_type == SCard_APDU:
print "got APDU of length %s" % the_len
send_msg(s, SCard_APDU, msg[8:])
continue
if the_type == SCard_Remove:
print "got removal??"
continue
print "got unexpected message type %s (length = %s)" % (the_type, the_len)
if __name__ == '__main__':
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 2001))
import sys
if len(sys.argv) > 1:
if sys.argv[1] == 'loop':
print "entering echo loop"
echoback(s)
elif sys.argv[1] == 'atr':
atr = default_atr if len(sys.argv) == 2 else sys.argv[2]
print "sending atr %r" % atr
insert_card(s, atr)
|