aboutsummaryrefslogtreecommitdiff
path: root/pyecsca/sca/target/ISO7816.py
blob: afa75c51cd3e529ec7a85bdee384d778f8e6ba04 (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
from dataclasses import dataclass
from typing import Optional

from public import public

from .base import Target


@public
@dataclass
class CommandAPDU(object):  # pragma: no cover
    """A command APDU that can be sent to an ISO7816-4 target."""
    cls: int
    ins: int
    p1: int
    p2: int
    data: Optional[bytes]

    def __bytes__(self):
        if self.data is None or len(self.data) == 0:
            return bytes([self.cls, self.ins, self.p1, self.p2])
        elif len(self.data) <= 255:
            return bytes([self.cls, self.ins, self.p1, self.p2, len(self.data)]) + self.data
        else:
            data_len = len(self.data)
            return bytes([self.cls, self.ins, self.p1, self.p2, 0, data_len >> 8,
                          data_len & 0xff]) + self.data


@public
@dataclass
class ResponseAPDU(object):
    """A response APDU that can be received from an ISO7816-4 target."""
    data: Optional[bytes]
    sw: int


@public
class ISO7816Target(Target):
    """An ISO7816-4 target."""

    @property
    def atr(self) -> bytes:
        """The ATR (Answer To Reset) of the target."""
        raise NotImplementedError

    def select(self, aid: bytes) -> bool:
        """
        Select an applet with `aid`.

        :param aid: The AID of the applet to select.
        :return: Whether the selection was successful.
        """
        raise NotImplementedError

    def send_apdu(self, apdu: CommandAPDU) -> ResponseAPDU:
        """
        Send an APDU to the selected applet.

        :param apdu: The APDU to send.
        :return: The response.
        """
        raise NotImplementedError