aboutsummaryrefslogtreecommitdiffstats
path: root/cards/generic_card.py
blob: 0010798b0a2d701f9b666a6c708e932df91e4633 (plain)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import crypto_utils, utils, pycsc, binascii, fnmatch
from utils import APDU

DEBUG = True
#DEBUG = False

class Card:
    APDU_GET_RESPONSE = APDU("\x00\xC0\x00\x00")
    APDU_VERIFY_PIN = APDU("\x00\x20\x00\x00")
    SW_OK = '\x90\x00'
    ATRS = []
    DRIVER_NAME = "Generic"
    ## Note: a key in this dictionary may either be a two-byte string containing
    ## a binary status word, or a four-byte string containing a hexadecimal
    ## status word, possibly with ? characters marking variable nibbles. 
    ## Hexadecimal characters MUST be in uppercase. The values that four-byte
    ## 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 = { 
        SW_OK: "Normal execution",
        '61??': "%(SW2)i (0x%(SW2)02x) bytes of response data can be retrieved with GetResponse.",
        '6700': "Wrong length",
        '6C??': "Bad value for LE, 0x%(SW2)02x is the correct value.",
        '63C?': lambda SW1,SW2: "The counter has reached the value '%i'" % (SW2%16)
    }

    def __init__(self, card = None, reader = None):
        if card is None:
            if reader is None:
                self.card = pycsc.pycsc(protocol = pycsc.SCARD_PROTOCOL_ANY)
            else:
                self.card = pycsc.pycsc(protocol = pycsc.SCARD_PROTOCOL_ANY, reader = reader)
        else:
            self.card = card
        
        self._i = 0
        self.last_apdu = None
        self.last_sw = None
        self.sw_changed = False
    
    def verify_pin(self, pin_number, pin_value):
        apdu = APDU(self.APDU_VERIFY_PIN, P2 = pin_number,
            content = pin_value)
        result = self.send_apdu(apdu)
        return result == self.SW_OK
    
    def cmd_verify(self, pin_number, pin_value):
        """Verify a PIN."""
        pin_number = int(pin_number, 0)
        pin_value = binascii.a2b_hex("".join(pin_value.split()))
        self.verify_pin(pin_number, pin_value)
    
    def cmd_reset(self):
        """Reset the card."""
        self.card.reconnect(init=pycsc.SCARD_RESET_CARD)
    
    COMMANDS = {
        "reset": cmd_reset,
        "verify": cmd_verify
    }

    def _check_apdu(apdu):
        return True
        if len(apdu) < 4 or ((len(apdu) > 5) and len(apdu) != (ord(apdu[4])+5)):
            print "Cowardly refusing to send invalid APDU:\n  ", utils.hexdump(apdu, indent=2)
            return False
        return True
    _check_apdu = staticmethod(_check_apdu)
    
    def _real_send(self, apdu):
        if not Card._check_apdu(apdu):
            raise Exception, "Invalid APDU"
        if DEBUG:
            print ">> " + utils.hexdump(apdu, indent = 3)
        result = self.card.transmit(apdu)
        self.last_apdu = apdu
        self.last_sw = result[-2:]
        self.sw_changed = True
        if DEBUG:
            print "<< " + utils.hexdump(result, indent = 3)
        return result
    
    def send_apdu(self, apdu):
        if isinstance(apdu, APDU):
            apdu = apdu.get_string(protocol = self.get_protocol()) ## FIXME
        if not Card._check_apdu(apdu):
            raise Exception, "Invalid APDU"
        if DEBUG:
            print "%s\nBeginning transaction %i" % ('-'*80, self._i)
        
        if hasattr(self, "before_send"):
            apdu = self.before_send(apdu)
        
        result = self._real_send(apdu)
        
        if len(result) == 2 and result[0] == '\x61':
            ## Need to call GetResponse
            gr_apdu = APDU(self.APDU_GET_RESPONSE, le = result[1]).get_string(protocol=0)
            result = self._real_send(gr_apdu)
        
        if DEBUG:
            print "Ending transaction %i\n%s\n" % (self._i, '-'*80)
        self._i = self._i + 1
        
        return result
    
    def can_handle(cls, card):
        """Determine whether this class can handle a given pycsc object."""
        ATR = card.status().get("ATR","")
        for (knownatr, mask) in cls.ATRS:
            if len(knownatr) != len(ATR):
                continue
            if crypto_utils.andstring(knownatr, mask) == crypto_utils.andstring(ATR, mask):
                return True
        return False
    can_handle = classmethod(can_handle)
    
    def get_prompt(self):
        return "(%s)" % self.DRIVER_NAME
    
    def decode_statusword(self):
        if self.last_sw is None:
            return "No command executed so far"
        else:
            retval = None
            
            desc = self.STATUS_WORDS.get(self.last_sw)
            if desc is not None:
                retval = desc
            else:
                target = binascii.b2a_hex(self.last_sw).upper()
                for (key, value) in self.STATUS_WORDS.items():
                    if fnmatch.fnmatch(target, key):
                        if isinstance(value, str):
                            retval = value % { "SW1": ord(self.last_sw[0]), 
                                "SW2": ord(self.last_sw[1]) }
                            break
                            
                        elif callable(value):
                            retval = value( ord(self.last_sw[0]),
                                ord(self.last_sw[1]) )
                            break
        
        if retval is None:
            return "%s: Unknown SW" % binascii.b2a_hex(self.last_sw)
        else:
            return "%s: %s" % (binascii.b2a_hex(self.last_sw), retval)
    
    def get_protocol(self):
        return ((self.card.status()["Protocol"] == pycsc.SCARD_PROTOCOL_T0) and (0,) or (1,))[0]