blob: c6a68fcce3b1e05a9eda5b4035593cf2024244f2 [file] [log] [blame]
Sylvain Munaut76504e02010-12-07 00:24:32 +01001# -*- coding: utf-8 -*-
2
3""" pySim: Card programmation logic
4"""
5
6#
7# Copyright (C) 2009-2010 Sylvain Munaut <tnt@246tNt.com>
Harald Welte263fb082023-07-09 17:15:36 +02008# Copyright (C) 2011-2023 Harald Welte <laforge@gnumonks.org>
Alexander Chemeriseb6807d2017-07-18 17:04:38 +03009# Copyright (C) 2017 Alexander.Chemeris <Alexander.Chemeris@gmail.com>
Sylvain Munaut76504e02010-12-07 00:24:32 +010010#
11# This program is free software: you can redistribute it and/or modify
12# it under the terms of the GNU General Public License as published by
13# the Free Software Foundation, either version 2 of the License, or
14# (at your option) any later version.
15#
16# This program is distributed in the hope that it will be useful,
17# but WITHOUT ANY WARRANTY; without even the implied warranty of
18# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19# GNU General Public License for more details.
20#
21# You should have received a copy of the GNU General Public License
22# along with this program. If not, see <http://www.gnu.org/licenses/>.
23#
24
Vadim Yanitskiy03c67f72021-05-02 02:10:39 +020025from typing import Optional, Dict, Tuple
Harald Weltef8d2e2b2023-07-09 17:58:38 +020026from pySim.ts_102_221 import EF_DIR, EF_ICCID
27from pySim.ts_51_011 import DF_GSM
Harald Weltea3961292023-07-09 21:44:52 +020028from pySim.transport import LinkBase
Vadim Yanitskiy85302d62021-05-02 02:18:42 +020029import abc
Vadim Yanitskiy03c67f72021-05-02 02:10:39 +020030
Alexander Chemeriseb6807d2017-07-18 17:04:38 +030031from pySim.utils import *
Harald Weltea3961292023-07-09 21:44:52 +020032from pySim.commands import Path
Harald Welte263fb082023-07-09 17:15:36 +020033
34class CardBase:
35 """General base class for some kind of telecommunications card."""
Harald Weltea3961292023-07-09 21:44:52 +020036 def __init__(self, scc: LinkBase):
Harald Welte263fb082023-07-09 17:15:36 +020037 self._scc = scc
38 self._aids = []
39
Harald Weltea3961292023-07-09 21:44:52 +020040 def reset(self) -> Optional[Hexstr]:
Harald Welte263fb082023-07-09 17:15:36 +020041 rc = self._scc.reset_card()
42 if rc == 1:
43 return self._scc.get_atr()
44 else:
45 return None
46
Harald Weltea3961292023-07-09 21:44:52 +020047 def set_apdu_parameter(self, cla: Hexstr, sel_ctrl: Hexstr) -> None:
Harald Welte263fb082023-07-09 17:15:36 +020048 """Set apdu parameters (class byte and selection control bytes)"""
49 self._scc.cla_byte = cla
50 self._scc.sel_ctrl = sel_ctrl
51
Harald Weltea3961292023-07-09 21:44:52 +020052 def get_apdu_parameter(self) -> Tuple[Hexstr, Hexstr]:
Harald Welte263fb082023-07-09 17:15:36 +020053 """Get apdu parameters (class byte and selection control bytes)"""
54 return (self._scc.cla_byte, self._scc.sel_ctrl)
55
56 def erase(self):
57 print("warning: erasing is not supported for specified card type!")
58 return
59
Harald Weltea3961292023-07-09 21:44:52 +020060 def file_exists(self, fid: Path) -> bool:
Harald Welte263fb082023-07-09 17:15:36 +020061 res_arr = self._scc.try_select_path(fid)
62 for res in res_arr:
63 if res[1] != '9000':
64 return False
65 return True
66
Harald Weltea3961292023-07-09 21:44:52 +020067 def read_aids(self) -> List[Hexstr]:
Harald Welte263fb082023-07-09 17:15:36 +020068 # a non-UICC doesn't have any applications. Convenience helper to avoid
69 # callers having to do hasattr('read_aids') ahead of every call.
70 return []
71
Harald Weltea3961292023-07-09 21:44:52 +020072 def read_iccid(self) -> Tuple[Optional[Hexstr], SwHexstr]:
Harald Weltef8d2e2b2023-07-09 17:58:38 +020073 ef_iccid = EF_ICCID()
74 (res, sw) = self._scc.read_binary(ef_iccid.fid)
75 if sw == '9000':
76 return (dec_iccid(res), sw)
77 else:
78 return (None, sw)
79
Harald Welte263fb082023-07-09 17:15:36 +020080
81class SimCardBase(CardBase):
Harald Welte263fb082023-07-09 17:15:36 +020082 """Here we only add methods for commands specified in TS 51.011, without
83 any higher-layer processing."""
Harald Welte263fb082023-07-09 17:15:36 +020084 name = 'SIM'
85
Harald Welte172c28e2023-07-10 22:20:40 +020086 def __init__(self, scc: LinkBase):
87 super(SimCardBase, self).__init__(scc)
88 self._scc.cla_byte = "A0"
Harald Welte659d7c12023-07-10 22:25:58 +020089 self._scc.sel_ctrl = "0000"
Harald Welte172c28e2023-07-10 22:20:40 +020090
Harald Weltea3961292023-07-09 21:44:52 +020091 def probe(self) -> bool:
Harald Weltef8d2e2b2023-07-09 17:58:38 +020092 df_gsm = DF_GSM()
93 return self.file_exists(df_gsm.fid)
Harald Welte263fb082023-07-09 17:15:36 +020094
95
96class UiccCardBase(SimCardBase):
97 name = 'UICC'
98
Harald Welte775ab012023-07-10 22:23:07 +020099 def __init__(self, scc: LinkBase):
100 super(UiccCardBase, self).__init__(scc)
Harald Welte172c28e2023-07-10 22:20:40 +0200101 self._scc.cla_byte = "00"
Harald Welte659d7c12023-07-10 22:25:58 +0200102 self._scc.sel_ctrl = "0004" # request an FCP
Harald Welte172c28e2023-07-10 22:20:40 +0200103 # See also: ETSI TS 102 221, Table 9.3
Harald Welte263fb082023-07-09 17:15:36 +0200104 self._adm_chv_num = 0xA0
105
Harald Weltea3961292023-07-09 21:44:52 +0200106 def probe(self) -> bool:
Harald Weltef8d2e2b2023-07-09 17:58:38 +0200107 # EF.DIR is a mandatory EF on all ICCIDs; however it *may* also exist on a TS 51.011 SIM
108 ef_dir = EF_DIR()
109 return self.file_exists(ef_dir.fid)
Harald Welte263fb082023-07-09 17:15:36 +0200110
Harald Weltea3961292023-07-09 21:44:52 +0200111 def read_aids(self) -> List[Hexstr]:
Harald Weltec91085e2022-02-10 18:05:45 +0100112 """Fetch all the AIDs present on UICC"""
113 self._aids = []
114 try:
Harald Weltef8d2e2b2023-07-09 17:58:38 +0200115 ef_dir = EF_DIR()
Harald Weltec91085e2022-02-10 18:05:45 +0100116 # Find out how many records the EF.DIR has
117 # and store all the AIDs in the UICC
Harald Weltef8d2e2b2023-07-09 17:58:38 +0200118 rec_cnt = self._scc.record_count(ef_dir.fid)
Harald Weltec91085e2022-02-10 18:05:45 +0100119 for i in range(0, rec_cnt):
Harald Weltef8d2e2b2023-07-09 17:58:38 +0200120 rec = self._scc.read_record(ef_dir.fid, i + 1)
Harald Weltec91085e2022-02-10 18:05:45 +0100121 if (rec[0][0:2], rec[0][4:6]) == ('61', '4f') and len(rec[0]) > 12 \
122 and rec[0][8:8 + int(rec[0][6:8], 16) * 2] not in self._aids:
123 self._aids.append(rec[0][8:8 + int(rec[0][6:8], 16) * 2])
124 except Exception as e:
125 print("Can't read AIDs from SIM -- %s" % (str(e),))
126 self._aids = []
127 return self._aids
Supreeth Herlee4e98312020-03-18 11:33:14 +0100128
Harald Weltec91085e2022-02-10 18:05:45 +0100129 @staticmethod
Harald Weltea3961292023-07-09 21:44:52 +0200130 def _get_aid(adf="usim") -> Optional[Hexstr]:
Harald Weltec91085e2022-02-10 18:05:45 +0100131 aid_map = {}
132 # First (known) halves of the U/ISIM AID
133 aid_map["usim"] = "a0000000871002"
134 aid_map["isim"] = "a0000000871004"
135 adf = adf.lower()
136 if adf in aid_map:
137 return aid_map[adf]
138 return None
Philipp Maier46c61542021-11-16 16:36:50 +0100139
Harald Weltea3961292023-07-09 21:44:52 +0200140 def _complete_aid(self, aid: Hexstr) -> Optional[Hexstr]:
Harald Weltec91085e2022-02-10 18:05:45 +0100141 """find the complete version of an ADF.U/ISIM AID"""
142 # Find full AID by partial AID:
143 if is_hex(aid):
144 for aid_known in self._aids:
145 if len(aid_known) >= len(aid) and aid == aid_known[0:len(aid)]:
146 return aid_known
147 return None
Philipp Maier46c61542021-11-16 16:36:50 +0100148
Harald Weltea3961292023-07-09 21:44:52 +0200149 def adf_present(self, adf: str = "usim") -> bool:
Philipp Maier84902402023-02-10 18:23:36 +0100150 """Check if the AID of the specified ADF is present in EF.DIR (call read_aids before use)"""
151 aid = self._get_aid(adf)
152 if aid:
153 aid_full = self._complete_aid(aid)
154 if aid_full:
155 return True
156 return False
157
Harald Weltea3961292023-07-09 21:44:52 +0200158 def select_adf_by_aid(self, adf: str = "usim") -> Tuple[Optional[Hexstr], Optional[SwHexstr]]:
Harald Weltec91085e2022-02-10 18:05:45 +0100159 """Select ADF.U/ISIM in the Card using its full AID"""
160 if is_hex(adf):
161 aid = adf
162 else:
163 aid = self._get_aid(adf)
164 if aid:
165 aid_full = self._complete_aid(aid)
166 if aid_full:
167 return self._scc.select_adf(aid_full)
168 else:
169 # If we cannot get the full AID, try with short AID
170 return self._scc.select_adf(aid)
171 return (None, None)
Supreeth Herlef9f3e5e2020-03-22 08:04:59 +0100172
Harald Weltea3961292023-07-09 21:44:52 +0200173def card_detect(scc: LinkBase) -> Optional[CardBase]:
Harald Weltef8d2e2b2023-07-09 17:58:38 +0200174 # UICC always has higher preference, as a UICC might also contain a SIM application
175 uicc = UiccCardBase(scc)
176 if uicc.probe():
177 return uicc
Philipp Maierbda52832022-06-14 16:18:12 +0200178
Harald Weltef8d2e2b2023-07-09 17:58:38 +0200179 # this is for detecting a real, classic TS 11.11 SIM card without any UICC support
180 sim = SimCardBase(scc)
181 if sim.probe():
182 return sim
Harald Welteca673942020-06-03 15:19:40 +0200183
Harald Weltef8d2e2b2023-07-09 17:58:38 +0200184 return None