Debian Codegraph @

src/spy/pcsc-spy

raw
1 #! /usr/bin/python3
2
3 """
4 # Display PC/SC functions arguments
5 # Copyright (C) 2011-2024 Ludovic Rousseau
6 """
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20
21 import os
22 import signal
23 import time
24 try:
25 # for Python3
26 from queue import Queue
27 except ImportError:
28 # for Python2
29 from Queue import Queue
30 from threading import Thread
31 from operator import attrgetter
32
33
34 def hexdump(data_buffer, width=16):
35 def quotechars(data_buffer):
36 return ''.join(['.', chr(c)][c > 31 and c < 127] for c in data_buffer)
37
38 result = []
39 offset = 0
40 while data_buffer:
41 line = data_buffer[:width]
42 data_buffer = data_buffer[width:]
43 hex_dump = " ".join("%02X" % c for c in line)
44 ascii_dump = quotechars(line)
45 if len(line) < width:
46 hex_dump += " " * (width - len(line))
47 result.append("%04X %s %s" % (offset, hex_dump, ascii_dump))
48 offset += width
49 return result
50
51
52 def _parse_rv(line):
53 """ parse the return value line """
54 if line == "":
55 raise Exception("Empty line (application exited?)")
56
57 (direction, sec, usec, function, rv) = line.split('|')
58 if direction != '<':
59 raise Exception("Wrong line:", line)
60
61 sec = int(sec)
62 usec = int(usec)
63
64 return (rv, sec, usec)
65
66
67 class SpyExit(Exception):
68 pass
69
70 class StatRecord(object):
71 """ Record to store statistics """
72
73 def __init__(self, name):
74 self.name = name
75 self.executions = list()
76 self.total_time = 0
77 self.occurrences = 0
78
79 def __repr__(self):
80 return self.name + ": " + repr(self.executions)
81
82
83 class PCSCspy(object):
84 """ PC/SC spy """
85
86 color_red = "\x1b[01;31m"
87 color_green = "\x1b[32m"
88 color_blue = "\x1b[34m"
89 color_magenta = "\x1b[35m"
90 color_normal = "\x1b[0m"
91
92 def get_line(self):
93 line = self.queue.get()
94 if line == "EXIT":
95 raise SpyExit()
96 return line
97
98 def _log_rv(self):
99 """ log the return value """
100 line = self.get_line()
101 (rv, sec, usec) = _parse_rv(line)
102 delta_sec = sec - self.sec
103 delta_usec = usec - self.usec
104 if delta_usec < 0:
105 delta_sec -= 1
106 delta_usec += 1000000
107 if self.diffable:
108 time = " [??.??]"
109 else:
110 time = " [%d.%06d]" % (delta_sec, delta_usec)
111 self.execution_time = delta_sec + delta_usec / 1000000.
112
113 rvs = {
114 0x00000000: "SCARD_S_SUCCESS",
115 0x80100001: "SCARD_F_INTERNAL_ERROR",
116 0x80100002: "SCARD_E_CANCELLED",
117 0x80100003: "SCARD_E_INVALID_HANDLE",
118 0x80100004: "SCARD_E_INVALID_PARAMETER",
119 0x80100005: "SCARD_E_INVALID_TARGET",
120 0x80100006: "SCARD_E_NO_MEMORY",
121 0x80100007: "SCARD_F_WAITED_TOO_LONG",
122 0x80100008: "SCARD_E_INSUFFICIENT_BUFFER",
123 0x80100009: "SCARD_E_UNKNOWN_READER",
124 0x8010000A: "SCARD_E_TIMEOUT",
125 0x8010000B: "SCARD_E_SHARING_VIOLATION",
126 0x8010000C: "SCARD_E_NO_SMARTCARD",
127 0x8010000D: "SCARD_E_UNKNOWN_CARD",
128 0x8010000E: "SCARD_E_CANT_DISPOSE",
129 0x8010000F: "SCARD_E_PROTO_MISMATCH",
130 0x80100010: "SCARD_E_NOT_READY",
131 0x80100011: "SCARD_E_INVALID_VALUE",
132 0x80100012: "SCARD_E_SYSTEM_CANCELLED",
133 0x80100013: "SCARD_F_COMM_ERROR",
134 0x80100014: "SCARD_F_UNKNOWN_ERROR",
135 0x80100015: "SCARD_E_INVALID_ATR",
136 0x80100016: "SCARD_E_NOT_TRANSACTED",
137 0x80100017: "SCARD_E_READER_UNAVAILABLE",
138 0x80100018: "SCARD_P_SHUTDOWN",
139 0x80100019: "SCARD_E_PCI_TOO_SMALL",
140 0x8010001A: "SCARD_E_READER_UNSUPPORTED",
141 0x8010001B: "SCARD_E_DUPLICATE_READER",
142 0x8010001C: "SCARD_E_CARD_UNSUPPORTED",
143 0x8010001D: "SCARD_E_NO_SERVICE",
144 0x8010001E: "SCARD_E_SERVICE_STOPPED",
145 0x8010001F: "SCARD_E_UNSUPPORTED_FEATURE",
146 0x80100020: "SCARD_E_ICC_INSTALLATION",
147 0x80100021: "SCARD_E_ICC_CREATEORDER",
148 0x80100023: "SCARD_E_DIR_NOT_FOUND",
149 0x80100024: "SCARD_E_FILE_NOT_FOUND",
150 0x80100025: "SCARD_E_NO_DIR",
151 0x80100026: "SCARD_E_NO_FILE",
152 0x80100027: "SCARD_E_NO_ACCESS",
153 0x80100028: "SCARD_E_WRITE_TOO_MANY",
154 0x80100029: "SCARD_E_BAD_SEEK",
155 0x8010002A: "SCARD_E_INVALID_CHV",
156 0x8010002B: "SCARD_E_UNKNOWN_RES_MSG",
157 0x8010002C: "SCARD_E_NO_SUCH_CERTIFICATE",
158 0x8010002D: "SCARD_E_CERTIFICATE_UNAVAILABLE",
159 0x8010002E: "SCARD_E_NO_READERS_AVAILABLE",
160 0x8010002F: "SCARD_E_COMM_DATA_LOST",
161 0x80100030: "SCARD_E_NO_KEY_CONTAINER",
162 0x80100031: "SCARD_E_SERVER_TOO_BUSY",
163 0x80100065: "SCARD_W_UNSUPPORTED_CARD",
164 0x80100066: "SCARD_W_UNRESPONSIVE_CARD",
165 0x80100067: "SCARD_W_UNPOWERED_CARD",
166 0x80100068: "SCARD_W_RESET_CARD",
167 0x80100069: "SCARD_W_REMOVED_CARD",
168 0x8010006A: "SCARD_W_SECURITY_VIOLATION",
169 0x8010006B: "SCARD_W_WRONG_CHV",
170 0x8010006C: "SCARD_W_CHV_BLOCKED",
171 0x8010006D: "SCARD_W_EOF",
172 0x8010006E: "SCARD_W_CANCELLED_BY_USER",
173 0x8010006F: "SCARD_W_CARD_NOT_AUTHENTICATED",
174 }
175 rv_text = rvs[int(rv, 16)]
176 data = " => " + rv_text + " [" + rv + "] "
177 if "0x00000000" != rv:
178 if self.color:
179 print(self.indent + PCSCspy.color_red + data +
180 PCSCspy.color_normal + time)
181 else:
182 print(self.indent + data + time)
183 else:
184 print(self.indent + data + time)
185
186 return rv_text
187
188 def log_in(self, line):
189 """ generic log for IN line """
190 if self.color:
191 print(self.indent + PCSCspy.color_green + " i " + line +
192 PCSCspy.color_normal)
193 else:
194 print(self.indent + " i " + line)
195
196 def log_out(self, line):
197 """ generic log for OUT line """
198 if self.color:
199 print(self.indent + PCSCspy.color_magenta + " o " + line +
200 PCSCspy.color_normal)
201 else:
202 print(self.indent + " o " + line)
203
204 def log_in_multi(self, lines, padding=""):
205 """ generic log for IN lines """
206 for line in lines:
207 self.log_in(padding + line)
208
209 def log_out_multi(self, lines, padding=""):
210 """ generic log for OUT lines """
211 for line in lines:
212 self.log_out(padding + line)
213
214 def log_in_hCard(self):
215 """ log hCard IN parameter """
216 hCard = self.get_line()
217 if self.diffable:
218 self.log_in("hCard: 0x????")
219 else:
220 self.log_in("hCard: %s" % hCard)
221
222 def log_in_scard_io_request(self):
223 """ log SCARD_IO_REQUEST IN parameter """
224 dwProtocol = self.get_line()
225 if self.diffable:
226 self.log_in("pioSendPci.dwProtocol: 0x????")
227 else:
228 self.log_in("pioSendPci.dwProtocol: %s" % dwProtocol)
229
230 cbPciLength = self.get_line()
231 if self.diffable:
232 self.log_in("pioSendPci.cbPciLength: 0x????")
233 else:
234 self.log_in("pioSendPci.cbPciLength: %s" % cbPciLength)
235
236 def log_in_hContext(self):
237 """ log hContext IN parameter """
238 hContext = self.get_line()
239 if self.diffable:
240 self.log_in("hContext: 0x????")
241 else:
242 self.log_in("hContext: %s" % hContext)
243
244 def log_in_disposition(self):
245 """ log dwDisposition IN parameter """
246 dwDisposition = self.get_line()
247 dispositions = {0: 'SCARD_LEAVE_CARD',
248 1: 'SCARD_RESET_CARD',
249 2: 'SCARD_UNPOWER_CARD',
250 3: 'SCARD_EJECT_CARD'}
251 try:
252 disposition = dispositions[int(dwDisposition, 16)]
253 except KeyError:
254 disposition = "UNKNOWN"
255 self.log_in("dwDisposition: %s (%s)" % (disposition,
256 dwDisposition))
257
258 def log_in_attrid(self):
259 """ log dwAttrId IN parameter """
260 dwAttrId = self.get_line()
261 attrids = {0x00010100: 'SCARD_ATTR_VENDOR_NAME',
262 0x00010102: 'SCARD_ATTR_VENDOR_IFD_VERSION',
263 0x00010103: 'SCARD_ATTR_VENDOR_IFD_SERIAL_NO',
264 0x0007A007: 'SCARD_ATTR_MAXINPUT',
265 0x00090300: 'SCARD_ATTR_ICC_PRESENCE',
266 0x00090301: 'SCARD_ATTR_ICC_INTERFACE_STATUS',
267 0x00090303: 'SCARD_ATTR_ATR_STRING',
268 0x7FFF0003: 'SCARD_ATTR_DEVICE_FRIENDLY_NAME_A',
269 0x7FFF0004: 'SCARD_ATTR_DEVICE_SYSTEM_NAME_A',
270 0x7FFF0005: 'SCARD_ATTR_DEVICE_FRIENDLY_NAME_W',
271 0x7FFF0006: 'SCARD_ATTR_DEVICE_SYSTEM_NAME_W'}
272 try:
273 attrid = attrids[int(dwAttrId, 16)]
274 except KeyError:
275 attrid = "UNKNOWN"
276 self.log_in("dwAttrId: %s (%s)" % (attrid, dwAttrId))
277
278 def log_in_dwShareMode(self):
279 """ log dwShareMode IN parameter """
280 dwShareMode = self.get_line()
281 sharemodes = {1: 'SCARD_SHARE_EXCLUSIVE',
282 2: 'SCARD_SHARE_SHARED',
283 3: 'SCARD_SHARE_DIRECT'}
284 try:
285 sharemode = sharemodes[int(dwShareMode, 16)]
286 except KeyError:
287 sharemode = "UNKNOWN"
288 self.log_in("dwShareMode: %s (%s)" % (sharemode, dwShareMode))
289
290 def log_in_dwPreferredProtocols(self):
291 """ log dwPreferredProtocols IN parameter """
292 dwPreferredProtocols = self.get_line()
293 PreferredProtocols = list()
294 protocol = int(dwPreferredProtocols, 16)
295 if protocol & 1:
296 PreferredProtocols.append("T=0")
297 if protocol & 2:
298 PreferredProtocols.append("T=1")
299 if protocol & 4:
300 PreferredProtocols.append("RAW")
301 if protocol & 8:
302 PreferredProtocols.append("T=15")
303 self.log_in("dwPreferredProtocols: %s (%s)" % (dwPreferredProtocols,
304 ", ".join(PreferredProtocols)))
305
306 def log_out_scard_io_request(self):
307 """ log SCARD_IO_REQUEST OUT parameter """
308 dwProtocol = self.get_line()
309 if self.diffable:
310 self.log_out("pioRecvPci.dwProtocol: 0x????")
311 else:
312 self.log_out("pioRecvPci.dwProtocol: %s" % dwProtocol)
313
314 cbPciLength = self.get_line()
315 if self.diffable:
316 self.log_out("pioRecvPci.cbPciLength: 0x????")
317 else:
318 self.log_out("pioRecvPci.cbPciLength: %s" % cbPciLength)
319
320 def log_out_dwActiveProtocol(self):
321 """ log dwActiveProtocol OUT parameter """
322 dwActiveProtocol = self.get_line()
323 protocol = int(dwActiveProtocol, 16)
324 if protocol & 1:
325 protocol = "T=0"
326 elif protocol & 2:
327 protocol = "T=1"
328 elif protocol & 4:
329 protocol = "RAW"
330 elif protocol & 8:
331 protocol = "T=15"
332 else:
333 protocol = "UNKNOWN"
334 self.log_out("dwActiveProtocol: %s (%s)" % (protocol,
335 dwActiveProtocol))
336
337 def log_out_hContext(self):
338 """ log hContext OUT parameter """
339 hContext = self.get_line()
340 if self.diffable:
341 self.log_out("hContext: 0x????")
342 else:
343 self.log_out("hContext: %s" % hContext)
344
345 def _get_state(self, dwState):
346 """ parse dwCurrentState and dwEventState """
347 SCardStates = {0: 'SCARD_STATE_UNAWARE',
348 1: 'SCARD_STATE_IGNORE',
349 2: 'SCARD_STATE_CHANGED',
350 4: 'SCARD_STATE_UNKNOWN',
351 8: 'SCARD_STATE_UNAVAILABLE',
352 16: 'SCARD_STATE_EMPTY',
353 32: 'SCARD_STATE_PRESENT',
354 64: 'SCARD_STATE_ATRMATCH',
355 128: 'SCARD_STATE_EXCLUSIVE',
356 256: 'SCARD_STATE_INUSE',
357 512: 'SCARD_STATE_MUTE',
358 1024: 'SCARD_STATE_UNPOWERED'}
359
360 state = list()
361 for bit in SCardStates.keys():
362 if dwState & bit:
363 state.append(SCardStates[bit])
364 return ", ".join(state)
365
366 def log_dwCurrentState(self, log):
367 """ log dwCurrentState IN/OUT parameter """
368 dwCurrentState = self.get_line()
369 state = self._get_state(int(dwCurrentState, 16))
370 log(" dwCurrentState: %s (%s)" % (state, dwCurrentState))
371
372 def log_dwEventState(self, log):
373 """ log dwEventState IN/OUT parameter """
374 dwEventState = self.get_line()
375 state = self._get_state(int(dwEventState, 16))
376 log(" dwEventState: %s (%s)" % (state, dwEventState))
377
378 def log_dwControlCode(self):
379 """ log SCardControl() dwControlCode """
380 dwControlCode = self.get_line()
381
382 try:
383 code = self.ControlCodes[int(dwControlCode, 16)]
384 except KeyError:
385 code = "UNKNOWN"
386 self.log_in("dwControlCode: %s (%s)" % (code, dwControlCode))
387
388 return int(dwControlCode, 16)
389
390 def log_in2(self, header):
391 """ generic log IN parameter """
392 data = self.get_line()
393 if data.startswith("0x"):
394 decimal = int(data, 16)
395 self.log_in("%s %s (%d)" % (header, data, decimal))
396 else:
397 self.log_in("%s %s" % (header, data))
398 return data
399
400 def log_out2(self, header):
401 """ generic log OUT parameter """
402 data = self.get_line()
403 if data.startswith("0x"):
404 decimal = int(data, 16)
405 self.log_out("%s %s (%d)" % (header, data, decimal))
406 else:
407 self.log_out("%s %s" % (header, data))
408 return data
409
410 def log_out_n_str(self, size_name, field_name):
411 """ log multi-lines entries """
412 data = self.get_line()
413 self.log_out("%s %s" % (size_name, data))
414 size = int(data, 16)
415 data_read = 0
416 if 0 == size:
417 data = self.get_line()
418 self.log_out("%s %s" % (field_name, data))
419 else:
420 while data_read < size:
421 data = self.get_line()
422 self.log_out("%s %s" % (field_name, data))
423 if data == 'NULL':
424 break
425 data_read += len(data) + 1
426
427 def log_name(self, name):
428 """ log function name """
429 if self.color:
430 print(self.indent + PCSCspy.color_blue + name +
431 PCSCspy.color_normal)
432 else:
433 print(self.indent + name)
434
435 def _log_readers(self, readers, direction):
436 """ log SCARD_READERSTATE structure """
437 log = self.log_in2
438 raw_log = self.log_in
439 if (direction == "out"):
440 log = self.log_out2
441 raw_log = self.log_out
442 for index in range(readers):
443 log("szReader:")
444 self.log_dwCurrentState(raw_log)
445 self.log_dwEventState(raw_log)
446 log(" Atr length:")
447 log(" Atr:")
448
449 def log_buffer(self, field, direction):
450 log = self.log_in
451 log_multi = self.log_in_multi
452 if direction == "out":
453 log = self.log_out
454 log_multi = self.log_out_multi
455
456 hex_buffer = self.get_line()
457 log(field)
458 if hex_buffer == "NULL":
459 log(" NULL")
460 elif hex_buffer != "":
461 int_buffer = [int(x, 16) for x in hex_buffer.split(" ")]
462 formated_buffer = hexdump(int_buffer)
463 log_multi(formated_buffer, " ")
464
465 return hex_buffer
466
467 def _SCardEstablishContext(self):
468 """ SCardEstablishContext """
469 self.log_name("SCardEstablishContext")
470 dwScope = self.get_line()
471 scopes = {0: 'SCARD_SCOPE_USER',
472 1: 'SCARD_SCOPE_TERMINAL',
473 2: 'SCARD_SCOPE_SYSTEM'}
474 self.log_in("dwScope: %s (%s)" % (scopes[int(dwScope, 16)], dwScope))
475 self.log_out_hContext()
476 self._log_rv()
477
478 def _SCardIsValidContext(self):
479 """ SCardIsValidContext """
480 self.log_name("SCardIsValidContext")
481 self.log_in_hContext()
482 self._log_rv()
483
484 def _SCardReleaseContext(self):
485 """ SCardReleaseContext """
486 self.log_name("SCardReleaseContext")
487 self.log_in_hContext()
488 self._log_rv()
489
490 def _SCardListReaders(self):
491 """ SCardListReaders """
492 self.log_name("SCardListReaders")
493 self.log_in_hContext()
494 self.log_in2("mszGroups:")
495 self.log_out_n_str("pcchReaders:", "mszReaders:")
496 self._log_rv()
497
498 def _SCardListReaderGroups(self):
499 """ SCardListReaderGroups """
500 self.log_name("SCardListReaderGroups")
501 self.log_in_hContext()
502 self.log_in2("pcchGroups:")
503 self.log_out_n_str("pcchGroups:", "mszGroups:")
504 self._log_rv()
505
506 def _SCardGetStatusChange(self):
507 """ SCardGetStatusChange """
508 self.log_name("SCardGetStatusChange")
509 self.log_in_hContext()
510 self.log_in2("dwTimeout:")
511 readers = int(self.get_line(), 16)
512 self.log_in("cReaders: %d" % readers)
513 self._log_readers(readers, direction="in")
514 self._log_readers(readers, direction="out")
515 self._log_rv()
516
517 def _SCardFreeMemory(self):
518 """ SCardFreeMemory """
519 self.log_name("SCardFreeMemory")
520 self.log_in_hContext()
521 self.log_in2("pvMem:")
522 self._log_rv()
523
524 def _SCardConnect(self):
525 """ SCardConnect """
526 self.log_name("SCardConnect")
527 self.log_in_hContext()
528 self.log_in2("szReader")
529 self.log_in_dwShareMode()
530 self.log_in_dwPreferredProtocols()
531 self.log_in2("phCard")
532 self.log_in2("pdwActiveProtocol")
533 self.log_out2("phCard")
534 self.log_out_dwActiveProtocol()
535 self._log_rv()
536
537 def _SCardTransmit(self):
538 """ SCardTransmit """
539 self.log_name("SCardTransmit")
540 self.log_in_hCard()
541 self.log_in_scard_io_request()
542 self.log_in2("bSendLength")
543 self.log_buffer("bSendBuffer", "in")
544 self.log_out_scard_io_request()
545 self.log_out2("bRecvLength")
546 self.log_buffer("bRecvBuffer", "out")
547 self._log_rv()
548
549 def _SCardControl(self):
550 """ SCardControl """
551 self.log_name("SCarControl")
552 self.log_in_hCard()
553 dwControlCode = self.log_dwControlCode()
554 bSendLength = self.log_in2("bSendLength")
555 bSendBuffer = self.log_buffer("bSendBuffer", "in")
556 bRecvLength = self.log_out2("bRecvLength")
557 bRecvBuffer = self.log_buffer("bRecvBuffer", "out")
558
559 rv_text = self._log_rv()
560
561 # do not parse the received buffer in case of error
562 if rv_text != "SCARD_S_SUCCESS":
563 return
564
565 def hex2int(data, length):
566 return [int(x, 16) for x in data.split(" ")]
567
568 if dwControlCode == self.CM_IOCTL_GET_FEATURE_REQUEST:
569 print(" parsing CM_IOCTL_GET_FEATURE_REQUEST results:")
570 bRecvLength = int(bRecvLength, 16)
571
572 bRecvBuffer = hex2int(bRecvBuffer, bRecvLength)
573
574 # parse GET_FEATURE_REQUEST results
575 while bRecvBuffer:
576 tag = bRecvBuffer[0]
577 length = bRecvBuffer[1]
578 value = bRecvBuffer[2:2 + length]
579 value_int = value[3] + 256 * (value[2] + 256
580 * (value[1] + 256 * value[0]))
581 try:
582 self.ControlCodes[value_int] = self.features[tag]
583 self.__dict__[self.features[tag]] = value_int
584 except KeyError:
585 self.ControlCodes[value_int] = "UNKNOWN"
586
587 print(" Tag %s is 0x%X" % (self.ControlCodes[value_int],
588 value_int))
589
590 bRecvBuffer = bRecvBuffer[2 + length:]
591
592 elif dwControlCode == self.FEATURE_GET_TLV_PROPERTIES:
593 print(" parsing FEATURE_GET_TLV_PROPERTIES results:")
594 bRecvLength = int(bRecvLength, 16)
595
596 bRecvBuffer = hex2int(bRecvBuffer, bRecvLength)
597
598 tlv_properties = {
599 1: "PCSCv2_PART10_PROPERTY_wLcdLayout",
600 2: "PCSCv2_PART10_PROPERTY_bEntryValidationCondition",
601 3: "PCSCv2_PART10_PROPERTY_bTimeOut2",
602 4: "PCSCv2_PART10_PROPERTY_wLcdMaxCharacters",
603 5: "PCSCv2_PART10_PROPERTY_wLcdMaxLines",
604 6: "PCSCv2_PART10_PROPERTY_bMinPINSize",
605 7: "PCSCv2_PART10_PROPERTY_bMaxPINSize",
606 8: "PCSCv2_PART10_PROPERTY_sFirmwareID",
607 9: "PCSCv2_PART10_PROPERTY_bPPDUSupport",
608 10: "PCSCv2_PART10_PROPERTY_dwMaxAPDUDataSize",
609 11: "PCSCv2_PART10_PROPERTY_wIdVendor",
610 12: "PCSCv2_PART10_PROPERTY_wIdProduct",
611 }
612
613 # parse GET_TLV_PROPERTIES results
614 while bRecvBuffer:
615 tag = bRecvBuffer[0]
616 length = bRecvBuffer[1]
617 value = bRecvBuffer[2:2 + length]
618
619 try:
620 tag_text = tlv_properties[tag]
621 except KeyError:
622 tag_text = "UNKNOWN"
623
624 print(" Tag:", tag_text)
625 print(" Length: ", length)
626 print(" Value:", value)
627
628 bRecvBuffer = bRecvBuffer[2 + length:]
629
630 elif dwControlCode == self.FEATURE_IFD_PIN_PROPERTIES:
631 print(" parsing FEATURE_IFD_PIN_PROPERTIES results:")
632 bRecvBuffer = hex2int(bRecvBuffer, int(bRecvLength, 16))
633
634 print(" wLcdLayout:", bRecvBuffer[0], bRecvBuffer[1])
635 print(" bEntryValidationCondition:", bRecvBuffer[2])
636 print(" bTimeOut2:", bRecvBuffer[3])
637
638 elif dwControlCode == self.FEATURE_VERIFY_PIN_DIRECT:
639 print(" parsing FEATURE_VERIFY_PIN_DIRECT:")
640 bSendBuffer = hex2int(bSendBuffer, int(bSendLength, 16))
641
642 print(" bTimerOut:", bSendBuffer[0])
643 print(" bTimerOut2:", bSendBuffer[1])
644 print(" bmFormatString:", bSendBuffer[2])
645 print(" bmPINBlockString:", bSendBuffer[3])
646 print(" bmPINLengthFormat:", bSendBuffer[4])
647 print(" wPINMaxExtraDigit: 0x%02X%02X" % (bSendBuffer[6],
648 bSendBuffer[5]))
649 print(" Min:", bSendBuffer[6])
650 print(" Max:", bSendBuffer[5])
651 print(" bEntryValidationCondition:", bSendBuffer[7])
652 print(" bNumberMessage:", bSendBuffer[8])
653 print(" wLangId: 0x%02X%02X" % (bSendBuffer[10],
654 bSendBuffer[9]))
655 print(" bMsgIndex:", bSendBuffer[11])
656 print(" bTeoPrologue:", bSendBuffer[12], bSendBuffer[13], \
657 bSendBuffer[14])
658 print(" ulDataLength:", bSendBuffer[15] + \
659 bSendBuffer[16] * 256 + bSendBuffer[17] * 2 ** 16 + \
660 bSendBuffer[18] * 2 ** 24)
661 print(" APDU:")
662 result = hexdump(bSendBuffer[19:])
663 for line in result:
664 print(" ", line)
665
666 def _SCardGetAttrib(self):
667 """ SCardGetAttrib """
668 self.log_name("SCardGetAttrib")
669 self.log_in_hCard()
670 self.log_in_attrid()
671 self.log_out2("bAttrLen")
672 self.log_buffer("bAttr", "out")
673 self._log_rv()
674
675 def _SCardSetAttrib(self):
676 """ SCardSetAttrib """
677 self.log_name("SCardSetAttrib")
678 self.log_in_hCard()
679 self.log_in_attrid()
680 self.log_in2("bAttrLen")
681 self.log_buffer("bAttr", "in")
682 self._log_rv()
683
684 def _SCardStatus(self):
685 """ SCardStatus """
686 self.log_name("SCardStatus")
687 self.log_in_hCard()
688 self.log_in2("pcchReaderLen")
689 self.log_in2("pcbAtrLen")
690 self.log_out2("cchReaderLen")
691 self.log_out2("mszReaderName")
692 self.log_out2("dwState")
693 self.log_out2("dwProtocol")
694 data = self.log_out2("bAtrLen")
695 if not data == "NULL":
696 self.log_out2("bAtr")
697 else:
698 self.log_out("bAtr")
699 self._log_rv()
700
701 def _SCardReconnect(self):
702 """ SCardReconnect """
703 self.log_name("SCardReconnect")
704 self.log_in_hCard()
705 self.log_in_dwShareMode()
706 self.log_in_dwPreferredProtocols()
707 self.log_in2("dwInitialization")
708 self.log_out_dwActiveProtocol()
709 self._log_rv()
710
711 def _SCardDisconnect(self):
712 """" SCardDisconnect """
713 self.log_name("SCardDisconnect")
714 self.log_in_hCard()
715 self.log_in_disposition()
716 self._log_rv()
717
718 def _SCardBeginTransaction(self):
719 """ SCardBeginTransaction """
720 self.log_name("SCardBeginTransaction")
721 self.log_in_hCard()
722 self._log_rv()
723
724 def _SCardEndTransaction(self):
725 """ SCardEndTransaction """
726 self.log_name("SCardEndTransaction")
727 self.log_in_hCard()
728 self.log_in_disposition()
729 self._log_rv()
730
731 def _SCardCancel(self):
732 """ SCardCancel """
733 self.log_name("SCardCancel")
734 self.log_in_hCard()
735 self._log_rv()
736
737 def __init__(self, queue, stats, indent=0, color=True, diffable=False):
738 """ constructor """
739
740 # communication queue
741 self.queue = queue
742
743 self.color = color
744 self.diffable = diffable
745 self.stats = stats
746 self.indent = " " * (indent * 4)
747 if display_thread:
748 self.indent += " (t%d) " % indent
749
750 self.features = {0x01: "FEATURE_VERIFY_PIN_START",
751 0x02: "FEATURE_VERIFY_PIN_FINISH",
752 0x03: "FEATURE_MODIFY_PIN_START",
753 0x04: "FEATURE_MODIFY_PIN_FINISH",
754 0x05: "FEATURE_GET_KEY_PRESSED",
755 0x06: "FEATURE_VERIFY_PIN_DIRECT",
756 0x07: "FEATURE_MODIFY_PIN_DIRECT",
757 0x08: "FEATURE_MCT_READER_DIRECT",
758 0x09: "FEATURE_MCT_UNIVERSAL",
759 0x0A: "FEATURE_IFD_PIN_PROPERTIES",
760 0x0B: "FEATURE_ABORT",
761 0x0C: "FEATURE_SET_SPE_MESSAGE",
762 0x0D: "FEATURE_VERIFY_PIN_DIRECT_APP_ID",
763 0x0E: "FEATURE_MODIFY_PIN_DIRECT_APP_ID",
764 0x0F: "FEATURE_WRITE_DISPLAY",
765 0x10: "FEATURE_GET_KEY",
766 0x11: "FEATURE_IFD_DISPLAY_PROPERTIES",
767 0x12: "FEATURE_GET_TLV_PROPERTIES",
768 0x13: "FEATURE_CCID_ESC_COMMAND"}
769
770 def SCARD_CTL_CODE(code):
771 return 0x42000000 + code
772
773 self.CM_IOCTL_GET_FEATURE_REQUEST = SCARD_CTL_CODE(3400)
774 self.ControlCodes = {
775 SCARD_CTL_CODE(1): "IOCTL_SMARTCARD_VENDOR_IFD_EXCHANGE",
776 SCARD_CTL_CODE(3400): "CM_IOCTL_GET_FEATURE_REQUEST"
777 }
778 # dwControlCode not yet known
779 for key in self.features.keys():
780 self.__dict__[self.features[key]] = -1
781
782 def worker(self, *args):
783 line = self.queue.get()
784 while line != '':
785 # Enter function?
786 if line[0] != '>':
787 if line == 'EXIT':
788 return
789 else:
790 print("Garbage: ", line)
791 else:
792 try:
793 # dispatch
794 (direction, sec, usec, fct) = line.strip().split('|')
795 self.sec = int(sec)
796 self.usec = int(usec)
797 if fct == 'SCardEstablishContext':
798 self._SCardEstablishContext()
799 elif fct == 'SCardReleaseContext':
800 self._SCardReleaseContext()
801 elif fct == 'SCardIsValidContext':
802 self._SCardIsValidContext()
803 elif fct == 'SCardListReaderGroups':
804 self._SCardListReaderGroups()
805 elif fct == 'SCardFreeMemory':
806 self._SCardFreeMemory()
807 elif fct == 'SCardListReaders':
808 self._SCardListReaders()
809 elif fct == 'SCardGetStatusChange':
810 self._SCardGetStatusChange()
811 elif fct == 'SCardConnect':
812 self._SCardConnect()
813 elif fct == 'SCardTransmit':
814 self._SCardTransmit()
815 elif fct == 'SCardControl' or fct == 'SCardControl132':
816 self._SCardControl()
817 elif fct == 'SCardGetAttrib':
818 self._SCardGetAttrib()
819 elif fct == 'SCardSetAttrib':
820 self._SCardSetAttrib()
821 elif fct == 'SCardStatus':
822 self._SCardStatus()
823 elif fct == 'SCardReconnect':
824 self._SCardReconnect()
825 elif fct == 'SCardDisconnect':
826 self._SCardDisconnect()
827 elif fct == 'SCardBeginTransaction':
828 self._SCardBeginTransaction()
829 elif fct == 'SCardEndTransaction':
830 self._SCardEndTransaction()
831 elif fct == 'SCardCancel':
832 self._SCardCancel()
833 else:
834 print("Unknown function:", fct)
835 except SpyExit:
836 return
837
838 try:
839 record = self.stats[fct]
840 except KeyError:
841 record = self.stats[fct] = StatRecord(fct)
842 record.executions.append(self.execution_time)
843
844 line = self.queue.get()
845
846
847 class PCSCdemultiplexer(object):
848 def __init__(self, logfile=None, color=True, diffable=False):
849 """ constructor """
850
851 # use default fifo file?
852 if logfile is None:
853 logfile = os.path.expanduser('~/pcsc-spy')
854
855 # create the FIFO file
856 try:
857 os.mkfifo(logfile)
858 except OSError:
859 print("fifo %s already present. Reusing it." % logfile)
860
861 self.sec = self.usec = 0
862
863 self.fifo = logfile
864 self.filedesc2 = open(self.fifo, 'r')
865
866 self.queues = dict()
867 self.color = color
868 self.diffable = diffable
869
870 def __del__(self):
871 """ cleanup """
872 from stat import S_ISFIFO
873 file_stat = os.stat(self.fifo)
874
875 # remove the log fifo only if it is a FIFO and not a log file
876 if S_ISFIFO(file_stat.st_mode):
877 os.unlink(self.fifo)
878
879 def loop(self):
880 """ loop reading logs """
881
882 # for statistics
883 stats = dict()
884
885 threads = dict()
886 indent = 0
887
888 # dispatch
889 line = self.filedesc2.readline().strip()
890
891 (thread, tail) = line.split('@')
892 res = tail.strip().split('|')
893 # check the first line format
894 if res[0] != ">":
895 print("Wrong format!")
896 print("First line Should start with a '>' but got:")
897 print(tail)
898 return
899 (direction, sec, usec, fct) = res
900
901 start_time = int(sec) + int(usec) / 1000000.
902
903 lastest_result = ""
904 while line != '':
905 previous_thread = thread
906 (thread, tail) = line.split('@')
907 if "<" in tail:
908 lastest_result = tail
909
910 # in case the thread changes
911 if previous_thread != thread:
912 # schedule the other thread so it has time to empty its
913 # queue
914 time.sleep(.001)
915
916 try:
917 queue = self.queues[thread]
918 except KeyError:
919 queue = self.queues[thread] = Queue()
920 stats[thread] = dict()
921 # new worker
922 spy = PCSCspy(queue, stats[thread], indent=indent,
923 color=self.color, diffable=self.diffable)
924 threads[thread] = Thread(target=spy.worker)
925 threads[thread].start()
926 indent += 1
927
928 queue.put(tail)
929
930 line = self.filedesc2.readline().strip()
931
932 # tell the workers to exit
933 for thread in self.queues.keys():
934 self.queues[thread].put('EXIT')
935
936 # wait for all the workers to finish
937 for thread in threads:
938 threads[thread].join()
939
940 (rv, sec, usec) = _parse_rv(lastest_result)
941 end_time = sec + usec / 1000000.
942 total_time = end_time - start_time
943
944 # compute some statistics
945 thread_n = 1
946 for thread in stats:
947 stat = stats[thread]
948 for fct in stat:
949 record = stat[fct]
950 record.occurrences = len(record.executions)
951 record.total_time = sum(record.executions)
952
953 records = [stat[fct] for fct in stat]
954
955 # display statistics sorted by total_time
956 print()
957 print("Thread %d/%d" % (thread_n, len(stats)))
958 print("Results sorted by total execution time")
959 print("total time: %f sec" % total_time)
960 for record in sorted(records, key=attrgetter('total_time'),
961 reverse=True):
962 print("%f sec (%3d calls) %5.2f%% %s" % (record.total_time,
963 record.occurrences, record.total_time / total_time * 100.,
964 record.name))
965
966 thread_n += 1
967
968
969 def main(logfile=None, color=True, diffable=False):
970 """ main """
971 spy = PCSCdemultiplexer(logfile, color, diffable)
972 spy.loop()
973
974
975 def signal_handler(sig, frame):
976 print('Ctrl-C, exiting.')
977 os.kill(os.getpid(), signal.SIGQUIT)
978
979
980 def print_usage():
981 print("Usage: pcsc-spy [-n|--nocolor] [-d|--diffable] [-h|--help] [-v|--version] [-t|--thread]")
982
983 if __name__ == "__main__":
984 import sys
985 import getopt
986
987 logfile = None
988 try:
989 opts, args = getopt.getopt(sys.argv[1:], "ndhvt", ["nocolor",
990 "diffable", "help", "version", "thread"])
991 except getopt.GetoptError:
992 print_usage()
993 sys.exit(1)
994
995 color = True
996 diffable = False
997 display_thread = False
998 for o, a in opts:
999 if o == "-n" or o == "--nocolor":
1000 color = False
1001 if o == "-d" or o == "--diffable":
1002 diffable = True
1003 if o == "-h" or o == "--help":
1004 print_usage()
1005 sys.exit(1)
1006 if o == "-v" or o == "--version":
1007 print("pcsc-spy version 1.2")
1008 print("Copyright (c) 2011-2024, Ludovic Rousseau <[email protected]>")
1009 print()
1010 sys.exit(1)
1011 if o == "-t" or o == "--thread":
1012 display_thread = True
1013
1014 if len(args) > 0:
1015 logfile = args[0]
1016
1017 signal.signal(signal.SIGINT, signal_handler)
1018 main(logfile, color=color, diffable=diffable)