Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 1 | # coding=utf-8 |
| 2 | """Utilities / Functions related to ETSI TS 102 221, the core UICC spec. |
| 3 | |
| 4 | (C) 2021 by Harald Welte <laforge@osmocom.org> |
| 5 | |
| 6 | This program is free software: you can redistribute it and/or modify |
| 7 | it under the terms of the GNU General Public License as published by |
| 8 | the Free Software Foundation, either version 2 of the License, or |
| 9 | (at your option) any later version. |
| 10 | |
| 11 | This program is distributed in the hope that it will be useful, |
| 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 | GNU General Public License for more details. |
| 15 | |
| 16 | You should have received a copy of the GNU General Public License |
| 17 | along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 18 | """ |
| 19 | |
Harald Welte | 8f892fb | 2021-06-05 10:12:43 +0200 | [diff] [blame] | 20 | from construct import * |
Harald Welte | 747a978 | 2022-02-13 17:52:28 +0100 | [diff] [blame] | 21 | from construct import Optional as COptional |
Harald Welte | 8f892fb | 2021-06-05 10:12:43 +0200 | [diff] [blame] | 22 | from pySim.construct import * |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 23 | from pySim.utils import * |
| 24 | from pySim.filesystem import * |
Harald Welte | 181c7c5 | 2022-02-10 14:18:32 +0100 | [diff] [blame] | 25 | from pySim.tlv import * |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 26 | from bidict import bidict |
Philipp Maier | a028c7d | 2021-11-08 16:12:03 +0100 | [diff] [blame] | 27 | from pySim.profile import CardProfile |
| 28 | from pySim.profile import match_uicc |
| 29 | from pySim.profile import match_sim |
Harald Welte | 181c7c5 | 2022-02-10 14:18:32 +0100 | [diff] [blame] | 30 | import pySim.iso7816_4 as iso7816_4 |
Philipp Maier | a028c7d | 2021-11-08 16:12:03 +0100 | [diff] [blame] | 31 | |
| 32 | # A UICC will usually also support 2G functionality. If this is the case, we |
| 33 | # need to add DF_GSM and DF_TELECOM along with the UICC related files |
Harald Welte | 323a350 | 2023-07-11 17:26:39 +0200 | [diff] [blame] | 34 | from pySim.ts_51_011 import DF_GSM, DF_TELECOM, AddonSIM |
| 35 | from pySim.gsm_r import AddonGSMR |
| 36 | from pySim.cdma_ruim import AddonRUIM |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 37 | |
| 38 | ts_102_22x_cmdset = CardCommandSet('TS 102 22x', [ |
| 39 | # TS 102 221 Section 10.1.2 Table 10.5 "Coding of Instruction Byte" |
| 40 | CardCommand('SELECT', 0xA4, ['0X', '4X', '6X']), |
| 41 | CardCommand('STATUS', 0xF2, ['8X', 'CX', 'EX']), |
| 42 | CardCommand('READ BINARY', 0xB0, ['0X', '4X', '6X']), |
| 43 | CardCommand('UPDATE BINARY', 0xD6, ['0X', '4X', '6X']), |
| 44 | CardCommand('READ RECORD', 0xB2, ['0X', '4X', '6X']), |
| 45 | CardCommand('UPDATE RECORD', 0xDC, ['0X', '4X', '6X']), |
| 46 | CardCommand('SEARCH RECORD', 0xA2, ['0X', '4X', '6X']), |
| 47 | CardCommand('INCREASE', 0x32, ['8X', 'CX', 'EX']), |
| 48 | CardCommand('RETRIEVE DATA', 0xCB, ['8X', 'CX', 'EX']), |
| 49 | CardCommand('SET DATA', 0xDB, ['8X', 'CX', 'EX']), |
| 50 | CardCommand('VERIFY PIN', 0x20, ['0X', '4X', '6X']), |
| 51 | CardCommand('CHANGE PIN', 0x24, ['0X', '4X', '6X']), |
| 52 | CardCommand('DISABLE PIN', 0x26, ['0X', '4X', '6X']), |
| 53 | CardCommand('ENABLE PIN', 0x28, ['0X', '4X', '6X']), |
| 54 | CardCommand('UNBLOCK PIN', 0x2C, ['0X', '4X', '6X']), |
| 55 | CardCommand('DEACTIVATE FILE', 0x04, ['0X', '4X', '6X']), |
| 56 | CardCommand('ACTIVATE FILE', 0x44, ['0X', '4X', '6X']), |
| 57 | CardCommand('AUTHENTICATE', 0x88, ['0X', '4X', '6X']), |
| 58 | CardCommand('AUTHENTICATE', 0x89, ['0X', '4X', '6X']), |
| 59 | CardCommand('GET CHALLENGE', 0x84, ['0X', '4X', '6X']), |
| 60 | CardCommand('TERMINAL CAPABILITY', 0xAA, ['8X', 'CX', 'EX']), |
| 61 | CardCommand('TERMINAL PROFILE', 0x10, ['80']), |
| 62 | CardCommand('ENVELOPE', 0xC2, ['80']), |
| 63 | CardCommand('FETCH', 0x12, ['80']), |
| 64 | CardCommand('TERMINAL RESPONSE', 0x14, ['80']), |
| 65 | CardCommand('MANAGE CHANNEL', 0x70, ['0X', '4X', '6X']), |
| 66 | CardCommand('MANAGE SECURE CHANNEL', 0x73, ['0X', '4X', '6X']), |
| 67 | CardCommand('TRANSACT DATA', 0x75, ['0X', '4X', '6X']), |
| 68 | CardCommand('SUSPEND UICC', 0x76, ['80']), |
| 69 | CardCommand('GET IDENTITY', 0x78, ['8X', 'CX', 'EX']), |
| 70 | CardCommand('EXCHANGE CAPABILITIES', 0x7A, ['80']), |
| 71 | CardCommand('GET RESPONSE', 0xC0, ['0X', '4X', '6X']), |
| 72 | # TS 102 222 Section 6.1 Table 1 "Coding of the commands" |
| 73 | CardCommand('CREATE FILE', 0xE0, ['0X', '4X']), |
| 74 | CardCommand('DELETE FILE', 0xE4, ['0X', '4X']), |
| 75 | CardCommand('DEACTIVATE FILE', 0x04, ['0X', '4X']), |
| 76 | CardCommand('ACTIVATE FILE', 0x44, ['0X', '4X']), |
| 77 | CardCommand('TERMINATE DF', 0xE6, ['0X', '4X']), |
| 78 | CardCommand('TERMINATE EF', 0xE8, ['0X', '4X']), |
| 79 | CardCommand('TERMINATE CARD USAGE', 0xFE, ['0X', '4X']), |
| 80 | CardCommand('RESIZE FILE', 0xD4, ['8X', 'CX']), |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 81 | ]) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 82 | |
Harald Welte | c8c3327 | 2022-02-11 14:45:23 +0100 | [diff] [blame] | 83 | # ETSI TS 102 221 11.1.1.4.2 |
| 84 | class FileSize(BER_TLV_IE, tag=0x80): |
Philipp Maier | 541a915 | 2022-06-01 18:21:17 +0200 | [diff] [blame] | 85 | _construct = GreedyInteger(minlen=2) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 86 | |
Harald Welte | c8c3327 | 2022-02-11 14:45:23 +0100 | [diff] [blame] | 87 | # ETSI TS 102 221 11.1.1.4.2 |
| 88 | class TotalFileSize(BER_TLV_IE, tag=0x81): |
Philipp Maier | 541a915 | 2022-06-01 18:21:17 +0200 | [diff] [blame] | 89 | _construct = GreedyInteger(minlen=2) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 90 | |
| 91 | # ETSI TS 102 221 11.1.1.4.3 |
Harald Welte | c8c3327 | 2022-02-11 14:45:23 +0100 | [diff] [blame] | 92 | class FileDescriptor(BER_TLV_IE, tag=0x82): |
Harald Welte | ee6a951 | 2023-12-23 16:14:04 +0100 | [diff] [blame] | 93 | _test_decode = [ |
| 94 | # FIXME: this doesn't work as _encode test for some strange reason. |
| 95 | ( '82027921', { "file_descriptor_byte": { "shareable": True, "structure": "ber_tlv" }, "record_len": None, "num_of_rec": None } ), |
| 96 | ] |
| 97 | _test_de_encode = [ |
| 98 | ( '82027821', { "file_descriptor_byte": { "shareable": True, "file_type": "df", "structure": "no_info_given" }, "record_len": None, "num_of_rec": None }), |
| 99 | ( '82024121', { "file_descriptor_byte": { "shareable": True, "file_type": "working_ef", "structure": "transparent" }, "record_len": None, "num_of_rec": None } ), |
| 100 | ( '82054221006e05', { "file_descriptor_byte": { "shareable": True, "file_type": "working_ef", "structure": "linear_fixed" }, "record_len": 110, "num_of_rec": 5 } ), |
| 101 | ] |
Harald Welte | 747a978 | 2022-02-13 17:52:28 +0100 | [diff] [blame] | 102 | class BerTlvAdapter(Adapter): |
| 103 | def _parse(self, obj, context, path): |
Harald Welte | ee6a951 | 2023-12-23 16:14:04 +0100 | [diff] [blame] | 104 | data = obj.read() |
| 105 | if data == b'\x01\x01\x01\x00\x00\x01': |
Harald Welte | 747a978 | 2022-02-13 17:52:28 +0100 | [diff] [blame] | 106 | return 'ber_tlv' |
| 107 | raise ValidationError |
| 108 | def _build(self, obj, context, path): |
| 109 | if obj == 'ber_tlv': |
Harald Welte | ee6a951 | 2023-12-23 16:14:04 +0100 | [diff] [blame] | 110 | return b'\x01\x01\x01\x00\x00\x01' |
Harald Welte | 747a978 | 2022-02-13 17:52:28 +0100 | [diff] [blame] | 111 | raise ValidationError |
| 112 | |
| 113 | FDB = Select(BitStruct(Const(0, Bit), 'shareable'/Flag, 'structure'/BerTlvAdapter(Const(0x39, BitsInteger(6)))), |
| 114 | BitStruct(Const(0, Bit), 'shareable'/Flag, 'file_type'/Enum(BitsInteger(3), working_ef=0, internal_ef=1, df=7), |
| 115 | 'structure'/Enum(BitsInteger(3), no_info_given=0, transparent=1, linear_fixed=2, cyclic=6)) |
| 116 | ) |
| 117 | _construct = Struct('file_descriptor_byte'/FDB, Const(b'\x21'), |
Harald Welte | 4ebeebf | 2022-02-25 09:47:51 +0100 | [diff] [blame] | 118 | 'record_len'/COptional(Int16ub), 'num_of_rec'/COptional(Int8ub)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 119 | |
Harald Welte | c8c3327 | 2022-02-11 14:45:23 +0100 | [diff] [blame] | 120 | # ETSI TS 102 221 11.1.1.4.4 |
| 121 | class FileIdentifier(BER_TLV_IE, tag=0x83): |
Harald Welte | 3c9b784 | 2021-10-19 21:44:24 +0200 | [diff] [blame] | 122 | _construct = HexAdapter(GreedyBytes) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 123 | |
Harald Welte | c8c3327 | 2022-02-11 14:45:23 +0100 | [diff] [blame] | 124 | # ETSI TS 102 221 11.1.1.4.5 |
| 125 | class DfName(BER_TLV_IE, tag=0x84): |
Harald Welte | 3c9b784 | 2021-10-19 21:44:24 +0200 | [diff] [blame] | 126 | _construct = HexAdapter(GreedyBytes) |
Harald Welte | c8c3327 | 2022-02-11 14:45:23 +0100 | [diff] [blame] | 127 | |
| 128 | # ETSI TS 102 221 11.1.1.4.6.1 |
| 129 | class UiccCharacteristics(BER_TLV_IE, tag=0x80): |
| 130 | _construct = GreedyBytes |
| 131 | |
| 132 | # ETSI TS 102 221 11.1.1.4.6.2 |
| 133 | class ApplicationPowerConsumption(BER_TLV_IE, tag=0x81): |
| 134 | _construct = Struct('voltage_class'/Int8ub, |
| 135 | 'power_consumption_ma'/Int8ub, |
| 136 | 'reference_freq_100k'/Int8ub) |
| 137 | |
| 138 | # ETSI TS 102 221 11.1.1.4.6.3 |
| 139 | class MinApplicationClockFrequency(BER_TLV_IE, tag=0x82): |
| 140 | _construct = Int8ub |
| 141 | |
| 142 | # ETSI TS 102 221 11.1.1.4.6.4 |
| 143 | class AvailableMemory(BER_TLV_IE, tag=0x83): |
| 144 | _construct = GreedyInteger() |
| 145 | |
| 146 | # ETSI TS 102 221 11.1.1.4.6.5 |
| 147 | class FileDetails(BER_TLV_IE, tag=0x84): |
| 148 | _construct = FlagsEnum(Byte, der_coding_only=1) |
| 149 | |
| 150 | # ETSI TS 102 221 11.1.1.4.6.6 |
| 151 | class ReservedFileSize(BER_TLV_IE, tag=0x85): |
| 152 | _construct = GreedyInteger() |
| 153 | |
| 154 | # ETSI TS 102 221 11.1.1.4.6.7 |
| 155 | class MaximumFileSize(BER_TLV_IE, tag=0x86): |
| 156 | _construct = GreedyInteger() |
| 157 | |
| 158 | # ETSI TS 102 221 11.1.1.4.6.8 |
| 159 | class SupportedFilesystemCommands(BER_TLV_IE, tag=0x87): |
| 160 | _construct = FlagsEnum(Byte, terminal_capability=1) |
| 161 | |
| 162 | # ETSI TS 102 221 11.1.1.4.6.9 |
| 163 | class SpecificUiccEnvironmentConditions(BER_TLV_IE, tag=0x88): |
| 164 | _construct = BitStruct('rfu'/BitsRFU(4), |
| 165 | 'high_humidity_supported'/Flag, |
| 166 | 'temperature_class'/Enum(BitsInteger(3), standard=0, class_A=1, class_B=2, class_C=3)) |
| 167 | |
| 168 | # ETSI TS 102 221 11.1.1.4.6.10 |
| 169 | class Platform2PlatformCatSecuredApdu(BER_TLV_IE, tag=0x89): |
| 170 | _construct = GreedyBytes |
| 171 | |
Harald Welte | 3c9b784 | 2021-10-19 21:44:24 +0200 | [diff] [blame] | 172 | # sysmoISIM-SJA2 specific |
| 173 | class ToolkitAccessConditions(BER_TLV_IE, tag=0xD2): |
| 174 | _construct = FlagsEnum(Byte, rfm_create=1, rfm_delete_terminate=2, other_applet_create=4, |
| 175 | other_applet_delete_terminate=8) |
| 176 | |
Harald Welte | c8c3327 | 2022-02-11 14:45:23 +0100 | [diff] [blame] | 177 | # ETSI TS 102 221 11.1.1.4.6.0 |
| 178 | class ProprietaryInformation(BER_TLV_IE, tag=0xA5, |
| 179 | nested=[UiccCharacteristics, ApplicationPowerConsumption, |
| 180 | MinApplicationClockFrequency, AvailableMemory, |
| 181 | FileDetails, ReservedFileSize, MaximumFileSize, |
Harald Welte | 3c9b784 | 2021-10-19 21:44:24 +0200 | [diff] [blame] | 182 | SupportedFilesystemCommands, SpecificUiccEnvironmentConditions, |
| 183 | ToolkitAccessConditions]): |
Harald Welte | c8c3327 | 2022-02-11 14:45:23 +0100 | [diff] [blame] | 184 | pass |
| 185 | |
| 186 | # ETSI TS 102 221 11.1.1.4.7.1 |
| 187 | class SecurityAttribCompact(BER_TLV_IE, tag=0x8c): |
| 188 | _construct = GreedyBytes |
| 189 | |
| 190 | # ETSI TS 102 221 11.1.1.4.7.2 |
| 191 | class SecurityAttribExpanded(BER_TLV_IE, tag=0xab): |
| 192 | _construct = GreedyBytes |
| 193 | |
| 194 | # ETSI TS 102 221 11.1.1.4.7.3 |
| 195 | class SecurityAttribReferenced(BER_TLV_IE, tag=0x8b): |
| 196 | # TODO: longer format with SEID |
Harald Welte | 3c9b784 | 2021-10-19 21:44:24 +0200 | [diff] [blame] | 197 | _construct = Struct('ef_arr_file_id'/HexAdapter(Bytes(2)), 'ef_arr_record_nr'/Int8ub) |
Harald Welte | c8c3327 | 2022-02-11 14:45:23 +0100 | [diff] [blame] | 198 | |
| 199 | # ETSI TS 102 221 11.1.1.4.8 |
| 200 | class ShortFileIdentifier(BER_TLV_IE, tag=0x88): |
Harald Welte | 5e9bd93 | 2022-02-25 09:35:28 +0100 | [diff] [blame] | 201 | # If the length of the TLV is 1, the SFI value is indicated in the 5 most significant bits (bits b8 to b4) |
| 202 | # of the TLV value field. In this case, bits b3 to b1 shall be set to 0 |
| 203 | class Shift3RAdapter(Adapter): |
| 204 | def _decode(self, obj, context, path): |
Philipp Maier | 373b23c | 2022-06-01 18:16:02 +0200 | [diff] [blame] | 205 | return int.from_bytes(obj, 'big') >> 3 |
Harald Welte | 5e9bd93 | 2022-02-25 09:35:28 +0100 | [diff] [blame] | 206 | def _encode(self, obj, context, path): |
Philipp Maier | 373b23c | 2022-06-01 18:16:02 +0200 | [diff] [blame] | 207 | val = int(obj) << 3 |
| 208 | return val.to_bytes(1, 'big') |
| 209 | _construct = COptional(Shift3RAdapter(Bytes(1))) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 210 | |
| 211 | # ETSI TS 102 221 11.1.1.4.9 |
Harald Welte | c8c3327 | 2022-02-11 14:45:23 +0100 | [diff] [blame] | 212 | class LifeCycleStatusInteger(BER_TLV_IE, tag=0x8A): |
Harald Welte | ee6a951 | 2023-12-23 16:14:04 +0100 | [diff] [blame] | 213 | _test_de_encode = [ |
| 214 | ( '8a0105', 'operational_activated' ), |
| 215 | ] |
Harald Welte | c8c3327 | 2022-02-11 14:45:23 +0100 | [diff] [blame] | 216 | def _from_bytes(self, do: bytes): |
| 217 | lcsi = int.from_bytes(do, 'big') |
| 218 | if lcsi == 0x00: |
| 219 | ret = 'no_information' |
| 220 | elif lcsi == 0x01: |
| 221 | ret = 'creation' |
| 222 | elif lcsi == 0x03: |
| 223 | ret = 'initialization' |
| 224 | elif lcsi & 0x05 == 0x05: |
| 225 | ret = 'operational_activated' |
| 226 | elif lcsi & 0x05 == 0x04: |
| 227 | ret = 'operational_deactivated' |
| 228 | elif lcsi & 0xc0 == 0xc0: |
| 229 | ret = 'termination' |
| 230 | else: |
| 231 | ret = lcsi |
| 232 | self.decoded = ret |
| 233 | return self.decoded |
Harald Welte | 3c9b784 | 2021-10-19 21:44:24 +0200 | [diff] [blame] | 234 | def _to_bytes(self): |
| 235 | if self.decoded == 'no_information': |
| 236 | return b'\x00' |
| 237 | elif self.decoded == 'creation': |
| 238 | return b'\x01' |
| 239 | elif self.decoded == 'initialization': |
| 240 | return b'\x03' |
| 241 | elif self.decoded == 'operational_activated': |
| 242 | return b'\x05' |
| 243 | elif self.decoded == 'operational_deactivated': |
| 244 | return b'\x04' |
| 245 | elif self.decoded == 'termination': |
| 246 | return b'\x0c' |
| 247 | elif isinstance(self.decoded, int): |
| 248 | return self.decoded.to_bytes(1, 'big') |
| 249 | else: |
| 250 | raise ValueError |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 251 | |
Harald Welte | c8c3327 | 2022-02-11 14:45:23 +0100 | [diff] [blame] | 252 | # ETSI TS 102 221 11.1.1.4.9 |
| 253 | class PS_DO(BER_TLV_IE, tag=0x90): |
| 254 | _construct = GreedyBytes |
| 255 | class UsageQualifier_DO(BER_TLV_IE, tag=0x95): |
| 256 | _construct = GreedyBytes |
| 257 | class KeyReference(BER_TLV_IE, tag=0x83): |
| 258 | _construct = Byte |
| 259 | class PinStatusTemplate_DO(BER_TLV_IE, tag=0xC6, nested=[PS_DO, UsageQualifier_DO, KeyReference]): |
| 260 | pass |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 261 | |
Harald Welte | c8c3327 | 2022-02-11 14:45:23 +0100 | [diff] [blame] | 262 | class FcpTemplate(BER_TLV_IE, tag=0x62, nested=[FileSize, TotalFileSize, FileDescriptor, FileIdentifier, |
| 263 | DfName, ProprietaryInformation, SecurityAttribCompact, |
| 264 | SecurityAttribExpanded, SecurityAttribReferenced, |
| 265 | ShortFileIdentifier, LifeCycleStatusInteger, |
| 266 | PinStatusTemplate_DO]): |
| 267 | pass |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 268 | |
| 269 | |
| 270 | def tlv_key_replace(inmap, indata): |
| 271 | def newkey(inmap, key): |
| 272 | if key in inmap: |
| 273 | return inmap[key] |
| 274 | else: |
| 275 | return key |
| 276 | return {newkey(inmap, d[0]): d[1] for d in indata.items()} |
| 277 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 278 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 279 | def tlv_val_interpret(inmap, indata): |
| 280 | def newval(inmap, key, val): |
| 281 | if key in inmap: |
| 282 | return inmap[key](val) |
| 283 | else: |
| 284 | return val |
| 285 | return {d[0]: newval(inmap, d[0], d[1]) for d in indata.items()} |
| 286 | |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 287 | # ETSI TS 102 221 Section 9.2.7 + ISO7816-4 9.3.3/9.3.4 |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 288 | class _AM_DO_DF(DataObject): |
| 289 | def __init__(self): |
| 290 | super().__init__('access_mode', 'Access Mode', tag=0x80) |
| 291 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 292 | def from_bytes(self, do: bytes): |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 293 | res = [] |
| 294 | if len(do) != 1: |
| 295 | raise ValueError("We only support single-byte AMF inside AM-DO") |
| 296 | amf = do[0] |
| 297 | # tables 17..29 and 41..44 of 7816-4 |
| 298 | if amf & 0x80 == 0: |
| 299 | if amf & 0x40: |
| 300 | res.append('delete_file') |
| 301 | if amf & 0x20: |
| 302 | res.append('terminate_df') |
| 303 | if amf & 0x10: |
| 304 | res.append('activate_file') |
| 305 | if amf & 0x08: |
| 306 | res.append('deactivate_file') |
| 307 | if amf & 0x04: |
| 308 | res.append('create_file_df') |
| 309 | if amf & 0x02: |
| 310 | res.append('create_file_ef') |
| 311 | if amf & 0x01: |
| 312 | res.append('delete_file_child') |
| 313 | self.decoded = res |
| 314 | |
| 315 | def to_bytes(self): |
| 316 | val = 0 |
| 317 | if 'delete_file' in self.decoded: |
| 318 | val |= 0x40 |
| 319 | if 'terminate_df' in self.decoded: |
| 320 | val |= 0x20 |
| 321 | if 'activate_file' in self.decoded: |
| 322 | val |= 0x10 |
| 323 | if 'deactivate_file' in self.decoded: |
| 324 | val |= 0x08 |
| 325 | if 'create_file_df' in self.decoded: |
| 326 | val |= 0x04 |
| 327 | if 'create_file_ef' in self.decoded: |
| 328 | val |= 0x02 |
| 329 | if 'delete_file_child' in self.decoded: |
| 330 | val |= 0x01 |
| 331 | return val.to_bytes(1, 'big') |
| 332 | |
| 333 | |
| 334 | class _AM_DO_EF(DataObject): |
| 335 | """ISO7816-4 9.3.2 Table 18 + 9.3.3.1 Table 31""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 336 | |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 337 | def __init__(self): |
| 338 | super().__init__('access_mode', 'Access Mode', tag=0x80) |
| 339 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 340 | def from_bytes(self, do: bytes): |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 341 | res = [] |
| 342 | if len(do) != 1: |
| 343 | raise ValueError("We only support single-byte AMF inside AM-DO") |
| 344 | amf = do[0] |
| 345 | # tables 17..29 and 41..44 of 7816-4 |
| 346 | if amf & 0x80 == 0: |
| 347 | if amf & 0x40: |
| 348 | res.append('delete_file') |
| 349 | if amf & 0x20: |
| 350 | res.append('terminate_ef') |
| 351 | if amf & 0x10: |
| 352 | res.append('activate_file_or_record') |
| 353 | if amf & 0x08: |
| 354 | res.append('deactivate_file_or_record') |
| 355 | if amf & 0x04: |
| 356 | res.append('write_append') |
| 357 | if amf & 0x02: |
| 358 | res.append('update_erase') |
| 359 | if amf & 0x01: |
| 360 | res.append('read_search_compare') |
| 361 | self.decoded = res |
| 362 | |
| 363 | def to_bytes(self): |
| 364 | val = 0 |
| 365 | if 'delete_file' in self.decoded: |
| 366 | val |= 0x40 |
| 367 | if 'terminate_ef' in self.decoded: |
| 368 | val |= 0x20 |
| 369 | if 'activate_file_or_record' in self.decoded: |
| 370 | val |= 0x10 |
| 371 | if 'deactivate_file_or_record' in self.decoded: |
| 372 | val |= 0x08 |
| 373 | if 'write_append' in self.decoded: |
| 374 | val |= 0x04 |
| 375 | if 'update_erase' in self.decoded: |
| 376 | val |= 0x02 |
| 377 | if 'read_search_compare' in self.decoded: |
| 378 | val |= 0x01 |
| 379 | return val.to_bytes(1, 'big') |
| 380 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 381 | |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 382 | class _AM_DO_CHDR(DataObject): |
| 383 | """Command Header Access Mode DO according to ISO 7816-4 Table 32.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 384 | |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 385 | def __init__(self, tag): |
| 386 | super().__init__('command_header', 'Command Header Description', tag=tag) |
| 387 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 388 | def from_bytes(self, do: bytes): |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 389 | res = {} |
| 390 | i = 0 |
| 391 | if self.tag & 0x08: |
| 392 | res['CLA'] = do[i] |
| 393 | i += 1 |
| 394 | if self.tag & 0x04: |
| 395 | res['INS'] = do[i] |
| 396 | i += 1 |
| 397 | if self.tag & 0x02: |
| 398 | res['P1'] = do[i] |
| 399 | i += 1 |
| 400 | if self.tag & 0x01: |
| 401 | res['P2'] = do[i] |
| 402 | i += 1 |
| 403 | self.decoded = res |
| 404 | |
| 405 | def _compute_tag(self): |
| 406 | """Override to encode the tag, as it depends on the value.""" |
| 407 | tag = 0x80 |
| 408 | if 'CLA' in self.decoded: |
| 409 | tag |= 0x08 |
| 410 | if 'INS' in self.decoded: |
| 411 | tag |= 0x04 |
| 412 | if 'P1' in self.decoded: |
| 413 | tag |= 0x02 |
| 414 | if 'P2' in self.decoded: |
| 415 | tag |= 0x01 |
| 416 | return tag |
| 417 | |
| 418 | def to_bytes(self): |
| 419 | res = bytearray() |
| 420 | if 'CLA' in self.decoded: |
| 421 | res.append(self.decoded['CLA']) |
| 422 | if 'INS' in self.decoded: |
| 423 | res.append(self.decoded['INS']) |
| 424 | if 'P1' in self.decoded: |
| 425 | res.append(self.decoded['P1']) |
| 426 | if 'P2' in self.decoded: |
| 427 | res.append(self.decoded['P2']) |
| 428 | return res |
| 429 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 430 | |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 431 | AM_DO_CHDR = DataObjectChoice('am_do_chdr', members=[ |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 432 | _AM_DO_CHDR(0x81), _AM_DO_CHDR(0x82), _AM_DO_CHDR(0x83), _AM_DO_CHDR(0x84), |
| 433 | _AM_DO_CHDR(0x85), _AM_DO_CHDR(0x86), _AM_DO_CHDR(0x87), _AM_DO_CHDR(0x88), |
| 434 | _AM_DO_CHDR(0x89), _AM_DO_CHDR(0x8a), _AM_DO_CHDR(0x8b), _AM_DO_CHDR(0x8c), |
| 435 | _AM_DO_CHDR(0x8d), _AM_DO_CHDR(0x8e), _AM_DO_CHDR(0x8f)]) |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 436 | |
| 437 | AM_DO_DF = AM_DO_CHDR | _AM_DO_DF() |
| 438 | AM_DO_EF = AM_DO_CHDR | _AM_DO_EF() |
| 439 | |
| 440 | |
| 441 | # TS 102 221 Section 9.5.1 / Table 9.3 |
| 442 | pin_names = bidict({ |
| 443 | 0x01: 'PIN1', |
| 444 | 0x02: 'PIN2', |
| 445 | 0x03: 'PIN3', |
| 446 | 0x04: 'PIN4', |
| 447 | 0x05: 'PIN5', |
| 448 | 0x06: 'PIN6', |
| 449 | 0x07: 'PIN7', |
| 450 | 0x08: 'PIN8', |
| 451 | 0x0a: 'ADM1', |
| 452 | 0x0b: 'ADM2', |
| 453 | 0x0c: 'ADM3', |
| 454 | 0x0d: 'ADM4', |
| 455 | 0x0e: 'ADM5', |
| 456 | |
| 457 | 0x11: 'UNIVERSAL_PIN', |
| 458 | 0x81: '2PIN1', |
| 459 | 0x82: '2PIN2', |
| 460 | 0x83: '2PIN3', |
| 461 | 0x84: '2PIN4', |
| 462 | 0x85: '2PIN5', |
| 463 | 0x86: '2PIN6', |
| 464 | 0x87: '2PIN7', |
| 465 | 0x88: '2PIN8', |
| 466 | 0x8a: 'ADM6', |
| 467 | 0x8b: 'ADM7', |
| 468 | 0x8c: 'ADM8', |
| 469 | 0x8d: 'ADM9', |
| 470 | 0x8e: 'ADM10', |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 471 | }) |
| 472 | |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 473 | |
| 474 | class CRT_DO(DataObject): |
| 475 | """Control Reference Template as per TS 102 221 9.5.1""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 476 | |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 477 | def __init__(self): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 478 | super().__init__('control_reference_template', |
| 479 | 'Control Reference Template', tag=0xA4) |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 480 | |
| 481 | def from_bytes(self, do: bytes): |
| 482 | """Decode a Control Reference Template DO.""" |
| 483 | if len(do) != 6: |
| 484 | raise ValueError('Unsupported CRT DO length: %s', do) |
| 485 | if do[0] != 0x83 or do[1] != 0x01: |
| 486 | raise ValueError('Unsupported Key Ref Tag or Len in CRT DO %s', do) |
| 487 | if do[3:] != b'\x95\x01\x08': |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 488 | raise ValueError( |
| 489 | 'Unsupported Usage Qualifier Tag or Len in CRT DO %s', do) |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 490 | self.encoded = do[0:6] |
| 491 | self.decoded = pin_names[do[2]] |
| 492 | return do[6:] |
| 493 | |
| 494 | def to_bytes(self): |
| 495 | pin = pin_names.inverse[self.decoded] |
| 496 | return b'\x83\x01' + pin.to_bytes(1, 'big') + b'\x95\x01\x08' |
| 497 | |
| 498 | # ISO7816-4 9.3.3 Table 33 |
| 499 | class SecCondByte_DO(DataObject): |
| 500 | def __init__(self, tag=0x9d): |
| 501 | super().__init__('security_condition_byte', tag=tag) |
| 502 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 503 | def from_bytes(self, binary: bytes): |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 504 | if len(binary) != 1: |
| 505 | raise ValueError |
| 506 | inb = binary[0] |
| 507 | if inb == 0: |
| 508 | cond = 'always' |
| 509 | if inb == 0xff: |
| 510 | cond = 'never' |
| 511 | res = [] |
| 512 | if inb & 0x80: |
| 513 | cond = 'and' |
| 514 | else: |
| 515 | cond = 'or' |
| 516 | if inb & 0x40: |
| 517 | res.append('secure_messaging') |
| 518 | if inb & 0x20: |
| 519 | res.append('external_auth') |
| 520 | if inb & 0x10: |
| 521 | res.append('user_auth') |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 522 | rd = {'mode': cond} |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 523 | if len(res): |
| 524 | rd['conditions'] = res |
| 525 | self.decoded = rd |
| 526 | |
| 527 | def to_bytes(self): |
| 528 | mode = self.decoded['mode'] |
| 529 | if mode == 'always': |
| 530 | res = 0 |
| 531 | elif mode == 'never': |
| 532 | res = 0xff |
| 533 | else: |
| 534 | res = 0 |
| 535 | if mode == 'and': |
| 536 | res |= 0x80 |
| 537 | elif mode == 'or': |
| 538 | pass |
| 539 | else: |
| 540 | raise ValueError('Unknown mode %s' % mode) |
| 541 | for c in self.decoded['conditions']: |
| 542 | if c == 'secure_messaging': |
| 543 | res |= 0x40 |
| 544 | elif c == 'external_auth': |
| 545 | res |= 0x20 |
| 546 | elif c == 'user_auth': |
| 547 | res |= 0x10 |
| 548 | else: |
| 549 | raise ValueError('Unknown condition %s' % c) |
| 550 | return res.to_bytes(1, 'big') |
| 551 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 552 | |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 553 | Always_DO = TL0_DataObject('always', 'Always', 0x90) |
| 554 | Never_DO = TL0_DataObject('never', 'Never', 0x97) |
Harald Welte | b060833 | 2022-02-10 12:45:37 +0100 | [diff] [blame] | 555 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 556 | |
Harald Welte | b060833 | 2022-02-10 12:45:37 +0100 | [diff] [blame] | 557 | class Nested_DO(DataObject): |
| 558 | """A DO that nests another DO/Choice/Sequence""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 559 | |
Harald Welte | b060833 | 2022-02-10 12:45:37 +0100 | [diff] [blame] | 560 | def __init__(self, name, tag, choice): |
| 561 | super().__init__(name, tag=tag) |
| 562 | self.children = choice |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 563 | |
| 564 | def from_bytes(self, binary: bytes) -> list: |
Harald Welte | b060833 | 2022-02-10 12:45:37 +0100 | [diff] [blame] | 565 | remainder = binary |
| 566 | self.decoded = [] |
| 567 | while remainder: |
| 568 | rc, remainder = self.children.decode(remainder) |
| 569 | self.decoded.append(rc) |
| 570 | return self.decoded |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 571 | |
Harald Welte | b060833 | 2022-02-10 12:45:37 +0100 | [diff] [blame] | 572 | def to_bytes(self) -> bytes: |
| 573 | encoded = [self.children.encode(d) for d in self.decoded] |
| 574 | return b''.join(encoded) |
| 575 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 576 | |
Harald Welte | b060833 | 2022-02-10 12:45:37 +0100 | [diff] [blame] | 577 | OR_Template = DataObjectChoice('or_template', 'OR-Template', |
| 578 | members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO()]) |
| 579 | OR_DO = Nested_DO('or', 0xa0, OR_Template) |
| 580 | AND_Template = DataObjectChoice('and_template', 'AND-Template', |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 581 | members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO()]) |
Harald Welte | b060833 | 2022-02-10 12:45:37 +0100 | [diff] [blame] | 582 | AND_DO = Nested_DO('and', 0xa7, AND_Template) |
| 583 | NOT_Template = DataObjectChoice('not_template', 'NOT-Template', |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 584 | members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO()]) |
Harald Welte | b060833 | 2022-02-10 12:45:37 +0100 | [diff] [blame] | 585 | NOT_DO = Nested_DO('not', 0xaf, NOT_Template) |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 586 | SC_DO = DataObjectChoice('security_condition', 'Security Condition', |
Harald Welte | b060833 | 2022-02-10 12:45:37 +0100 | [diff] [blame] | 587 | members=[Always_DO, Never_DO, SecCondByte_DO(), SecCondByte_DO(0x9e), CRT_DO(), |
| 588 | OR_DO, AND_DO, NOT_DO]) |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 589 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 590 | # TS 102 221 Section 13.1 |
| 591 | class EF_DIR(LinFixedEF): |
Harald Welte | 865eea6 | 2023-01-27 19:26:12 +0100 | [diff] [blame] | 592 | # FIXME: re-encode failure when changing to _test_de_encode |
| 593 | _test_decode = [ |
| 594 | ( '61294f10a0000000871002ffffffff890709000050055553696d31730ea00c80011781025f608203454150', |
| 595 | { "application_template": [ { "application_id": h2b("a0000000871002ffffffff8907090000") }, |
| 596 | { "application_label": "USim1" }, |
| 597 | { "discretionary_template": h2b("a00c80011781025f608203454150") } ] } |
| 598 | ), |
Harald Welte | ee6a951 | 2023-12-23 16:14:04 +0100 | [diff] [blame] | 599 | ( '61194f10a0000000871004ffffffff890709000050054953696d31', |
| 600 | { "application_template": [ { "application_id": h2b("a0000000871004ffffffff8907090000") }, |
| 601 | { "application_label": "ISim1" } ] } |
| 602 | ), |
Harald Welte | 865eea6 | 2023-01-27 19:26:12 +0100 | [diff] [blame] | 603 | ] |
Harald Welte | 181c7c5 | 2022-02-10 14:18:32 +0100 | [diff] [blame] | 604 | class ApplicationLabel(BER_TLV_IE, tag=0x50): |
| 605 | # TODO: UCS-2 coding option as per Annex A of TS 102 221 |
| 606 | _construct = GreedyString('ascii') |
| 607 | |
| 608 | # see https://github.com/PyCQA/pylint/issues/5794 |
| 609 | #pylint: disable=undefined-variable |
| 610 | class ApplicationTemplate(BER_TLV_IE, tag=0x61, |
| 611 | nested=[iso7816_4.ApplicationId, ApplicationLabel, iso7816_4.FileReference, |
| 612 | iso7816_4.CommandApdu, iso7816_4.DiscretionaryData, |
| 613 | iso7816_4.DiscretionaryTemplate, iso7816_4.URL, |
| 614 | iso7816_4.ApplicationRelatedDOSet]): |
| 615 | pass |
| 616 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 617 | def __init__(self, fid='2f00', sfid=0x1e, name='EF.DIR', desc='Application Directory'): |
Harald Welte | 99e4cc0 | 2022-07-21 15:25:47 +0200 | [diff] [blame] | 618 | super().__init__(fid, sfid=sfid, name=name, desc=desc, rec_len=(5, 54)) |
Harald Welte | 181c7c5 | 2022-02-10 14:18:32 +0100 | [diff] [blame] | 619 | self._tlv = EF_DIR.ApplicationTemplate |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 620 | |
| 621 | # TS 102 221 Section 13.2 |
| 622 | class EF_ICCID(TransparentEF): |
Harald Welte | 865eea6 | 2023-01-27 19:26:12 +0100 | [diff] [blame] | 623 | _test_de_encode = [ |
| 624 | ( '988812010000400310f0', { "iccid": "8988211000000430010" } ), |
| 625 | ] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 626 | def __init__(self, fid='2fe2', sfid=0x02, name='EF.ICCID', desc='ICC Identification'): |
Harald Welte | 13edf30 | 2022-07-21 15:19:23 +0200 | [diff] [blame] | 627 | super().__init__(fid, sfid=sfid, name=name, desc=desc, size=(10, 10)) |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 628 | |
| 629 | def _decode_hex(self, raw_hex): |
| 630 | return {'iccid': dec_iccid(raw_hex)} |
| 631 | |
| 632 | def _encode_hex(self, abstract): |
| 633 | return enc_iccid(abstract['iccid']) |
| 634 | |
| 635 | # TS 102 221 Section 13.3 |
| 636 | class EF_PL(TransRecEF): |
Harald Welte | 865eea6 | 2023-01-27 19:26:12 +0100 | [diff] [blame] | 637 | _test_de_encode = [ |
| 638 | ( '6465', "de" ), |
| 639 | ( '656e', "en" ), |
| 640 | ( 'ffff', None ), |
| 641 | ] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 642 | def __init__(self, fid='2f05', sfid=0x05, name='EF.PL', desc='Preferred Languages'): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 643 | super().__init__(fid, sfid=sfid, name=name, |
Harald Welte | 13edf30 | 2022-07-21 15:19:23 +0200 | [diff] [blame] | 644 | desc=desc, rec_len=2, size=(2, None)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 645 | |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 646 | def _decode_record_bin(self, bin_data, **kwargs): |
Harald Welte | 0c840f0 | 2022-01-21 15:42:22 +0100 | [diff] [blame] | 647 | if bin_data == b'\xff\xff': |
| 648 | return None |
| 649 | else: |
| 650 | return bin_data.decode('ascii') |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 651 | |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 652 | def _encode_record_bin(self, in_json, **kwargs): |
Harald Welte | 0c840f0 | 2022-01-21 15:42:22 +0100 | [diff] [blame] | 653 | if in_json is None: |
| 654 | return b'\xff\xff' |
| 655 | else: |
| 656 | return in_json.encode('ascii') |
| 657 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 658 | |
| 659 | # TS 102 221 Section 13.4 |
| 660 | class EF_ARR(LinFixedEF): |
Harald Welte | 865eea6 | 2023-01-27 19:26:12 +0100 | [diff] [blame] | 661 | _test_de_encode = [ |
| 662 | ( '800101a40683010a950108800106900080016097008401d4a40683010a950108', |
| 663 | [ [ { "access_mode": [ "read_search_compare" ] }, |
| 664 | { "control_reference_template": "ADM1" } ], |
| 665 | [ { "access_mode": [ "write_append", "update_erase" ] }, |
| 666 | { "always": None } ], |
| 667 | [ { "access_mode": [ "delete_file", "terminate_ef" ] }, |
| 668 | { "never": None } ], |
| 669 | [ { "command_header": { "INS": 212 } }, |
| 670 | { "control_reference_template": "ADM1" } ] |
| 671 | ] ), |
| 672 | ( '80010190008001029700800118a40683010a9501088401d4a40683010a950108', |
| 673 | [ [ { "access_mode": [ "read_search_compare" ] }, |
| 674 | { "always": None } ], |
| 675 | [ { "access_mode": [ "update_erase" ] }, |
| 676 | { "never": None } ], |
| 677 | [ { "access_mode": [ "activate_file_or_record", "deactivate_file_or_record" ] }, |
| 678 | { "control_reference_template": "ADM1" } ], |
| 679 | [ { "command_header": { "INS": 212 } }, |
| 680 | { "control_reference_template": "ADM1" } ] |
| 681 | ] ), |
| 682 | ] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 683 | def __init__(self, fid='2f06', sfid=0x06, name='EF.ARR', desc='Access Rule Reference'): |
| 684 | super().__init__(fid, sfid=sfid, name=name, desc=desc) |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 685 | # add those commands to the general commands of a TransparentEF |
| 686 | self.shell_commands += [self.AddlShellCommands()] |
| 687 | |
| 688 | @staticmethod |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 689 | def flatten(inp: list): |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 690 | """Flatten the somewhat deep/complex/nested data returned from decoder.""" |
| 691 | def sc_abbreviate(sc): |
| 692 | if 'always' in sc: |
| 693 | return 'always' |
| 694 | elif 'never' in sc: |
| 695 | return 'never' |
| 696 | elif 'control_reference_template' in sc: |
| 697 | return sc['control_reference_template'] |
| 698 | else: |
| 699 | return sc |
| 700 | |
| 701 | by_mode = {} |
| 702 | for t in inp: |
| 703 | am = t[0] |
| 704 | sc = t[1] |
| 705 | sc_abbr = sc_abbreviate(sc) |
| 706 | if 'access_mode' in am: |
| 707 | for m in am['access_mode']: |
| 708 | by_mode[m] = sc_abbr |
| 709 | elif 'command_header' in am: |
| 710 | ins = am['command_header']['INS'] |
| 711 | if 'CLA' in am['command_header']: |
| 712 | cla = am['command_header']['CLA'] |
| 713 | else: |
| 714 | cla = None |
| 715 | cmd = ts_102_22x_cmdset.lookup(ins, cla) |
| 716 | if cmd: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 717 | name = cmd.name.lower().replace(' ', '_') |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 718 | by_mode[name] = sc_abbr |
| 719 | else: |
| 720 | raise ValueError |
| 721 | else: |
| 722 | raise ValueError |
| 723 | return by_mode |
| 724 | |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 725 | def _decode_record_bin(self, raw_bin_data, **kwargs): |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 726 | # we can only guess if we should decode for EF or DF here :( |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 727 | arr_seq = DataObjectSequence('arr', sequence=[AM_DO_EF, SC_DO]) |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 728 | dec = arr_seq.decode_multi(raw_bin_data) |
| 729 | # we cannot pass the result through flatten() here, as we don't have a related |
| 730 | # 'un-flattening' decoder, and hence would be unable to encode :( |
| 731 | return dec[0] |
| 732 | |
Harald Welte | f6b37af | 2023-01-24 15:42:26 +0100 | [diff] [blame] | 733 | def _encode_record_bin(self, in_json, **kwargs): |
Harald Welte | c30bed2 | 2022-04-05 14:45:18 +0200 | [diff] [blame] | 734 | # we can only guess if we should decode for EF or DF here :( |
| 735 | arr_seq = DataObjectSequence('arr', sequence=[AM_DO_EF, SC_DO]) |
| 736 | return arr_seq.encode_multi(in_json) |
| 737 | |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 738 | @with_default_category('File-Specific Commands') |
| 739 | class AddlShellCommands(CommandSet): |
| 740 | def __init__(self): |
| 741 | super().__init__() |
| 742 | |
| 743 | @cmd2.with_argparser(LinFixedEF.ShellCommands.read_rec_dec_parser) |
| 744 | def do_read_arr_record(self, opts): |
| 745 | """Read one EF.ARR record in flattened, human-friendly form.""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 746 | (data, sw) = self._cmd.lchan.read_record_dec(opts.record_nr) |
| 747 | data = self._cmd.lchan.selected_file.flatten(data) |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 748 | self._cmd.poutput_json(data, opts.oneline) |
| 749 | |
| 750 | @cmd2.with_argparser(LinFixedEF.ShellCommands.read_recs_dec_parser) |
| 751 | def do_read_arr_records(self, opts): |
| 752 | """Read + decode all EF.ARR records in flattened, human-friendly form.""" |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 753 | num_of_rec = self._cmd.lchan.selected_file_num_of_rec() |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 754 | # collect all results in list so they are rendered as JSON list when printing |
| 755 | data_list = [] |
| 756 | for recnr in range(1, 1 + num_of_rec): |
Harald Welte | a6c0f88 | 2022-07-17 14:23:17 +0200 | [diff] [blame] | 757 | (data, sw) = self._cmd.lchan.read_record_dec(recnr) |
| 758 | data = self._cmd.lchan.selected_file.flatten(data) |
Harald Welte | 4ae228a | 2021-05-02 21:29:04 +0200 | [diff] [blame] | 759 | data_list.append(data) |
| 760 | self._cmd.poutput_json(data_list, opts.oneline) |
| 761 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 762 | |
| 763 | # TS 102 221 Section 13.6 |
| 764 | class EF_UMPC(TransparentEF): |
Harald Welte | 865eea6 | 2023-01-27 19:26:12 +0100 | [diff] [blame] | 765 | _test_de_encode = [ |
| 766 | ( '3cff02', { "max_current_mA": 60, "t_op_s": 255, |
| 767 | "addl_info": { "req_inc_idle_current": False, "support_uicc_suspend": True } } ), |
Harald Welte | 324175f | 2023-12-21 20:25:30 +0100 | [diff] [blame] | 768 | ( '320500', { "max_current_mA": 50, "t_op_s": 5, "addl_info": {"req_inc_idle_current": False, |
| 769 | "support_uicc_suspend": False } } ), |
Harald Welte | 865eea6 | 2023-01-27 19:26:12 +0100 | [diff] [blame] | 770 | ] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 771 | def __init__(self, fid='2f08', sfid=0x08, name='EF.UMPC', desc='UICC Maximum Power Consumption'): |
Harald Welte | 13edf30 | 2022-07-21 15:19:23 +0200 | [diff] [blame] | 772 | super().__init__(fid, sfid=sfid, name=name, desc=desc, size=(5, 5)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 773 | addl_info = FlagsEnum(Byte, req_inc_idle_current=1, |
| 774 | support_uicc_suspend=2) |
| 775 | self._construct = Struct( |
| 776 | 'max_current_mA'/Int8ub, 't_op_s'/Int8ub, 'addl_info'/addl_info) |
| 777 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 778 | |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 779 | class CardProfileUICC(CardProfile): |
Philipp Maier | a028c7d | 2021-11-08 16:12:03 +0100 | [diff] [blame] | 780 | |
| 781 | ORDER = 1 |
| 782 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 783 | def __init__(self, name='UICC'): |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 784 | files = [ |
| 785 | EF_DIR(), |
| 786 | EF_ICCID(), |
| 787 | EF_PL(), |
| 788 | EF_ARR(), |
| 789 | # FIXME: DF.CD |
| 790 | EF_UMPC(), |
| 791 | ] |
Harald Welte | 323a350 | 2023-07-11 17:26:39 +0200 | [diff] [blame] | 792 | addons = [ |
| 793 | AddonSIM, |
| 794 | AddonGSMR, |
| 795 | AddonRUIM, |
| 796 | ] |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 797 | sw = { |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 798 | 'Normal': { |
| 799 | '9000': 'Normal ending of the command', |
| 800 | '91xx': 'Normal ending of the command, with extra information from the proactive UICC containing a command for the terminal', |
| 801 | '92xx': 'Normal ending of the command, with extra information concerning an ongoing data transfer session', |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 802 | }, |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 803 | 'Postponed processing': { |
| 804 | '9300': 'SIM Application Toolkit is busy. Command cannot be executed at present, further normal commands are allowed', |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 805 | }, |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 806 | 'Warnings': { |
| 807 | '6200': 'No information given, state of non-volatile memory unchanged', |
| 808 | '6281': 'Part of returned data may be corrupted', |
| 809 | '6282': 'End of file/record reached before reading Le bytes or unsuccessful search', |
| 810 | '6283': 'Selected file invalidated', |
| 811 | '6284': 'Selected file in termination state', |
| 812 | '62f1': 'More data available', |
| 813 | '62f2': 'More data available and proactive command pending', |
| 814 | '62f3': 'Response data available', |
| 815 | '63f1': 'More data expected', |
| 816 | '63f2': 'More data expected and proactive command pending', |
| 817 | '63cx': 'Command successful but after using an internal update retry routine X times', |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 818 | }, |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 819 | 'Execution errors': { |
| 820 | '6400': 'No information given, state of non-volatile memory unchanged', |
| 821 | '6500': 'No information given, state of non-volatile memory changed', |
| 822 | '6581': 'Memory problem', |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 823 | }, |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 824 | 'Checking errors': { |
| 825 | '6700': 'Wrong length', |
| 826 | '67xx': 'The interpretation of this status word is command dependent', |
| 827 | '6b00': 'Wrong parameter(s) P1-P2', |
| 828 | '6d00': 'Instruction code not supported or invalid', |
| 829 | '6e00': 'Class not supported', |
| 830 | '6f00': 'Technical problem, no precise diagnosis', |
| 831 | '6fxx': 'The interpretation of this status word is command dependent', |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 832 | }, |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 833 | 'Functions in CLA not supported': { |
| 834 | '6800': 'No information given', |
| 835 | '6881': 'Logical channel not supported', |
| 836 | '6882': 'Secure messaging not supported', |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 837 | }, |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 838 | 'Command not allowed': { |
| 839 | '6900': 'No information given', |
| 840 | '6981': 'Command incompatible with file structure', |
| 841 | '6982': 'Security status not satisfied', |
| 842 | '6983': 'Authentication/PIN method blocked', |
| 843 | '6984': 'Referenced data invalidated', |
| 844 | '6985': 'Conditions of use not satisfied', |
| 845 | '6986': 'Command not allowed (no EF selected)', |
| 846 | '6989': 'Command not allowed - secure channel - security not satisfied', |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 847 | }, |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 848 | 'Wrong parameters': { |
| 849 | '6a80': 'Incorrect parameters in the data field', |
| 850 | '6a81': 'Function not supported', |
| 851 | '6a82': 'File not found', |
| 852 | '6a83': 'Record not found', |
| 853 | '6a84': 'Not enough memory space', |
| 854 | '6a86': 'Incorrect parameters P1 to P2', |
| 855 | '6a87': 'Lc inconsistent with P1 to P2', |
| 856 | '6a88': 'Referenced data not found', |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 857 | }, |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 858 | 'Application errors': { |
| 859 | '9850': 'INCREASE cannot be performed, max value reached', |
| 860 | '9862': 'Authentication error, application specific', |
| 861 | '9863': 'Security session or association expired', |
| 862 | '9864': 'Minimum UICC suspension time is too long', |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 863 | }, |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 864 | } |
Harald Welte | b2edd14 | 2021-01-08 23:29:35 +0100 | [diff] [blame] | 865 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 866 | super().__init__(name, desc='ETSI TS 102 221', cla="00", |
Harald Welte | 659781c | 2023-06-06 17:00:51 +0200 | [diff] [blame] | 867 | sel_ctrl="0004", files_in_mf=files, sw=sw, |
Harald Welte | 323a350 | 2023-07-11 17:26:39 +0200 | [diff] [blame] | 868 | shell_cmdsets = [self.AddlShellCommands()], addons = addons) |
Philipp Maier | 5af7bdf | 2021-11-04 12:48:41 +0100 | [diff] [blame] | 869 | |
Philipp Maier | 5998a3a | 2021-11-16 15:16:39 +0100 | [diff] [blame] | 870 | @staticmethod |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 871 | def decode_select_response(resp_hex: str) -> object: |
Philipp Maier | 5998a3a | 2021-11-16 15:16:39 +0100 | [diff] [blame] | 872 | """ETSI TS 102 221 Section 11.1.1.3""" |
Harald Welte | c8c3327 | 2022-02-11 14:45:23 +0100 | [diff] [blame] | 873 | t = FcpTemplate() |
| 874 | t.from_tlv(h2b(resp_hex)) |
| 875 | d = t.to_dict() |
| 876 | return flatten_dict_lists(d['fcp_template']) |
Philipp Maier | a028c7d | 2021-11-08 16:12:03 +0100 | [diff] [blame] | 877 | |
| 878 | @staticmethod |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 879 | def match_with_card(scc: SimCardCommands) -> bool: |
Philipp Maier | a028c7d | 2021-11-08 16:12:03 +0100 | [diff] [blame] | 880 | return match_uicc(scc) |
| 881 | |
Harald Welte | 659781c | 2023-06-06 17:00:51 +0200 | [diff] [blame] | 882 | @with_default_category('TS 102 221 Specific Commands') |
| 883 | class AddlShellCommands(CommandSet): |
| 884 | suspend_uicc_parser = argparse.ArgumentParser() |
| 885 | suspend_uicc_parser.add_argument('--min-duration-secs', type=int, default=60, |
| 886 | help='Proposed minimum duration of suspension') |
| 887 | suspend_uicc_parser.add_argument('--max-duration-secs', type=int, default=24*60*60, |
| 888 | help='Proposed maximum duration of suspension') |
| 889 | |
| 890 | # not ISO7816-4 but TS 102 221 |
| 891 | @cmd2.with_argparser(suspend_uicc_parser) |
| 892 | def do_suspend_uicc(self, opts): |
Harald Welte | b0e0dce | 2023-06-06 17:21:13 +0200 | [diff] [blame] | 893 | """Perform the SUSPEND UICC command. Only supported on some UICC (check EF.UMPC).""" |
Harald Welte | 659781c | 2023-06-06 17:00:51 +0200 | [diff] [blame] | 894 | (duration, token, sw) = self._cmd.card._scc.suspend_uicc(min_len_secs=opts.min_duration_secs, |
| 895 | max_len_secs=opts.max_duration_secs) |
| 896 | self._cmd.poutput( |
| 897 | 'Negotiated Duration: %u secs, Token: %s, SW: %s' % (duration, token, sw)) |
| 898 | |
Harald Welte | b0e0dce | 2023-06-06 17:21:13 +0200 | [diff] [blame] | 899 | resume_uicc_parser = argparse.ArgumentParser() |
| 900 | resume_uicc_parser.add_argument('token', type=str, help='Token provided during SUSPEND') |
| 901 | |
| 902 | @cmd2.with_argparser(resume_uicc_parser) |
| 903 | def do_resume_uicc(self, opts): |
| 904 | """Perform the REUSME UICC operation. Only supported on some UICC. Also: A power-cycle |
| 905 | of the card is required between SUSPEND and RESUME, and only very few non-RESUME |
| 906 | commands are permitted between SUSPEND and RESUME. See TS 102 221 Section 11.1.22.""" |
| 907 | self._cmd.card._scc.resume_uicc(opts.token) |