aboutsummaryrefslogtreecommitdiffhomepage
path: root/pyecsca/sca/target/leia.py
blob: 5bd19afece3b12e89b30ef3f3d14df6b8b3e886d (plain) (blame)
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
"""Provides a smartcard target communicating via the LEIA board in solo mode."""

from typing import Optional

from smartleia import LEIA, create_APDU_from_bytes, T

from pyecsca.sca.target.ISO7816 import (
    ISO7816Target,
    CommandAPDU,
    ResponseAPDU,
    ISO7816,
    CardProtocol,
    CardConnectionException,
)


class LEIATarget(ISO7816Target):  # pragma: no cover
    """Smartcard target communicating via LEIA in solo mode."""

    def __init__(self, leia: LEIA):
        self.leia = leia

    @property
    def atr(self) -> bytes:
        return self.leia.get_ATR().normalized()

    @property
    def card_present(self) -> bool:
        return self.leia.is_card_inserted()

    def select(self, aid: bytes) -> bool:
        apdu = CommandAPDU(0x00, 0xA4, 0x04, 0x00, aid)
        resp = self.send_apdu(apdu)
        return resp.sw == ISO7816.SW_NO_ERROR

    def send_apdu(self, apdu: CommandAPDU) -> ResponseAPDU:
        leia_apdu = create_APDU_from_bytes(bytes(apdu))
        resp = self.leia.send_APDU(leia_apdu)
        return ResponseAPDU(bytes(resp.data), resp.sw1 << 8 | resp.sw2)

    def connect(self, protocol: Optional[CardProtocol] = None):
        proto = T.AUTO
        if protocol == CardProtocol.T0:
            proto = T.T0
        elif protocol == CardProtocol.T1:
            proto = T.T1
        try:
            self.leia.configure_smartcard(protocol_to_use=proto)
        except:  # noqa
            raise CardConnectionException()

    def disconnect(self):
        pass