2007-06-16 06:56:57 +00:00
|
|
|
import smartcard
|
2010-03-06 20:42:16 +00:00
|
|
|
import TLV_utils, crypto_utils, utils, binascii, fnmatch, re, time
|
2006-05-18 15:45:07 +00:00
|
|
|
from utils import C_APDU, R_APDU
|
2005-09-29 03:39:14 +00:00
|
|
|
|
|
|
|
DEBUG = True
|
2005-09-29 19:05:55 +00:00
|
|
|
#DEBUG = False
|
2005-09-29 03:39:14 +00:00
|
|
|
|
2007-02-13 00:32:04 +00:00
|
|
|
|
2007-03-18 23:38:24 +00:00
|
|
|
_GENERIC_NAME = "Generic"
|
2005-09-29 03:39:14 +00:00
|
|
|
class Card:
|
2007-03-18 23:38:24 +00:00
|
|
|
DRIVER_NAME = [_GENERIC_NAME]
|
2010-10-15 14:37:26 +00:00
|
|
|
COMMAND_GET_RESPONSE = None
|
2010-10-15 06:20:22 +00:00
|
|
|
|
|
|
|
## Constants for check_sw()
|
|
|
|
PURPOSE_SUCCESS = 1 # Command executed successful
|
|
|
|
PURPOSE_GET_RESPONSE = 2 # Command executed successful but needs GET RESPONSE with correct length
|
|
|
|
PURPOSE_SM_OK = 3 # Command not executed successful or with warnings, but response still contains SM objects
|
|
|
|
PURPOSE_RETRY = 4 # Command would be executed successful but needs retry with correct length
|
|
|
|
|
2007-02-13 00:32:04 +00:00
|
|
|
## Map for check_sw()
|
2010-10-15 06:20:22 +00:00
|
|
|
STATUS_MAP = {}
|
|
|
|
|
2006-05-19 00:19:08 +00:00
|
|
|
## Note: an item in this list must be a tuple of (atr, mask) where atr is a binary
|
|
|
|
## string and mask a binary mask. Alternatively mask may be None, then ATR must be a regex
|
|
|
|
## to match on the ATRs hexlify representation
|
2005-09-29 03:39:14 +00:00
|
|
|
ATRS = []
|
2007-05-30 16:47:43 +00:00
|
|
|
## Note: A list of _not_ supported ATRs, overriding any possible match in ATRS. Matching
|
|
|
|
## is done as for ATRS.
|
|
|
|
STOP_ATRS = []
|
2010-10-15 06:20:22 +00:00
|
|
|
|
|
|
|
## Note: a key in this dictionary may either be a one- or two-byte string containing
|
|
|
|
## a binary status word, or a two or four-byte string containing a hexadecimal
|
2005-10-03 07:02:49 +00:00
|
|
|
## status word, possibly with ? characters marking variable nibbles.
|
2010-10-15 06:20:22 +00:00
|
|
|
## Hexadecimal characters MUST be in uppercase. The values that two- or four-byte
|
2005-10-03 07:02:49 +00:00
|
|
|
## strings map to may be either format strings, that can make use of the
|
|
|
|
## keyword substitutions for SW1 and SW2 or a callable accepting two arguments
|
|
|
|
## (SW1, SW2) that returns a string.
|
|
|
|
STATUS_WORDS = {
|
2005-09-29 17:16:27 +00:00
|
|
|
}
|
2006-06-16 23:14:14 +00:00
|
|
|
## For the format of this dictionary of dictionaries see TLV_utils.tags
|
|
|
|
TLV_OBJECTS = {}
|
2007-02-13 13:23:29 +00:00
|
|
|
DEFAULT_CONTEXT = None
|
2007-01-14 13:46:30 +00:00
|
|
|
|
|
|
|
## Format: "AID (binary)": ("name", [optional: description, {more information}])
|
|
|
|
APPLICATIONS = {
|
|
|
|
}
|
2007-01-16 17:14:37 +00:00
|
|
|
|
|
|
|
## Format: "RID (binary)": ("vendor name", [optional: {more information}])
|
|
|
|
VENDORS = {
|
|
|
|
}
|
2007-02-13 00:32:04 +00:00
|
|
|
|
2007-01-14 14:25:57 +00:00
|
|
|
def _decode_df_name(self, value):
|
|
|
|
result = " " + utils.hexdump(value, short=True)
|
2007-01-16 17:14:37 +00:00
|
|
|
info = None
|
|
|
|
|
2007-01-14 14:25:57 +00:00
|
|
|
if self.APPLICATIONS.has_key(value):
|
|
|
|
info = self.APPLICATIONS[value]
|
2007-01-16 17:14:37 +00:00
|
|
|
else:
|
|
|
|
for aid, i in self.APPLICATIONS.items():
|
|
|
|
if not len(i) > 2 or not i[2].has_key("significant_length"):
|
|
|
|
continue
|
|
|
|
if aid[ :i[2]["significant_length"] ] == value[ :i[2]["significant_length"] ]:
|
|
|
|
info = i
|
|
|
|
break
|
|
|
|
|
|
|
|
result_array = []
|
|
|
|
if info is not None:
|
2007-01-17 09:14:35 +00:00
|
|
|
if info[0] is not None:
|
|
|
|
result_array.append( ("Name", info[0]) )
|
2007-01-16 17:14:37 +00:00
|
|
|
|
|
|
|
if len(info) > 1 and not info[1] is None:
|
|
|
|
result_array.append( ("Description", info[1] ) )
|
|
|
|
|
|
|
|
if self.VENDORS.has_key(value[:5]):
|
|
|
|
result_array.append( ("Vendor", self.VENDORS[ value[:5] ][0]) )
|
|
|
|
|
|
|
|
if len(result_array) > 0:
|
|
|
|
max_len = max( [len(a) for a,b in result_array] + [11] ) + 1
|
|
|
|
result = result + "\n" + "\n".join( [("%%-%is %%s" % max_len) % (a+":",b) for a,b in result_array] )
|
2007-01-14 14:25:57 +00:00
|
|
|
return result
|
|
|
|
|
|
|
|
def decode_df_name(value):
|
|
|
|
# Static method for when there is no object reference
|
|
|
|
return Card._decode_df_name(value)
|
|
|
|
|
2010-02-25 15:43:54 +00:00
|
|
|
def __init__(self, reader):
|
|
|
|
self.reader = reader
|
2005-09-29 03:39:14 +00:00
|
|
|
|
|
|
|
self._i = 0
|
2005-09-29 17:16:27 +00:00
|
|
|
self.last_apdu = None
|
2006-05-18 20:21:51 +00:00
|
|
|
self.last_result = None
|
2010-03-06 20:42:16 +00:00
|
|
|
self._last_start = None
|
|
|
|
self.last_delta = None
|
2005-09-29 03:39:14 +00:00
|
|
|
|
2006-07-21 18:22:40 +00:00
|
|
|
def cmd_parsetlv(self, start = None, end = None):
|
|
|
|
"Decode the TLV data in the last response, start and end are optional"
|
|
|
|
lastlen = len(self.last_result.data)
|
|
|
|
if start is not None:
|
|
|
|
start = (lastlen + (int(start,0) % lastlen) ) % lastlen
|
|
|
|
else:
|
|
|
|
start = 0
|
|
|
|
if end is not None:
|
|
|
|
end = (lastlen + (int(end,0) % lastlen) ) % lastlen
|
|
|
|
else:
|
|
|
|
end = lastlen
|
2007-02-13 13:23:29 +00:00
|
|
|
print TLV_utils.decode(self.last_result.data[start:end], tags=self.TLV_OBJECTS, context = self.DEFAULT_CONTEXT)
|
2006-05-22 01:04:32 +00:00
|
|
|
|
2007-01-14 13:46:30 +00:00
|
|
|
_SHOW_APPLICATIONS_FORMAT_STRING = "%(aid)-50s %(name)-20s %(description)-30s"
|
|
|
|
def cmd_show_applications(self):
|
|
|
|
"Show the list of known (by the shell) applications"
|
|
|
|
print self._SHOW_APPLICATIONS_FORMAT_STRING % {"aid": "AID", "name": "Name", "description": "Description"}
|
|
|
|
foo = self.APPLICATIONS.items()
|
|
|
|
foo.sort()
|
|
|
|
for aid, info in foo:
|
|
|
|
print self._SHOW_APPLICATIONS_FORMAT_STRING % {
|
|
|
|
"aid": utils.hexdump(aid, short=True),
|
|
|
|
"name": info[0],
|
|
|
|
"description": len(info) > 1 and info[1] or ""
|
|
|
|
}
|
|
|
|
|
2010-10-15 06:20:22 +00:00
|
|
|
def cmd_reset(self):
|
|
|
|
"""Reset the card."""
|
|
|
|
# FIXME
|
|
|
|
raise NotImplementedException
|
|
|
|
|
2005-09-29 21:37:28 +00:00
|
|
|
COMMANDS = {
|
2005-10-09 02:06:32 +00:00
|
|
|
"reset": cmd_reset,
|
2006-05-22 01:04:32 +00:00
|
|
|
"parse_tlv": cmd_parsetlv,
|
2007-01-14 13:46:30 +00:00
|
|
|
"show_applications": cmd_show_applications,
|
2005-09-29 21:37:28 +00:00
|
|
|
}
|
2007-06-16 06:56:57 +00:00
|
|
|
|
2005-09-29 17:16:27 +00:00
|
|
|
def _real_send(self, apdu):
|
2006-05-18 15:45:07 +00:00
|
|
|
apdu_binary = apdu.render()
|
|
|
|
|
2005-09-29 17:16:27 +00:00
|
|
|
if DEBUG:
|
2006-05-18 15:45:07 +00:00
|
|
|
print ">> " + utils.hexdump(apdu_binary, indent = 3)
|
|
|
|
|
2010-02-25 15:43:54 +00:00
|
|
|
result_binary = self.reader.transceive(apdu_binary)
|
2010-10-15 14:50:01 +00:00
|
|
|
result = apdu.RESPONSE_CLASS(result_binary)
|
2006-05-18 15:45:07 +00:00
|
|
|
|
2005-09-29 17:16:27 +00:00
|
|
|
self.last_apdu = apdu
|
2006-05-18 15:45:07 +00:00
|
|
|
|
2005-09-29 17:16:27 +00:00
|
|
|
if DEBUG:
|
2006-05-18 15:45:07 +00:00
|
|
|
print "<< " + utils.hexdump(result_binary, indent = 3)
|
2005-09-29 17:16:27 +00:00
|
|
|
return result
|
|
|
|
|
2006-05-26 04:51:06 +00:00
|
|
|
def _send_with_retry(self, apdu):
|
|
|
|
result = self._real_send(apdu)
|
|
|
|
|
2010-10-15 15:58:54 +00:00
|
|
|
while self.check_sw(result.sw, self.PURPOSE_GET_RESPONSE):
|
2006-05-26 04:51:06 +00:00
|
|
|
## Need to call GetResponse
|
2010-10-15 15:25:05 +00:00
|
|
|
gr_apdu = self.COMMAND_GET_RESPONSE
|
2010-10-15 15:58:54 +00:00
|
|
|
tmp = self._real_send(gr_apdu)
|
|
|
|
|
|
|
|
if not callable(result.append):
|
|
|
|
result = tmp
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
result = result.append(tmp)
|
2006-05-26 04:51:06 +00:00
|
|
|
|
|
|
|
return result
|
|
|
|
|
2005-09-29 03:39:14 +00:00
|
|
|
def send_apdu(self, apdu):
|
|
|
|
if DEBUG:
|
|
|
|
print "%s\nBeginning transaction %i" % ('-'*80, self._i)
|
|
|
|
|
2010-03-06 20:42:16 +00:00
|
|
|
self.last_delta = None
|
|
|
|
self._last_start = time.time()
|
|
|
|
|
2005-09-29 03:39:14 +00:00
|
|
|
if hasattr(self, "before_send"):
|
|
|
|
apdu = self.before_send(apdu)
|
|
|
|
|
2006-05-26 04:51:06 +00:00
|
|
|
result = self._send_with_retry(apdu)
|
2005-09-29 03:39:14 +00:00
|
|
|
|
2006-11-21 00:51:32 +00:00
|
|
|
if hasattr(self, "after_send"):
|
|
|
|
result = self.after_send(result)
|
|
|
|
|
2010-03-06 20:42:16 +00:00
|
|
|
if self._last_start is not None:
|
|
|
|
self.last_delta = time.time() - self._last_start
|
|
|
|
self._last_start = None
|
|
|
|
|
2005-09-29 03:39:14 +00:00
|
|
|
if DEBUG:
|
|
|
|
print "Ending transaction %i\n%s\n" % (self._i, '-'*80)
|
|
|
|
self._i = self._i + 1
|
2005-09-29 17:16:27 +00:00
|
|
|
|
2006-05-18 20:21:51 +00:00
|
|
|
self.last_result = result
|
2005-09-29 03:39:14 +00:00
|
|
|
return result
|
|
|
|
|
2007-02-13 00:32:04 +00:00
|
|
|
def check_sw(self, sw, purpose = None):
|
|
|
|
if purpose is None: purpose = Card.PURPOSE_SUCCESS
|
|
|
|
return self.match_statusword(self.STATUS_MAP[purpose], sw)
|
|
|
|
|
2010-02-25 15:43:54 +00:00
|
|
|
def _get_atr(reader):
|
|
|
|
return reader.get_ATR()
|
2007-06-16 07:25:42 +00:00
|
|
|
_get_atr = staticmethod(_get_atr)
|
|
|
|
|
|
|
|
def get_atr(self):
|
2010-02-25 15:43:54 +00:00
|
|
|
return self._get_atr(self.reader)
|
2007-06-16 07:25:42 +00:00
|
|
|
|
2010-02-25 15:43:54 +00:00
|
|
|
def can_handle(cls, reader):
|
2007-06-16 07:25:42 +00:00
|
|
|
"""Determine whether this class can handle a given card/connection object."""
|
2010-02-25 15:43:54 +00:00
|
|
|
ATR = cls._get_atr(reader)
|
2007-05-30 16:47:43 +00:00
|
|
|
def match_list(atr, list):
|
|
|
|
for (knownatr, mask) in list:
|
|
|
|
if mask is None:
|
2007-06-09 19:31:05 +00:00
|
|
|
if re.match(knownatr, binascii.hexlify(atr), re.I):
|
2007-05-30 16:47:43 +00:00
|
|
|
return True
|
|
|
|
else:
|
|
|
|
if len(knownatr) != len(atr):
|
|
|
|
continue
|
|
|
|
if crypto_utils.andstring(knownatr, mask) == crypto_utils.andstring(atr, mask):
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
if not match_list(ATR, cls.STOP_ATRS) and match_list(ATR, cls.ATRS):
|
|
|
|
return True
|
2005-09-29 03:39:14 +00:00
|
|
|
return False
|
2007-05-30 16:47:43 +00:00
|
|
|
|
2005-09-29 03:39:14 +00:00
|
|
|
can_handle = classmethod(can_handle)
|
|
|
|
|
|
|
|
def get_prompt(self):
|
2007-03-18 23:38:24 +00:00
|
|
|
return "(%s)" % self.get_driver_name()
|
2005-09-29 17:16:27 +00:00
|
|
|
|
2007-02-13 00:32:04 +00:00
|
|
|
def match_statusword(swlist, sw):
|
|
|
|
"""Try to find sw in swlist.
|
|
|
|
swlist must be a list of either binary statuswords (two bytes), hexadecimal statuswords (four bytes) or fnmatch patterns on a hexadecimal statusword.
|
|
|
|
Returns: The element that matched (either two bytes, four bytes or the fnmatch pattern)."""
|
|
|
|
if sw in swlist:
|
|
|
|
return sw
|
|
|
|
sw = binascii.hexlify(sw).upper()
|
|
|
|
if sw in swlist:
|
|
|
|
return sw
|
|
|
|
for value in swlist:
|
|
|
|
if fnmatch.fnmatch(sw, value):
|
|
|
|
return value
|
|
|
|
return None
|
|
|
|
match_statusword = staticmethod(match_statusword)
|
|
|
|
|
2007-03-18 23:38:24 +00:00
|
|
|
def get_driver_name(self):
|
|
|
|
if len(self.DRIVER_NAME) > 1:
|
|
|
|
names = [e for e in self.DRIVER_NAME if e != _GENERIC_NAME]
|
|
|
|
else:
|
|
|
|
names = self.DRIVER_NAME
|
|
|
|
return ", ".join(names)
|
|
|
|
|
2006-05-22 03:26:13 +00:00
|
|
|
def close_card(self):
|
|
|
|
"Disconnect from a card"
|
2010-02-25 15:43:54 +00:00
|
|
|
self.reader.disconnect()
|
|
|
|
del self.reader
|
2007-06-16 06:56:57 +00:00
|
|
|
|