Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
| 2 | |
| 3 | """ pySim: various utilities |
| 4 | """ |
| 5 | |
Harald Welte | 5e749a7 | 2021-04-10 17:18:17 +0200 | [diff] [blame] | 6 | import json |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 7 | import abc |
Philipp Maier | 796ca3d | 2021-11-01 17:13:57 +0100 | [diff] [blame] | 8 | import string |
Harald Welte | 5e749a7 | 2021-04-10 17:18:17 +0200 | [diff] [blame] | 9 | from io import BytesIO |
Harald Welte | f5e26ae | 2023-07-09 16:11:46 +0200 | [diff] [blame] | 10 | from typing import Optional, List, Dict, Any, Tuple, NewType |
Harald Welte | 5225557 | 2021-04-03 09:56:32 +0200 | [diff] [blame] | 11 | |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 12 | # Copyright (C) 2009-2010 Sylvain Munaut <tnt@246tNt.com> |
Harald Welte | 5e749a7 | 2021-04-10 17:18:17 +0200 | [diff] [blame] | 13 | # Copyright (C) 2021 Harald Welte <laforge@osmocom.org> |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 14 | # |
| 15 | # This program is free software: you can redistribute it and/or modify |
| 16 | # it under the terms of the GNU General Public License as published by |
| 17 | # the Free Software Foundation, either version 2 of the License, or |
| 18 | # (at your option) any later version. |
| 19 | # |
| 20 | # This program is distributed in the hope that it will be useful, |
| 21 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 22 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 23 | # GNU General Public License for more details. |
| 24 | # |
| 25 | # You should have received a copy of the GNU General Public License |
| 26 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 27 | # |
| 28 | |
Harald Welte | 5225557 | 2021-04-03 09:56:32 +0200 | [diff] [blame] | 29 | # just to differentiate strings of hex nibbles from everything else |
Harald Welte | f5e26ae | 2023-07-09 16:11:46 +0200 | [diff] [blame] | 30 | Hexstr = NewType('Hexstr', str) |
Harald Welte | ab6897c | 2023-07-09 16:21:23 +0200 | [diff] [blame] | 31 | SwHexstr = NewType('SwHexstr', str) |
| 32 | SwMatchstr = NewType('SwMatchstr', str) |
Harald Welte | fdb187d | 2023-07-09 17:03:17 +0200 | [diff] [blame] | 33 | ResTuple = Tuple[Hexstr, SwHexstr] |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 34 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 35 | def h2b(s: Hexstr) -> bytearray: |
| 36 | """convert from a string of hex nibbles to a sequence of bytes""" |
| 37 | return bytearray.fromhex(s) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 38 | |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 39 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 40 | def b2h(b: bytearray) -> Hexstr: |
| 41 | """convert from a sequence of bytes to a string of hex nibbles""" |
| 42 | return ''.join(['%02x' % (x) for x in b]) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 43 | |
Alexander Chemeris | a5f0ea6 | 2017-07-18 16:48:47 +0300 | [diff] [blame] | 44 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 45 | def h2i(s: Hexstr) -> List[int]: |
| 46 | """convert from a string of hex nibbles to a list of integers""" |
| 47 | return [(int(x, 16) << 4)+int(y, 16) for x, y in zip(s[0::2], s[1::2])] |
Alexander Chemeris | a5f0ea6 | 2017-07-18 16:48:47 +0300 | [diff] [blame] | 48 | |
Supreeth Herle | 7d77d2d | 2020-05-11 09:07:08 +0200 | [diff] [blame] | 49 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 50 | def i2h(s: List[int]) -> Hexstr: |
| 51 | """convert from a list of integers to a string of hex nibbles""" |
| 52 | return ''.join(['%02x' % (x) for x in s]) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 53 | |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 54 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 55 | def h2s(s: Hexstr) -> str: |
| 56 | """convert from a string of hex nibbles to an ASCII string""" |
| 57 | return ''.join([chr((int(x, 16) << 4)+int(y, 16)) for x, y in zip(s[0::2], s[1::2]) |
| 58 | if int(x + y, 16) != 0xff]) |
Alexander Chemeris | 5e96c3d | 2013-07-04 17:33:33 +0400 | [diff] [blame] | 59 | |
Ben Fox-Moore | 0ec1475 | 2018-09-24 15:47:02 +0200 | [diff] [blame] | 60 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 61 | def s2h(s: str) -> Hexstr: |
| 62 | """convert from an ASCII string to a string of hex nibbles""" |
| 63 | b = bytearray() |
| 64 | b.extend(map(ord, s)) |
| 65 | return b2h(b) |
Philipp Maier | 796ca3d | 2021-11-01 17:13:57 +0100 | [diff] [blame] | 66 | |
Philipp Maier | 796ca3d | 2021-11-01 17:13:57 +0100 | [diff] [blame] | 67 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 68 | def i2s(s: List[int]) -> str: |
| 69 | """convert from a list of integers to an ASCII string""" |
| 70 | return ''.join([chr(x) for x in s]) |
| 71 | |
| 72 | |
| 73 | def swap_nibbles(s: Hexstr) -> Hexstr: |
| 74 | """swap the nibbles in a hex string""" |
| 75 | return ''.join([x+y for x, y in zip(s[1::2], s[0::2])]) |
| 76 | |
| 77 | |
| 78 | def rpad(s: str, l: int, c='f') -> str: |
| 79 | """pad string on the right side. |
| 80 | Args: |
| 81 | s : string to pad |
| 82 | l : total length to pad to |
| 83 | c : padding character |
| 84 | Returns: |
| 85 | String 's' padded with as many 'c' as needed to reach total length of 'l' |
| 86 | """ |
| 87 | return s + c * (l - len(s)) |
| 88 | |
| 89 | |
| 90 | def lpad(s: str, l: int, c='f') -> str: |
| 91 | """pad string on the left side. |
| 92 | Args: |
| 93 | s : string to pad |
| 94 | l : total length to pad to |
| 95 | c : padding character |
| 96 | Returns: |
| 97 | String 's' padded with as many 'c' as needed to reach total length of 'l' |
| 98 | """ |
| 99 | return c * (l - len(s)) + s |
| 100 | |
| 101 | |
| 102 | def half_round_up(n: int) -> int: |
| 103 | return (n + 1)//2 |
| 104 | |
| 105 | |
| 106 | def str_sanitize(s: str) -> str: |
| 107 | """replace all non printable chars, line breaks and whitespaces, with ' ', make sure that |
| 108 | there are no whitespaces at the end and at the beginning of the string. |
| 109 | |
| 110 | Args: |
| 111 | s : string to sanitize |
| 112 | Returns: |
| 113 | filtered result of string 's' |
| 114 | """ |
| 115 | |
| 116 | chars_to_keep = string.digits + string.ascii_letters + string.punctuation |
| 117 | res = ''.join([c if c in chars_to_keep else ' ' for c in s]) |
| 118 | return res.strip() |
Philipp Maier | 796ca3d | 2021-11-01 17:13:57 +0100 | [diff] [blame] | 119 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 120 | ######################################################################### |
Harald Welte | 9f3b44d | 2021-05-04 18:18:09 +0200 | [diff] [blame] | 121 | # poor man's COMPREHENSION-TLV decoder. |
| 122 | ######################################################################### |
| 123 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 124 | |
| 125 | def comprehensiontlv_parse_tag_raw(binary: bytes) -> Tuple[int, bytes]: |
Harald Welte | 6912b1b | 2021-05-24 23:16:44 +0200 | [diff] [blame] | 126 | """Parse a single Tag according to ETSI TS 101 220 Section 7.1.1""" |
| 127 | if binary[0] in [0x00, 0x80, 0xff]: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 128 | raise ValueError("Found illegal value 0x%02x in %s" % |
| 129 | (binary[0], binary)) |
Harald Welte | 6912b1b | 2021-05-24 23:16:44 +0200 | [diff] [blame] | 130 | if binary[0] == 0x7f: |
| 131 | # three-byte tag |
| 132 | tag = binary[0] << 16 | binary[1] << 8 | binary[2] |
| 133 | return (tag, binary[3:]) |
| 134 | elif binary[0] == 0xff: |
| 135 | return None, binary |
| 136 | else: |
| 137 | # single byte tag |
| 138 | tag = binary[0] |
| 139 | return (tag, binary[1:]) |
| 140 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 141 | |
| 142 | def comprehensiontlv_parse_tag(binary: bytes) -> Tuple[dict, bytes]: |
Harald Welte | 9f3b44d | 2021-05-04 18:18:09 +0200 | [diff] [blame] | 143 | """Parse a single Tag according to ETSI TS 101 220 Section 7.1.1""" |
| 144 | if binary[0] in [0x00, 0x80, 0xff]: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 145 | raise ValueError("Found illegal value 0x%02x in %s" % |
| 146 | (binary[0], binary)) |
Harald Welte | 9f3b44d | 2021-05-04 18:18:09 +0200 | [diff] [blame] | 147 | if binary[0] == 0x7f: |
| 148 | # three-byte tag |
| 149 | tag = (binary[1] & 0x7f) << 8 |
| 150 | tag |= binary[2] |
| 151 | compr = True if binary[1] & 0x80 else False |
| 152 | return ({'comprehension': compr, 'tag': tag}, binary[3:]) |
| 153 | else: |
| 154 | # single byte tag |
| 155 | tag = binary[0] & 0x7f |
| 156 | compr = True if binary[0] & 0x80 else False |
| 157 | return ({'comprehension': compr, 'tag': tag}, binary[1:]) |
| 158 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 159 | |
Harald Welte | 9f3b44d | 2021-05-04 18:18:09 +0200 | [diff] [blame] | 160 | def comprehensiontlv_encode_tag(tag) -> bytes: |
| 161 | """Encode a single Tag according to ETSI TS 101 220 Section 7.1.1""" |
| 162 | # permit caller to specify tag also as integer value |
| 163 | if isinstance(tag, int): |
| 164 | compr = True if tag < 0xff and tag & 0x80 else False |
| 165 | tag = {'tag': tag, 'comprehension': compr} |
| 166 | compr = tag.get('comprehension', False) |
| 167 | if tag['tag'] in [0x00, 0x80, 0xff] or tag['tag'] > 0xff: |
| 168 | # 3-byte format |
Vadim Yanitskiy | dbd5ed6 | 2021-11-05 16:20:52 +0300 | [diff] [blame] | 169 | byte3 = tag['tag'] & 0xff |
Harald Welte | 9f3b44d | 2021-05-04 18:18:09 +0200 | [diff] [blame] | 170 | byte2 = (tag['tag'] >> 8) & 0x7f |
| 171 | if compr: |
| 172 | byte2 |= 0x80 |
| 173 | return b'\x7f' + byte2.to_bytes(1, 'big') + byte3.to_bytes(1, 'big') |
| 174 | else: |
| 175 | # 1-byte format |
| 176 | ret = tag['tag'] |
| 177 | if compr: |
| 178 | ret |= 0x80 |
| 179 | return ret.to_bytes(1, 'big') |
| 180 | |
| 181 | # length value coding is equal to BER-TLV |
| 182 | |
Harald Welte | 6912b1b | 2021-05-24 23:16:44 +0200 | [diff] [blame] | 183 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 184 | def comprehensiontlv_parse_one(binary: bytes) -> Tuple[dict, int, bytes, bytes]: |
| 185 | """Parse a single TLV IE at the start of the given binary data. |
| 186 | Args: |
| 187 | binary : binary input data of BER-TLV length field |
| 188 | Returns: |
| 189 | Tuple of (tag:dict, len:int, remainder:bytes) |
| 190 | """ |
| 191 | (tagdict, remainder) = comprehensiontlv_parse_tag(binary) |
| 192 | (length, remainder) = bertlv_parse_len(remainder) |
| 193 | value = remainder[:length] |
| 194 | remainder = remainder[length:] |
| 195 | return (tagdict, length, value, remainder) |
Harald Welte | 6912b1b | 2021-05-24 23:16:44 +0200 | [diff] [blame] | 196 | |
Harald Welte | 9f3b44d | 2021-05-04 18:18:09 +0200 | [diff] [blame] | 197 | |
| 198 | ######################################################################### |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 199 | # poor man's BER-TLV decoder. To be a more sophisticated OO library later |
| 200 | ######################################################################### |
| 201 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 202 | def bertlv_parse_tag_raw(binary: bytes) -> Tuple[int, bytes]: |
| 203 | """Get a single raw Tag from start of input according to ITU-T X.690 8.1.2 |
| 204 | Args: |
| 205 | binary : binary input data of BER-TLV length field |
| 206 | Returns: |
| 207 | Tuple of (tag:int, remainder:bytes) |
| 208 | """ |
| 209 | # check for FF padding at the end, as customary in SIM card files |
| 210 | if binary[0] == 0xff and len(binary) == 1 or binary[0] == 0xff and binary[1] == 0xff: |
| 211 | return None, binary |
| 212 | tag = binary[0] & 0x1f |
| 213 | if tag <= 30: |
| 214 | return binary[0], binary[1:] |
| 215 | else: # multi-byte tag |
| 216 | tag = binary[0] |
| 217 | i = 1 |
| 218 | last = False |
| 219 | while not last: |
| 220 | last = False if binary[i] & 0x80 else True |
| 221 | tag <<= 8 |
| 222 | tag |= binary[i] |
| 223 | i += 1 |
| 224 | return tag, binary[i:] |
Harald Welte | 6912b1b | 2021-05-24 23:16:44 +0200 | [diff] [blame] | 225 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 226 | |
| 227 | def bertlv_parse_tag(binary: bytes) -> Tuple[dict, bytes]: |
| 228 | """Parse a single Tag value according to ITU-T X.690 8.1.2 |
| 229 | Args: |
| 230 | binary : binary input data of BER-TLV length field |
| 231 | Returns: |
| 232 | Tuple of ({class:int, constructed:bool, tag:int}, remainder:bytes) |
| 233 | """ |
| 234 | cls = binary[0] >> 6 |
| 235 | constructed = True if binary[0] & 0x20 else False |
| 236 | tag = binary[0] & 0x1f |
| 237 | if tag <= 30: |
| 238 | return ({'class': cls, 'constructed': constructed, 'tag': tag}, binary[1:]) |
| 239 | else: # multi-byte tag |
| 240 | tag = 0 |
| 241 | i = 1 |
| 242 | last = False |
| 243 | while not last: |
| 244 | last = False if binary[i] & 0x80 else True |
| 245 | tag <<= 7 |
| 246 | tag |= binary[i] & 0x7f |
| 247 | i += 1 |
| 248 | return ({'class': cls, 'constructed': constructed, 'tag': tag}, binary[i:]) |
| 249 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 250 | |
Harald Welte | f0885b1 | 2021-05-24 23:18:59 +0200 | [diff] [blame] | 251 | def bertlv_encode_tag(t) -> bytes: |
| 252 | """Encode a single Tag value according to ITU-T X.690 8.1.2 |
| 253 | """ |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 254 | def get_top7_bits(inp: int) -> Tuple[int, int]: |
Harald Welte | f0885b1 | 2021-05-24 23:18:59 +0200 | [diff] [blame] | 255 | """Get top 7 bits of integer. Returns those 7 bits as integer and the remaining LSBs.""" |
| 256 | remain_bits = inp.bit_length() |
| 257 | if remain_bits >= 7: |
| 258 | bitcnt = 7 |
| 259 | else: |
| 260 | bitcnt = remain_bits |
| 261 | outp = inp >> (remain_bits - bitcnt) |
| 262 | remainder = inp & ~ (inp << (remain_bits - bitcnt)) |
| 263 | return outp, remainder |
| 264 | |
| 265 | if isinstance(t, int): |
| 266 | # FIXME: multiple byte tags |
| 267 | tag = t & 0x1f |
| 268 | constructed = True if t & 0x20 else False |
| 269 | cls = t >> 6 |
| 270 | else: |
| 271 | tag = t['tag'] |
| 272 | constructed = t['constructed'] |
| 273 | cls = t['class'] |
| 274 | if tag <= 30: |
| 275 | t = tag & 0x1f |
| 276 | if constructed: |
| 277 | t |= 0x20 |
| 278 | t |= (cls & 3) << 6 |
| 279 | return bytes([t]) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 280 | else: # multi-byte tag |
Vadim Yanitskiy | dbd5ed6 | 2021-11-05 16:20:52 +0300 | [diff] [blame] | 281 | t = 0x1f |
Harald Welte | f0885b1 | 2021-05-24 23:18:59 +0200 | [diff] [blame] | 282 | if constructed: |
| 283 | t |= 0x20 |
| 284 | t |= (cls & 3) << 6 |
| 285 | tag_bytes = bytes([t]) |
| 286 | remain = tag |
| 287 | while True: |
| 288 | t, remain = get_top7_bits(remain) |
| 289 | if remain: |
| 290 | t |= 0x80 |
| 291 | tag_bytes += bytes([t]) |
| 292 | if not remain: |
| 293 | break |
| 294 | return tag_bytes |
| 295 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 296 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 297 | def bertlv_parse_len(binary: bytes) -> Tuple[int, bytes]: |
| 298 | """Parse a single Length value according to ITU-T X.690 8.1.3; |
| 299 | only the definite form is supported here. |
| 300 | Args: |
| 301 | binary : binary input data of BER-TLV length field |
| 302 | Returns: |
| 303 | Tuple of (length, remainder) |
| 304 | """ |
| 305 | if binary[0] < 0x80: |
| 306 | return (binary[0], binary[1:]) |
| 307 | else: |
| 308 | num_len_oct = binary[0] & 0x7f |
| 309 | length = 0 |
| 310 | for i in range(1, 1+num_len_oct): |
| 311 | length <<= 8 |
| 312 | length |= binary[i] |
| 313 | return (length, binary[1+num_len_oct:]) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 314 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 315 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 316 | def bertlv_encode_len(length: int) -> bytes: |
| 317 | """Encode a single Length value according to ITU-T X.690 8.1.3; |
| 318 | only the definite form is supported here. |
| 319 | Args: |
| 320 | length : length value to be encoded |
| 321 | Returns: |
| 322 | binary output data of BER-TLV length field |
| 323 | """ |
| 324 | if length < 0x80: |
| 325 | return length.to_bytes(1, 'big') |
| 326 | elif length <= 0xff: |
| 327 | return b'\x81' + length.to_bytes(1, 'big') |
| 328 | elif length <= 0xffff: |
| 329 | return b'\x82' + length.to_bytes(2, 'big') |
| 330 | elif length <= 0xffffff: |
| 331 | return b'\x83' + length.to_bytes(3, 'big') |
| 332 | elif length <= 0xffffffff: |
| 333 | return b'\x84' + length.to_bytes(4, 'big') |
| 334 | else: |
| 335 | raise ValueError("Length > 32bits not supported") |
| 336 | |
| 337 | |
| 338 | def bertlv_parse_one(binary: bytes) -> Tuple[dict, int, bytes, bytes]: |
| 339 | """Parse a single TLV IE at the start of the given binary data. |
| 340 | Args: |
| 341 | binary : binary input data of BER-TLV length field |
| 342 | Returns: |
| 343 | Tuple of (tag:dict, len:int, remainder:bytes) |
| 344 | """ |
| 345 | (tagdict, remainder) = bertlv_parse_tag(binary) |
| 346 | (length, remainder) = bertlv_parse_len(remainder) |
| 347 | value = remainder[:length] |
| 348 | remainder = remainder[length:] |
| 349 | return (tagdict, length, value, remainder) |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 350 | |
| 351 | |
Ben Fox-Moore | 0ec1475 | 2018-09-24 15:47:02 +0200 | [diff] [blame] | 352 | # IMSI encoded format: |
| 353 | # For IMSI 0123456789ABCDE: |
| 354 | # |
| 355 | # | byte 1 | 2 upper | 2 lower | 3 upper | 3 lower | ... | 9 upper | 9 lower | |
| 356 | # | length in bytes | 0 | odd/even | 2 | 1 | ... | E | D | |
| 357 | # |
| 358 | # If the IMSI is less than 15 characters, it should be padded with 'f' from the end. |
| 359 | # |
| 360 | # The length is the total number of bytes used to encoded the IMSI. This includes the odd/even |
| 361 | # parity bit. E.g. an IMSI of length 14 is 8 bytes long, not 7, as it uses bytes 2 to 9 to |
| 362 | # encode itself. |
| 363 | # |
| 364 | # Because of this, an odd length IMSI fits exactly into len(imsi) + 1 // 2 bytes, whereas an |
| 365 | # even length IMSI only uses half of the last byte. |
| 366 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 367 | def enc_imsi(imsi: str): |
| 368 | """Converts a string IMSI into the encoded value of the EF""" |
| 369 | l = half_round_up( |
| 370 | len(imsi) + 1) # Required bytes - include space for odd/even indicator |
| 371 | oe = len(imsi) & 1 # Odd (1) / Even (0) |
| 372 | ei = '%02x' % l + swap_nibbles('%01x%s' % ((oe << 3) | 1, rpad(imsi, 15))) |
| 373 | return ei |
Alexander Chemeris | 7be92ff | 2013-07-10 11:18:06 +0400 | [diff] [blame] | 374 | |
Alexander Chemeris | 5e96c3d | 2013-07-04 17:33:33 +0400 | [diff] [blame] | 375 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 376 | def dec_imsi(ef: Hexstr) -> Optional[str]: |
| 377 | """Converts an EF value to the IMSI string representation""" |
| 378 | if len(ef) < 4: |
| 379 | return None |
| 380 | l = int(ef[0:2], 16) * 2 # Length of the IMSI string |
| 381 | l = l - 1 # Encoded length byte includes oe nibble |
| 382 | swapped = swap_nibbles(ef[2:]).rstrip('f') |
| 383 | if len(swapped) < 1: |
| 384 | return None |
| 385 | oe = (int(swapped[0]) >> 3) & 1 # Odd (1) / Even (0) |
| 386 | if not oe: |
| 387 | # if even, only half of last byte was used |
| 388 | l = l-1 |
| 389 | if l != len(swapped) - 1: |
| 390 | return None |
| 391 | imsi = swapped[1:] |
| 392 | return imsi |
Alexander Chemeris | 7be92ff | 2013-07-10 11:18:06 +0400 | [diff] [blame] | 393 | |
Alexander Chemeris | 7be92ff | 2013-07-10 11:18:06 +0400 | [diff] [blame] | 394 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 395 | def dec_iccid(ef: Hexstr) -> str: |
| 396 | return swap_nibbles(ef).strip('f') |
Philipp Maier | 6c5cd80 | 2021-04-23 21:19:36 +0200 | [diff] [blame] | 397 | |
Philipp Maier | 6c5cd80 | 2021-04-23 21:19:36 +0200 | [diff] [blame] | 398 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 399 | def enc_iccid(iccid: str) -> Hexstr: |
| 400 | return swap_nibbles(rpad(iccid, 20)) |
Philipp Maier | 6c5cd80 | 2021-04-23 21:19:36 +0200 | [diff] [blame] | 401 | |
Philipp Maier | 6c5cd80 | 2021-04-23 21:19:36 +0200 | [diff] [blame] | 402 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 403 | def enc_plmn(mcc: Hexstr, mnc: Hexstr) -> Hexstr: |
| 404 | """Converts integer MCC/MNC into 3 bytes for EF""" |
Alexander Chemeris | a5f0ea6 | 2017-07-18 16:48:47 +0300 | [diff] [blame] | 405 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 406 | # Make sure there are no excess whitespaces in the input |
| 407 | # parameters |
| 408 | mcc = mcc.strip() |
| 409 | mnc = mnc.strip() |
| 410 | |
| 411 | # Make sure that MCC/MNC are correctly padded with leading |
| 412 | # zeros or 'F', depending on the length. |
| 413 | if len(mnc) == 0: |
| 414 | mnc = "FFF" |
| 415 | elif len(mnc) == 1: |
farhadh | fec721f | 2023-07-19 15:43:13 +0200 | [diff] [blame] | 416 | mnc = "0" + mnc + "F" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 417 | elif len(mnc) == 2: |
| 418 | mnc += "F" |
| 419 | |
| 420 | if len(mcc) == 0: |
| 421 | mcc = "FFF" |
| 422 | elif len(mcc) == 1: |
| 423 | mcc = "00" + mcc |
| 424 | elif len(mcc) == 2: |
| 425 | mcc = "0" + mcc |
| 426 | |
| 427 | return (mcc[1] + mcc[0]) + (mnc[2] + mcc[2]) + (mnc[1] + mnc[0]) |
| 428 | |
| 429 | |
| 430 | def dec_plmn(threehexbytes: Hexstr) -> dict: |
| 431 | res = {'mcc': "0", 'mnc': "0"} |
| 432 | dec_mcc_from_plmn_str(threehexbytes) |
| 433 | res['mcc'] = dec_mcc_from_plmn_str(threehexbytes) |
| 434 | res['mnc'] = dec_mnc_from_plmn_str(threehexbytes) |
| 435 | return res |
| 436 | |
Harald Welte | d7a7e17 | 2021-04-07 00:30:10 +0200 | [diff] [blame] | 437 | |
Daniel Laszlo Sitzer | 851e9c0 | 2018-12-04 19:40:08 +0100 | [diff] [blame] | 438 | # Accepts hex string representing three bytes |
Daniel Laszlo Sitzer | 851e9c0 | 2018-12-04 19:40:08 +0100 | [diff] [blame] | 439 | |
Philipp Maier | 6c5cd80 | 2021-04-23 21:19:36 +0200 | [diff] [blame] | 440 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 441 | def dec_mcc_from_plmn(plmn: Hexstr) -> int: |
| 442 | ia = h2i(plmn) |
| 443 | digit1 = ia[0] & 0x0F # 1st byte, LSB |
| 444 | digit2 = (ia[0] & 0xF0) >> 4 # 1st byte, MSB |
| 445 | digit3 = ia[1] & 0x0F # 2nd byte, LSB |
| 446 | if digit3 == 0xF and digit2 == 0xF and digit1 == 0xF: |
| 447 | return 0xFFF # 4095 |
| 448 | return derive_mcc(digit1, digit2, digit3) |
Daniel Laszlo Sitzer | 851e9c0 | 2018-12-04 19:40:08 +0100 | [diff] [blame] | 449 | |
Philipp Maier | 6c5cd80 | 2021-04-23 21:19:36 +0200 | [diff] [blame] | 450 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 451 | def dec_mcc_from_plmn_str(plmn: Hexstr) -> str: |
| 452 | digit1 = plmn[1] # 1st byte, LSB |
| 453 | digit2 = plmn[0] # 1st byte, MSB |
| 454 | digit3 = plmn[3] # 2nd byte, LSB |
| 455 | res = digit1 + digit2 + digit3 |
| 456 | return res.upper().strip("F") |
Daniel Laszlo Sitzer | 851e9c0 | 2018-12-04 19:40:08 +0100 | [diff] [blame] | 457 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 458 | |
| 459 | def dec_mnc_from_plmn(plmn: Hexstr) -> int: |
| 460 | ia = h2i(plmn) |
| 461 | digit1 = ia[2] & 0x0F # 3rd byte, LSB |
| 462 | digit2 = (ia[2] & 0xF0) >> 4 # 3rd byte, MSB |
| 463 | digit3 = (ia[1] & 0xF0) >> 4 # 2nd byte, MSB |
| 464 | if digit3 == 0xF and digit2 == 0xF and digit1 == 0xF: |
| 465 | return 0xFFF # 4095 |
| 466 | return derive_mnc(digit1, digit2, digit3) |
| 467 | |
| 468 | |
| 469 | def dec_mnc_from_plmn_str(plmn: Hexstr) -> str: |
| 470 | digit1 = plmn[5] # 3rd byte, LSB |
| 471 | digit2 = plmn[4] # 3rd byte, MSB |
| 472 | digit3 = plmn[2] # 2nd byte, MSB |
| 473 | res = digit1 + digit2 + digit3 |
| 474 | return res.upper().strip("F") |
| 475 | |
| 476 | |
| 477 | def dec_act(twohexbytes: Hexstr) -> List[str]: |
| 478 | act_list = [ |
| 479 | {'bit': 15, 'name': "UTRAN"}, |
| 480 | {'bit': 14, 'name': "E-UTRAN"}, |
| 481 | {'bit': 11, 'name': "NG-RAN"}, |
| 482 | {'bit': 7, 'name': "GSM"}, |
| 483 | {'bit': 6, 'name': "GSM COMPACT"}, |
| 484 | {'bit': 5, 'name': "cdma2000 HRPD"}, |
| 485 | {'bit': 4, 'name': "cdma2000 1xRTT"}, |
| 486 | ] |
| 487 | ia = h2i(twohexbytes) |
| 488 | u16t = (ia[0] << 8) | ia[1] |
| 489 | sel = [] |
| 490 | for a in act_list: |
| 491 | if u16t & (1 << a['bit']): |
| 492 | if a['name'] == "E-UTRAN": |
| 493 | # The Access technology identifier of E-UTRAN |
| 494 | # allows a more detailed specification: |
| 495 | if u16t & (1 << 13) and u16t & (1 << 12): |
| 496 | sel.append("E-UTRAN WB-S1") |
| 497 | sel.append("E-UTRAN NB-S1") |
| 498 | elif u16t & (1 << 13): |
| 499 | sel.append("E-UTRAN WB-S1") |
| 500 | elif u16t & (1 << 12): |
| 501 | sel.append("E-UTRAN NB-S1") |
| 502 | else: |
| 503 | sel.append("E-UTRAN") |
| 504 | else: |
| 505 | sel.append(a['name']) |
| 506 | return sel |
| 507 | |
| 508 | |
| 509 | def dec_xplmn_w_act(fivehexbytes: Hexstr) -> Dict[str, Any]: |
| 510 | res = {'mcc': "0", 'mnc': "0", 'act': []} |
| 511 | plmn_chars = 6 |
| 512 | act_chars = 4 |
| 513 | # first three bytes (six ascii hex chars) |
| 514 | plmn_str = fivehexbytes[:plmn_chars] |
| 515 | # two bytes after first three bytes |
| 516 | act_str = fivehexbytes[plmn_chars:plmn_chars + act_chars] |
| 517 | res['mcc'] = dec_mcc_from_plmn_str(plmn_str) |
| 518 | res['mnc'] = dec_mnc_from_plmn_str(plmn_str) |
| 519 | res['act'] = dec_act(act_str) |
| 520 | return res |
| 521 | |
Daniel Laszlo Sitzer | 851e9c0 | 2018-12-04 19:40:08 +0100 | [diff] [blame] | 522 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 523 | def dec_xplmn(threehexbytes: Hexstr) -> dict: |
| 524 | res = {'mcc': 0, 'mnc': 0, 'act': []} |
| 525 | plmn_chars = 6 |
| 526 | # first three bytes (six ascii hex chars) |
| 527 | plmn_str = threehexbytes[:plmn_chars] |
Matan Perelman | 60951b0 | 2023-06-01 17:39:04 +0300 | [diff] [blame] | 528 | res['mcc'] = dec_mcc_from_plmn_str(plmn_str) |
| 529 | res['mnc'] = dec_mnc_from_plmn_str(plmn_str) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 530 | return res |
Harald Welte | ca67394 | 2020-06-03 15:19:40 +0200 | [diff] [blame] | 531 | |
Alexander Chemeris | 19fffa1 | 2018-01-11 13:06:43 +0900 | [diff] [blame] | 532 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 533 | def derive_milenage_opc(ki_hex: Hexstr, op_hex: Hexstr) -> Hexstr: |
| 534 | """ |
| 535 | Run the milenage algorithm to calculate OPC from Ki and OP |
| 536 | """ |
Harald Welte | d75fa3f | 2023-05-31 20:47:55 +0200 | [diff] [blame] | 537 | from Cryptodome.Cipher import AES |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 538 | # pylint: disable=no-name-in-module |
Harald Welte | d75fa3f | 2023-05-31 20:47:55 +0200 | [diff] [blame] | 539 | from Cryptodome.Util.strxor import strxor |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 540 | from pySim.utils import b2h |
| 541 | |
| 542 | # We pass in hex string and now need to work on bytes |
| 543 | ki_bytes = bytes(h2b(ki_hex)) |
| 544 | op_bytes = bytes(h2b(op_hex)) |
| 545 | aes = AES.new(ki_bytes, AES.MODE_ECB) |
| 546 | opc_bytes = aes.encrypt(op_bytes) |
| 547 | return b2h(strxor(opc_bytes, op_bytes)) |
| 548 | |
Alexander Chemeris | 19fffa1 | 2018-01-11 13:06:43 +0900 | [diff] [blame] | 549 | |
Harald Welte | 5225557 | 2021-04-03 09:56:32 +0200 | [diff] [blame] | 550 | def calculate_luhn(cc) -> int: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 551 | """ |
| 552 | Calculate Luhn checksum used in e.g. ICCID and IMEI |
| 553 | """ |
| 554 | num = list(map(int, str(cc))) |
| 555 | check_digit = 10 - sum(num[-2::-2] + [sum(divmod(d * 2, 10)) |
| 556 | for d in num[::-2]]) % 10 |
| 557 | return 0 if check_digit == 10 else check_digit |
Philipp Maier | 7592eee | 2019-09-12 13:03:23 +0200 | [diff] [blame] | 558 | |
Philipp Maier | 7592eee | 2019-09-12 13:03:23 +0200 | [diff] [blame] | 559 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 560 | def mcc_from_imsi(imsi: str) -> Optional[str]: |
| 561 | """ |
| 562 | Derive the MCC (Mobile Country Code) from the first three digits of an IMSI |
| 563 | """ |
| 564 | if imsi == None: |
| 565 | return None |
Philipp Maier | 7592eee | 2019-09-12 13:03:23 +0200 | [diff] [blame] | 566 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 567 | if len(imsi) > 3: |
| 568 | return imsi[:3] |
| 569 | else: |
| 570 | return None |
Philipp Maier | 7592eee | 2019-09-12 13:03:23 +0200 | [diff] [blame] | 571 | |
Supreeth Herle | d24f163 | 2019-11-30 10:37:09 +0100 | [diff] [blame] | 572 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 573 | def mnc_from_imsi(imsi: str, long: bool = False) -> Optional[str]: |
| 574 | """ |
| 575 | Derive the MNC (Mobile Country Code) from the 4th to 6th digit of an IMSI |
| 576 | """ |
| 577 | if imsi == None: |
| 578 | return None |
Supreeth Herle | d24f163 | 2019-11-30 10:37:09 +0100 | [diff] [blame] | 579 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 580 | if len(imsi) > 3: |
| 581 | if long: |
| 582 | return imsi[3:6] |
| 583 | else: |
| 584 | return imsi[3:5] |
| 585 | else: |
| 586 | return None |
Supreeth Herle | d24f163 | 2019-11-30 10:37:09 +0100 | [diff] [blame] | 587 | |
Supreeth Herle | d24f163 | 2019-11-30 10:37:09 +0100 | [diff] [blame] | 588 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 589 | def derive_mcc(digit1: int, digit2: int, digit3: int) -> int: |
| 590 | """ |
| 591 | Derive decimal representation of the MCC (Mobile Country Code) |
| 592 | from three given digits. |
| 593 | """ |
Supreeth Herle | d24f163 | 2019-11-30 10:37:09 +0100 | [diff] [blame] | 594 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 595 | mcc = 0 |
Supreeth Herle | d24f163 | 2019-11-30 10:37:09 +0100 | [diff] [blame] | 596 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 597 | if digit1 != 0x0f: |
| 598 | mcc += digit1 * 100 |
| 599 | if digit2 != 0x0f: |
| 600 | mcc += digit2 * 10 |
| 601 | if digit3 != 0x0f: |
| 602 | mcc += digit3 |
Supreeth Herle | d24f163 | 2019-11-30 10:37:09 +0100 | [diff] [blame] | 603 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 604 | return mcc |
Supreeth Herle | d24f163 | 2019-11-30 10:37:09 +0100 | [diff] [blame] | 605 | |
Supreeth Herle | d24f163 | 2019-11-30 10:37:09 +0100 | [diff] [blame] | 606 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 607 | def derive_mnc(digit1: int, digit2: int, digit3: int = 0x0f) -> int: |
| 608 | """ |
| 609 | Derive decimal representation of the MNC (Mobile Network Code) |
| 610 | from two or (optionally) three given digits. |
| 611 | """ |
Supreeth Herle | 4b1c763 | 2019-12-22 09:00:59 +0100 | [diff] [blame] | 612 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 613 | mnc = 0 |
Supreeth Herle | 4b1c763 | 2019-12-22 09:00:59 +0100 | [diff] [blame] | 614 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 615 | # 3-rd digit is optional for the MNC. If present |
| 616 | # the algorythm is the same as for the MCC. |
| 617 | if digit3 != 0x0f: |
| 618 | return derive_mcc(digit1, digit2, digit3) |
Supreeth Herle | 4b1c763 | 2019-12-22 09:00:59 +0100 | [diff] [blame] | 619 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 620 | if digit1 != 0x0f: |
| 621 | mnc += digit1 * 10 |
| 622 | if digit2 != 0x0f: |
| 623 | mnc += digit2 |
Supreeth Herle | 4b1c763 | 2019-12-22 09:00:59 +0100 | [diff] [blame] | 624 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 625 | return mnc |
Supreeth Herle | 4b1c763 | 2019-12-22 09:00:59 +0100 | [diff] [blame] | 626 | |
Supreeth Herle | 4b1c763 | 2019-12-22 09:00:59 +0100 | [diff] [blame] | 627 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 628 | def dec_msisdn(ef_msisdn: Hexstr) -> Optional[Tuple[int, int, Optional[str]]]: |
| 629 | """ |
| 630 | Decode MSISDN from EF.MSISDN or EF.ADN (same structure). |
| 631 | See 3GPP TS 31.102, section 4.2.26 and 4.4.2.3. |
| 632 | """ |
Supreeth Herle | 4b1c763 | 2019-12-22 09:00:59 +0100 | [diff] [blame] | 633 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 634 | # Convert from str to (kind of) 'bytes' |
| 635 | ef_msisdn = h2b(ef_msisdn) |
Supreeth Herle | 4b1c763 | 2019-12-22 09:00:59 +0100 | [diff] [blame] | 636 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 637 | # Make sure mandatory fields are present |
| 638 | if len(ef_msisdn) < 14: |
| 639 | raise ValueError("EF.MSISDN is too short") |
Supreeth Herle | 4b1c763 | 2019-12-22 09:00:59 +0100 | [diff] [blame] | 640 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 641 | # Skip optional Alpha Identifier |
| 642 | xlen = len(ef_msisdn) - 14 |
| 643 | msisdn_lhv = ef_msisdn[xlen:] |
Supreeth Herle | 5a54101 | 2019-12-22 08:59:16 +0100 | [diff] [blame] | 644 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 645 | # Parse the length (in bytes) of the BCD encoded number |
| 646 | bcd_len = msisdn_lhv[0] |
| 647 | # BCD length = length of dial num (max. 10 bytes) + 1 byte ToN and NPI |
| 648 | if bcd_len == 0xff: |
| 649 | return None |
| 650 | elif bcd_len > 11 or bcd_len < 1: |
| 651 | raise ValueError( |
| 652 | "Length of MSISDN (%d bytes) is out of range" % bcd_len) |
Supreeth Herle | 5a54101 | 2019-12-22 08:59:16 +0100 | [diff] [blame] | 653 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 654 | # Parse ToN / NPI |
| 655 | ton = (msisdn_lhv[1] >> 4) & 0x07 |
| 656 | npi = msisdn_lhv[1] & 0x0f |
| 657 | bcd_len -= 1 |
Supreeth Herle | 5a54101 | 2019-12-22 08:59:16 +0100 | [diff] [blame] | 658 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 659 | # No MSISDN? |
| 660 | if not bcd_len: |
| 661 | return (npi, ton, None) |
Philipp Maier | b46cb3f | 2021-04-20 22:38:21 +0200 | [diff] [blame] | 662 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 663 | msisdn = swap_nibbles(b2h(msisdn_lhv[2:][:bcd_len])).rstrip('f') |
| 664 | # International number 10.5.118/3GPP TS 24.008 |
| 665 | if ton == 0x01: |
| 666 | msisdn = '+' + msisdn |
Supreeth Herle | 5a54101 | 2019-12-22 08:59:16 +0100 | [diff] [blame] | 667 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 668 | return (npi, ton, msisdn) |
Philipp Maier | b46cb3f | 2021-04-20 22:38:21 +0200 | [diff] [blame] | 669 | |
Supreeth Herle | 5a54101 | 2019-12-22 08:59:16 +0100 | [diff] [blame] | 670 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 671 | def enc_msisdn(msisdn: str, npi: int = 0x01, ton: int = 0x03) -> Hexstr: |
| 672 | """ |
| 673 | Encode MSISDN as LHV so it can be stored to EF.MSISDN. |
| 674 | See 3GPP TS 31.102, section 4.2.26 and 4.4.2.3. (The result |
| 675 | will not contain the optional Alpha Identifier at the beginning.) |
Supreeth Herle | 5a54101 | 2019-12-22 08:59:16 +0100 | [diff] [blame] | 676 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 677 | Default NPI / ToN values: |
| 678 | - NPI: ISDN / telephony numbering plan (E.164 / E.163), |
| 679 | - ToN: network specific or international number (if starts with '+'). |
| 680 | """ |
| 681 | |
| 682 | # If no MSISDN is supplied then encode the file contents as all "ff" |
| 683 | if msisdn == "" or msisdn == "+": |
| 684 | return "ff" * 14 |
| 685 | |
| 686 | # Leading '+' indicates International Number |
| 687 | if msisdn[0] == '+': |
| 688 | msisdn = msisdn[1:] |
| 689 | ton = 0x01 |
| 690 | |
| 691 | # An MSISDN must not exceed 20 digits |
| 692 | if len(msisdn) > 20: |
| 693 | raise ValueError("msisdn must not be longer than 20 digits") |
| 694 | |
| 695 | # Append 'f' padding if number of digits is odd |
| 696 | if len(msisdn) % 2 > 0: |
| 697 | msisdn += 'f' |
| 698 | |
| 699 | # BCD length also includes NPI/ToN header |
| 700 | bcd_len = len(msisdn) // 2 + 1 |
| 701 | npi_ton = (npi & 0x0f) | ((ton & 0x07) << 4) | 0x80 |
| 702 | bcd = rpad(swap_nibbles(msisdn), 10 * 2) # pad to 10 octets |
| 703 | |
| 704 | return ('%02x' % bcd_len) + ('%02x' % npi_ton) + bcd + ("ff" * 2) |
Philipp Maier | b46cb3f | 2021-04-20 22:38:21 +0200 | [diff] [blame] | 705 | |
Supreeth Herle | 441c4a7 | 2020-03-24 10:19:15 +0100 | [diff] [blame] | 706 | |
Supreeth Herle | 9837055 | 2020-05-11 09:04:41 +0200 | [diff] [blame] | 707 | def first_TLV_parser(bytelist): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 708 | ''' |
| 709 | first_TLV_parser([0xAA, 0x02, 0xAB, 0xCD, 0xFF, 0x00]) -> (170, 2, [171, 205]) |
Supreeth Herle | 9837055 | 2020-05-11 09:04:41 +0200 | [diff] [blame] | 710 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 711 | parses first TLV format record in a list of bytelist |
| 712 | returns a 3-Tuple: Tag, Length, Value |
| 713 | Value is a list of bytes |
| 714 | parsing of length is ETSI'style 101.220 |
| 715 | ''' |
| 716 | Tag = bytelist[0] |
| 717 | if bytelist[1] == 0xFF: |
| 718 | Len = bytelist[2]*256 + bytelist[3] |
| 719 | Val = bytelist[4:4+Len] |
| 720 | else: |
| 721 | Len = bytelist[1] |
| 722 | Val = bytelist[2:2+Len] |
| 723 | return (Tag, Len, Val) |
| 724 | |
Supreeth Herle | 9837055 | 2020-05-11 09:04:41 +0200 | [diff] [blame] | 725 | |
| 726 | def TLV_parser(bytelist): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 727 | ''' |
| 728 | TLV_parser([0xAA, ..., 0xFF]) -> [(T, L, [V]), (T, L, [V]), ...] |
Supreeth Herle | 9837055 | 2020-05-11 09:04:41 +0200 | [diff] [blame] | 729 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 730 | loops on the input list of bytes with the "first_TLV_parser()" function |
| 731 | returns a list of 3-Tuples |
| 732 | ''' |
| 733 | ret = [] |
| 734 | while len(bytelist) > 0: |
| 735 | T, L, V = first_TLV_parser(bytelist) |
| 736 | if T == 0xFF: |
| 737 | # padding bytes |
| 738 | break |
| 739 | ret.append((T, L, V)) |
| 740 | # need to manage length of L |
| 741 | if L > 0xFE: |
| 742 | bytelist = bytelist[L+4:] |
| 743 | else: |
| 744 | bytelist = bytelist[L+2:] |
| 745 | return ret |
| 746 | |
Supreeth Herle | d572ede | 2020-03-22 09:55:04 +0100 | [diff] [blame] | 747 | |
Supreeth Herle | 3b342c2 | 2020-03-24 16:15:02 +0100 | [diff] [blame] | 748 | def dec_addr_tlv(hexstr): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 749 | """ |
| 750 | Decode hex string to get EF.P-CSCF Address or EF.ePDGId or EF.ePDGIdEm. |
| 751 | See 3GPP TS 31.102 version 13.4.0 Release 13, section 4.2.8, 4.2.102 and 4.2.104. |
| 752 | """ |
Supreeth Herle | d572ede | 2020-03-22 09:55:04 +0100 | [diff] [blame] | 753 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 754 | # Convert from hex str to int bytes list |
| 755 | addr_tlv_bytes = h2i(hexstr) |
Supreeth Herle | d572ede | 2020-03-22 09:55:04 +0100 | [diff] [blame] | 756 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 757 | # Get list of tuples containing parsed TLVs |
| 758 | tlvs = TLV_parser(addr_tlv_bytes) |
Supreeth Herle | d572ede | 2020-03-22 09:55:04 +0100 | [diff] [blame] | 759 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 760 | for tlv in tlvs: |
| 761 | # tlv = (T, L, [V]) |
| 762 | # T = Tag |
| 763 | # L = Length |
| 764 | # [V] = List of value |
Supreeth Herle | d572ede | 2020-03-22 09:55:04 +0100 | [diff] [blame] | 765 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 766 | # Invalid Tag value scenario |
| 767 | if tlv[0] != 0x80: |
| 768 | continue |
Supreeth Herle | d572ede | 2020-03-22 09:55:04 +0100 | [diff] [blame] | 769 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 770 | # Empty field - Zero length |
| 771 | if tlv[1] == 0: |
| 772 | continue |
Supreeth Herle | d6a5ec5 | 2020-06-01 12:27:51 +0200 | [diff] [blame] | 773 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 774 | # First byte in the value has the address type |
| 775 | addr_type = tlv[2][0] |
| 776 | # TODO: Support parsing of IPv6 |
| 777 | # Address Type: 0x00 (FQDN), 0x01 (IPv4), 0x02 (IPv6), other (Reserved) |
| 778 | if addr_type == 0x00: # FQDN |
| 779 | # Skip address tye byte i.e. first byte in value list |
| 780 | content = tlv[2][1:] |
| 781 | return (i2s(content), '00') |
Philipp Maier | be18f2a | 2021-04-30 15:00:27 +0200 | [diff] [blame] | 782 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 783 | elif addr_type == 0x01: # IPv4 |
| 784 | # Skip address tye byte i.e. first byte in value list |
| 785 | # Skip the unused byte in Octect 4 after address type byte as per 3GPP TS 31.102 |
| 786 | ipv4 = tlv[2][2:] |
| 787 | content = '.'.join(str(x) for x in ipv4) |
| 788 | return (content, '01') |
| 789 | else: |
| 790 | raise ValueError("Invalid address type") |
Supreeth Herle | d572ede | 2020-03-22 09:55:04 +0100 | [diff] [blame] | 791 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 792 | return (None, None) |
| 793 | |
Philipp Maier | ff84c23 | 2020-05-12 17:24:18 +0200 | [diff] [blame] | 794 | |
Supreeth Herle | 3b342c2 | 2020-03-24 16:15:02 +0100 | [diff] [blame] | 795 | def enc_addr_tlv(addr, addr_type='00'): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 796 | """ |
| 797 | Encode address TLV object used in EF.P-CSCF Address, EF.ePDGId and EF.ePDGIdEm. |
| 798 | See 3GPP TS 31.102 version 13.4.0 Release 13, section 4.2.8, 4.2.102 and 4.2.104. |
Supreeth Herle | 3c0bd7a | 2020-03-23 11:59:33 +0100 | [diff] [blame] | 799 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 800 | Default values: |
| 801 | - addr_type: 00 - FQDN format of Address |
| 802 | """ |
Supreeth Herle | 3c0bd7a | 2020-03-23 11:59:33 +0100 | [diff] [blame] | 803 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 804 | s = "" |
Supreeth Herle | 3c0bd7a | 2020-03-23 11:59:33 +0100 | [diff] [blame] | 805 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 806 | # TODO: Encoding of IPv6 address |
| 807 | if addr_type == '00': # FQDN |
| 808 | hex_str = s2h(addr) |
| 809 | s += '80' + ('%02x' % ((len(hex_str)//2)+1)) + '00' + hex_str |
| 810 | elif addr_type == '01': # IPv4 |
| 811 | ipv4_list = addr.split('.') |
| 812 | ipv4_str = "" |
| 813 | for i in ipv4_list: |
| 814 | ipv4_str += ('%02x' % (int(i))) |
Supreeth Herle | 654eca7 | 2020-03-25 14:25:38 +0100 | [diff] [blame] | 815 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 816 | # Unused bytes shall be set to 'ff'. i.e 4th Octet after Address Type is not used |
| 817 | # IPv4 Address is in octet 5 to octet 8 of the TLV data object |
| 818 | s += '80' + ('%02x' % ((len(ipv4_str)//2)+2)) + '01' + 'ff' + ipv4_str |
Supreeth Herle | 3c0bd7a | 2020-03-23 11:59:33 +0100 | [diff] [blame] | 819 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 820 | return s |
Supreeth Herle | 3c0bd7a | 2020-03-23 11:59:33 +0100 | [diff] [blame] | 821 | |
Philipp Maier | 4723650 | 2021-03-09 21:28:25 +0100 | [diff] [blame] | 822 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 823 | def is_hex(string: str, minlen: int = 2, maxlen: Optional[int] = None) -> bool: |
| 824 | """ |
| 825 | Check if a string is a valid hexstring |
| 826 | """ |
Philipp Maier | 4723650 | 2021-03-09 21:28:25 +0100 | [diff] [blame] | 827 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 828 | # Filter obviously bad strings |
| 829 | if not string: |
| 830 | return False |
| 831 | if len(string) < minlen or minlen < 2: |
| 832 | return False |
| 833 | if len(string) % 2: |
| 834 | return False |
| 835 | if maxlen and len(string) > maxlen: |
| 836 | return False |
Philipp Maier | 4723650 | 2021-03-09 21:28:25 +0100 | [diff] [blame] | 837 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 838 | # Try actual encoding to be sure |
| 839 | try: |
| 840 | try_encode = h2b(string) |
| 841 | return True |
| 842 | except: |
| 843 | return False |
Philipp Maier | e8536c0 | 2020-05-11 21:35:01 +0200 | [diff] [blame] | 844 | |
Philipp Maier | e8536c0 | 2020-05-11 21:35:01 +0200 | [diff] [blame] | 845 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 846 | def sanitize_pin_adm(pin_adm, pin_adm_hex=None) -> Hexstr: |
| 847 | """ |
| 848 | The ADM pin can be supplied either in its hexadecimal form or as |
| 849 | ascii string. This function checks the supplied opts parameter and |
| 850 | returns the pin_adm as hex encoded string, regardless in which form |
| 851 | it was originally supplied by the user |
| 852 | """ |
Philipp Maier | e8536c0 | 2020-05-11 21:35:01 +0200 | [diff] [blame] | 853 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 854 | if pin_adm is not None: |
| 855 | if len(pin_adm) <= 8: |
| 856 | pin_adm = ''.join(['%02x' % (ord(x)) for x in pin_adm]) |
| 857 | pin_adm = rpad(pin_adm, 16) |
Philipp Maier | e8536c0 | 2020-05-11 21:35:01 +0200 | [diff] [blame] | 858 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 859 | else: |
| 860 | raise ValueError("PIN-ADM needs to be <=8 digits (ascii)") |
| 861 | |
| 862 | if pin_adm_hex is not None: |
| 863 | if len(pin_adm_hex) == 16: |
| 864 | pin_adm = pin_adm_hex |
| 865 | # Ensure that it's hex-encoded |
| 866 | try: |
| 867 | try_encode = h2b(pin_adm) |
| 868 | except ValueError: |
| 869 | raise ValueError( |
| 870 | "PIN-ADM needs to be hex encoded using this option") |
| 871 | else: |
| 872 | raise ValueError( |
| 873 | "PIN-ADM needs to be exactly 16 digits (hex encoded)") |
| 874 | |
| 875 | return pin_adm |
| 876 | |
Philipp Maier | e8536c0 | 2020-05-11 21:35:01 +0200 | [diff] [blame] | 877 | |
Supreeth Herle | 556b0fe | 2020-03-25 11:26:57 +0100 | [diff] [blame] | 878 | def get_addr_type(addr): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 879 | """ |
| 880 | Validates the given address and returns it's type (FQDN or IPv4 or IPv6) |
| 881 | Return: 0x00 (FQDN), 0x01 (IPv4), 0x02 (IPv6), None (Bad address argument given) |
Supreeth Herle | 556b0fe | 2020-03-25 11:26:57 +0100 | [diff] [blame] | 882 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 883 | TODO: Handle IPv6 |
| 884 | """ |
Supreeth Herle | 556b0fe | 2020-03-25 11:26:57 +0100 | [diff] [blame] | 885 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 886 | # Empty address string |
| 887 | if not len(addr): |
| 888 | return None |
Supreeth Herle | 556b0fe | 2020-03-25 11:26:57 +0100 | [diff] [blame] | 889 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 890 | addr_list = addr.split('.') |
Supreeth Herle | 556b0fe | 2020-03-25 11:26:57 +0100 | [diff] [blame] | 891 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 892 | # Check for IPv4/IPv6 |
| 893 | try: |
| 894 | import ipaddress |
| 895 | # Throws ValueError if addr is not correct |
| 896 | ipa = ipaddress.ip_address(addr) |
Supreeth Herle | 556b0fe | 2020-03-25 11:26:57 +0100 | [diff] [blame] | 897 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 898 | if ipa.version == 4: |
| 899 | return 0x01 |
| 900 | elif ipa.version == 6: |
| 901 | return 0x02 |
| 902 | except Exception as e: |
| 903 | invalid_ipv4 = True |
| 904 | for i in addr_list: |
| 905 | # Invalid IPv4 may qualify for a valid FQDN, so make check here |
| 906 | # e.g. 172.24.15.300 |
| 907 | import re |
| 908 | if not re.match('^[0-9_]+$', i): |
| 909 | invalid_ipv4 = False |
| 910 | break |
Supreeth Herle | 556b0fe | 2020-03-25 11:26:57 +0100 | [diff] [blame] | 911 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 912 | if invalid_ipv4: |
| 913 | return None |
Supreeth Herle | 556b0fe | 2020-03-25 11:26:57 +0100 | [diff] [blame] | 914 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 915 | fqdn_flag = True |
| 916 | for i in addr_list: |
| 917 | # Only Alpha-numeric characters and hyphen - RFC 1035 |
| 918 | import re |
| 919 | if not re.match("^[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)?$", i): |
| 920 | fqdn_flag = False |
| 921 | break |
Supreeth Herle | 556b0fe | 2020-03-25 11:26:57 +0100 | [diff] [blame] | 922 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 923 | # FQDN |
| 924 | if fqdn_flag: |
| 925 | return 0x00 |
Supreeth Herle | 556b0fe | 2020-03-25 11:26:57 +0100 | [diff] [blame] | 926 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 927 | return None |
Harald Welte | 67d551a | 2021-01-21 14:50:01 +0100 | [diff] [blame] | 928 | |
Philipp Maier | 5d3e259 | 2021-02-22 17:22:16 +0100 | [diff] [blame] | 929 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 930 | def sw_match(sw: str, pattern: str) -> bool: |
| 931 | """Match given SW against given pattern.""" |
| 932 | # Create a masked version of the returned status word |
| 933 | sw_lower = sw.lower() |
| 934 | sw_masked = "" |
| 935 | for i in range(0, 4): |
| 936 | if pattern[i] == '?': |
| 937 | sw_masked = sw_masked + '?' |
| 938 | elif pattern[i] == 'x': |
| 939 | sw_masked = sw_masked + 'x' |
| 940 | else: |
| 941 | sw_masked = sw_masked + sw_lower[i] |
| 942 | # Compare the masked version against the pattern |
| 943 | return sw_masked == pattern |
Harald Welte | ee3501f | 2021-04-02 13:00:18 +0200 | [diff] [blame] | 944 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 945 | |
| 946 | def tabulate_str_list(str_list, width: int = 79, hspace: int = 2, lspace: int = 1, |
| 947 | align_left: bool = True) -> str: |
| 948 | """Pretty print a list of strings into a tabulated form. |
| 949 | |
| 950 | Args: |
| 951 | width : total width in characters per line |
| 952 | space : horizontal space between cells |
| 953 | lspace : number of spaces before row |
| 954 | align_lef : Align text to the left side |
| 955 | Returns: |
| 956 | multi-line string containing formatted table |
| 957 | """ |
| 958 | if str_list == None: |
| 959 | return "" |
| 960 | if len(str_list) <= 0: |
| 961 | return "" |
| 962 | longest_str = max(str_list, key=len) |
| 963 | cellwith = len(longest_str) + hspace |
| 964 | cols = width // cellwith |
| 965 | rows = (len(str_list) - 1) // cols + 1 |
| 966 | table = [] |
| 967 | for i in iter(range(rows)): |
| 968 | str_list_row = str_list[i::rows] |
| 969 | if (align_left): |
| 970 | format_str_cell = '%%-%ds' |
| 971 | else: |
| 972 | format_str_cell = '%%%ds' |
| 973 | format_str_row = (format_str_cell % cellwith) * len(str_list_row) |
| 974 | format_str_row = (" " * lspace) + format_str_row |
| 975 | table.append(format_str_row % tuple(str_list_row)) |
| 976 | return '\n'.join(table) |
| 977 | |
Harald Welte | 5e749a7 | 2021-04-10 17:18:17 +0200 | [diff] [blame] | 978 | |
Harald Welte | 917d98c | 2021-04-21 11:51:25 +0200 | [diff] [blame] | 979 | def auto_int(x): |
| 980 | """Helper function for argparse to accept hexadecimal integers.""" |
| 981 | return int(x, 0) |
| 982 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 983 | |
Philipp Maier | 40ea4a4 | 2022-06-02 14:45:41 +0200 | [diff] [blame] | 984 | def expand_hex(hexstring, length): |
| 985 | """Expand a given hexstring to a specified length by replacing "." or ".." |
| 986 | with a filler that is derived from the neighboring nibbles respective |
| 987 | bytes. Usually this will be the nibble respective byte before "." or |
| 988 | "..", execpt when the string begins with "." or "..", then the nibble |
| 989 | respective byte after "." or ".." is used.". In case the string cannot |
| 990 | be expanded for some reason, the input string is returned unmodified. |
| 991 | |
| 992 | Args: |
| 993 | hexstring : hexstring to expand |
| 994 | length : desired length of the resulting hexstring. |
| 995 | Returns: |
| 996 | expanded hexstring |
| 997 | """ |
| 998 | |
| 999 | # expand digit aligned |
| 1000 | if hexstring.count(".") == 1: |
| 1001 | pos = hexstring.index(".") |
| 1002 | if pos > 0: |
| 1003 | filler = hexstring[pos - 1] |
| 1004 | else: |
| 1005 | filler = hexstring[pos + 1] |
| 1006 | |
| 1007 | missing = length * 2 - (len(hexstring) - 1) |
| 1008 | if missing <= 0: |
| 1009 | return hexstring |
| 1010 | |
| 1011 | return hexstring.replace(".", filler * missing) |
| 1012 | |
| 1013 | # expand byte aligned |
| 1014 | elif hexstring.count("..") == 1: |
| 1015 | if len(hexstring) % 2: |
| 1016 | return hexstring |
| 1017 | |
| 1018 | pos = hexstring.index("..") |
| 1019 | |
| 1020 | if pos % 2: |
| 1021 | return hexstring |
| 1022 | |
| 1023 | if pos > 1: |
| 1024 | filler = hexstring[pos - 2:pos] |
| 1025 | else: |
| 1026 | filler = hexstring[pos + 2:pos+4] |
| 1027 | |
| 1028 | missing = length * 2 - (len(hexstring) - 2) |
| 1029 | if missing <= 0: |
| 1030 | return hexstring |
| 1031 | |
| 1032 | return hexstring.replace("..", filler * (missing // 2)) |
| 1033 | |
| 1034 | # no change |
| 1035 | return hexstring |
| 1036 | |
| 1037 | |
Harald Welte | 5e749a7 | 2021-04-10 17:18:17 +0200 | [diff] [blame] | 1038 | class JsonEncoder(json.JSONEncoder): |
| 1039 | """Extend the standard library JSONEncoder with support for more types.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1040 | |
Harald Welte | 5e749a7 | 2021-04-10 17:18:17 +0200 | [diff] [blame] | 1041 | def default(self, o): |
| 1042 | if isinstance(o, BytesIO) or isinstance(o, bytes) or isinstance(o, bytearray): |
| 1043 | return b2h(o) |
| 1044 | return json.JSONEncoder.default(self, o) |
Philipp Maier | 80ce71f | 2021-04-19 21:24:23 +0200 | [diff] [blame] | 1045 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1046 | |
Philipp Maier | 80ce71f | 2021-04-19 21:24:23 +0200 | [diff] [blame] | 1047 | def boxed_heading_str(heading, width=80): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1048 | """Generate a string that contains a boxed heading.""" |
| 1049 | # Auto-enlarge box if heading exceeds length |
| 1050 | if len(heading) > width - 4: |
| 1051 | width = len(heading) + 4 |
Philipp Maier | 80ce71f | 2021-04-19 21:24:23 +0200 | [diff] [blame] | 1052 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1053 | res = "#" * width |
| 1054 | fstr = "\n# %-" + str(width - 4) + "s #\n" |
| 1055 | res += fstr % (heading) |
| 1056 | res += "#" * width |
| 1057 | return res |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1058 | |
| 1059 | |
| 1060 | class DataObject(abc.ABC): |
| 1061 | """A DataObject (DO) in the sense of ISO 7816-4. Contrary to 'normal' TLVs where one |
| 1062 | simply has any number of different TLVs that may occur in any order at any point, ISO 7816 |
| 1063 | has the habit of specifying TLV data but with very spcific ordering, or specific choices of |
| 1064 | tags at specific points in a stream. This class tries to represent this.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1065 | |
Harald Welte | 425038f | 2022-02-10 19:32:04 +0100 | [diff] [blame] | 1066 | def __init__(self, name: str, desc: Optional[str] = None, tag: Optional[int] = None): |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1067 | """ |
| 1068 | Args: |
| 1069 | name: A brief, all-lowercase, underscore separated string identifier |
| 1070 | desc: A human-readable description of what this DO represents |
| 1071 | tag : The tag associated with this DO |
| 1072 | """ |
| 1073 | self.name = name |
| 1074 | self.desc = desc |
| 1075 | self.tag = tag |
| 1076 | self.decoded = None |
| 1077 | self.encoded = None |
| 1078 | |
| 1079 | def __str__(self): |
| 1080 | return self.name |
| 1081 | |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1082 | def __repr__(self) -> str: |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1083 | return '%s(%s)' % (self.__class__, self.name) |
| 1084 | |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1085 | def __or__(self, other) -> 'DataObjectChoice': |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1086 | """OR-ing DataObjects together renders a DataObjectChoice.""" |
| 1087 | if isinstance(other, DataObject): |
| 1088 | # DataObject | DataObject = DataObjectChoice |
| 1089 | return DataObjectChoice(None, members=[self, other]) |
| 1090 | else: |
| 1091 | raise TypeError |
| 1092 | |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1093 | def __add__(self, other) -> 'DataObjectCollection': |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1094 | """ADD-ing DataObjects together renders a DataObjectCollection.""" |
| 1095 | if isinstance(other, DataObject): |
| 1096 | # DataObject + DataObject = DataObjectCollectin |
| 1097 | return DataObjectCollection(None, members=[self, other]) |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1098 | else: |
| 1099 | raise TypeError |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1100 | |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1101 | def _compute_tag(self) -> int: |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1102 | """Compute the tag (sometimes the tag encodes part of the value).""" |
| 1103 | return self.tag |
| 1104 | |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1105 | def to_dict(self) -> dict: |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1106 | """Return a dict in form "name: decoded_value" """ |
| 1107 | return {self.name: self.decoded} |
| 1108 | |
| 1109 | @abc.abstractmethod |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1110 | def from_bytes(self, do: bytes): |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1111 | """Parse the value part of the DO into the internal state of this instance. |
| 1112 | Args: |
| 1113 | do : binary encoded bytes |
| 1114 | """ |
| 1115 | |
| 1116 | @abc.abstractmethod |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1117 | def to_bytes(self) -> bytes: |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1118 | """Encode the internal state of this instance into the TLV value part. |
| 1119 | Returns: |
| 1120 | binary bytes encoding the internal state |
| 1121 | """ |
| 1122 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1123 | def from_tlv(self, do: bytes) -> bytes: |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1124 | """Parse binary TLV representation into internal state. The resulting decoded |
| 1125 | representation is _not_ returned, but just internalized in the object instance! |
| 1126 | Args: |
| 1127 | do : input bytes containing TLV-encoded representation |
| 1128 | Returns: |
| 1129 | bytes remaining at end of 'do' after parsing one TLV/DO. |
| 1130 | """ |
| 1131 | if do[0] != self.tag: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1132 | raise ValueError('%s: Can only decode tag 0x%02x' % |
| 1133 | (self, self.tag)) |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1134 | length = do[1] |
| 1135 | val = do[2:2+length] |
| 1136 | self.from_bytes(val) |
| 1137 | # return remaining bytes |
| 1138 | return do[2+length:] |
| 1139 | |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1140 | def to_tlv(self) -> bytes: |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1141 | """Encode internal representation to binary TLV. |
| 1142 | Returns: |
| 1143 | bytes encoded in TLV format. |
| 1144 | """ |
| 1145 | val = self.to_bytes() |
Harald Welte | 785d484 | 2022-04-05 14:24:22 +0200 | [diff] [blame] | 1146 | return bertlv_encode_tag(self._compute_tag()) + bertlv_encode_len(len(val)) + val |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1147 | |
| 1148 | # 'codec' interface |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1149 | def decode(self, binary: bytes) -> Tuple[dict, bytes]: |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1150 | """Decode a single DOs from the input data. |
| 1151 | Args: |
| 1152 | binary : binary bytes of encoded data |
| 1153 | Returns: |
| 1154 | tuple of (decoded_result, binary_remainder) |
| 1155 | """ |
| 1156 | tag = binary[0] |
| 1157 | if tag != self.tag: |
| 1158 | raise ValueError('%s: Unknown Tag 0x%02x in %s; expected 0x%02x' % |
| 1159 | (self, tag, binary, self.tag)) |
| 1160 | remainder = self.from_tlv(binary) |
| 1161 | return (self.to_dict(), remainder) |
| 1162 | |
| 1163 | # 'codec' interface |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1164 | def encode(self) -> bytes: |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1165 | return self.to_tlv() |
| 1166 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1167 | |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1168 | class TL0_DataObject(DataObject): |
| 1169 | """Data Object that has Tag, Len=0 and no Value part.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1170 | |
| 1171 | def __init__(self, name: str, desc: str, tag: int, val=None): |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1172 | super().__init__(name, desc, tag) |
| 1173 | self.val = val |
| 1174 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1175 | def from_bytes(self, binary: bytes): |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1176 | if len(binary) != 0: |
| 1177 | raise ValueError |
| 1178 | self.decoded = self.val |
| 1179 | |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1180 | def to_bytes(self) -> bytes: |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1181 | return b'' |
| 1182 | |
| 1183 | |
| 1184 | class DataObjectCollection: |
| 1185 | """A DataObjectCollection consits of multiple Data Objects identified by their tags. |
| 1186 | A given encoded DO may contain any of them in any order, and may contain multiple instances |
| 1187 | of each DO.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1188 | |
Harald Welte | 425038f | 2022-02-10 19:32:04 +0100 | [diff] [blame] | 1189 | def __init__(self, name: str, desc: Optional[str] = None, members=None): |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1190 | self.name = name |
| 1191 | self.desc = desc |
| 1192 | self.members = members or [] |
| 1193 | self.members_by_tag = {} |
| 1194 | self.members_by_name = {} |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1195 | self.members_by_tag = {m.tag: m for m in members} |
| 1196 | self.members_by_name = {m.name: m for m in members} |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1197 | |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1198 | def __str__(self) -> str: |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1199 | member_strs = [str(x) for x in self.members] |
| 1200 | return '%s(%s)' % (self.name, ','.join(member_strs)) |
| 1201 | |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1202 | def __repr__(self) -> str: |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1203 | member_strs = [repr(x) for x in self.members] |
| 1204 | return '%s(%s)' % (self.__class__, ','.join(member_strs)) |
| 1205 | |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1206 | def __add__(self, other) -> 'DataObjectCollection': |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1207 | """Extending DataCollections with other DataCollections or DataObjects.""" |
| 1208 | if isinstance(other, DataObjectCollection): |
| 1209 | # adding one collection to another |
| 1210 | members = self.members + other.members |
| 1211 | return DataObjectCollection(self.name, self.desc, members) |
| 1212 | elif isinstance(other, DataObject): |
| 1213 | # adding a member to a collection |
| 1214 | return DataObjectCollection(self.name, self.desc, self.members + [other]) |
| 1215 | else: |
| 1216 | raise TypeError |
| 1217 | |
| 1218 | # 'codec' interface |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1219 | def decode(self, binary: bytes) -> Tuple[List, bytes]: |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1220 | """Decode any number of DOs from the collection until the end of the input data, |
| 1221 | or uninitialized memory (0xFF) is found. |
| 1222 | Args: |
| 1223 | binary : binary bytes of encoded data |
| 1224 | Returns: |
| 1225 | tuple of (decoded_result, binary_remainder) |
| 1226 | """ |
| 1227 | res = [] |
| 1228 | remainder = binary |
| 1229 | # iterate until no binary trailer is left |
| 1230 | while len(remainder): |
| 1231 | tag = remainder[0] |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1232 | if tag == 0xff: # uninitialized memory at the end? |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1233 | return (res, remainder) |
| 1234 | if not tag in self.members_by_tag: |
| 1235 | raise ValueError('%s: Unknown Tag 0x%02x in %s; expected %s' % |
| 1236 | (self, tag, remainder, self.members_by_tag.keys())) |
| 1237 | obj = self.members_by_tag[tag] |
| 1238 | # DO from_tlv returns remainder of binary |
| 1239 | remainder = obj.from_tlv(remainder) |
| 1240 | # collect our results |
| 1241 | res.append(obj.to_dict()) |
| 1242 | return (res, remainder) |
| 1243 | |
| 1244 | # 'codec' interface |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1245 | def encode(self, decoded) -> bytes: |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1246 | res = bytearray() |
| 1247 | for i in decoded: |
| 1248 | obj = self.members_by_name(i[0]) |
| 1249 | res.append(obj.to_tlv()) |
| 1250 | return res |
| 1251 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1252 | |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1253 | class DataObjectChoice(DataObjectCollection): |
| 1254 | """One Data Object from within a choice, identified by its tag. |
| 1255 | This means that exactly one member of the choice must occur, and which one occurs depends |
| 1256 | on the tag.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1257 | |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1258 | def __add__(self, other): |
| 1259 | """We overload the add operator here to avoid inheriting it from DataObjecCollection.""" |
| 1260 | raise TypeError |
| 1261 | |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1262 | def __or__(self, other) -> 'DataObjectChoice': |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1263 | """OR-ing a Choice to another choice extends the choice, as does OR-ing a DataObject.""" |
| 1264 | if isinstance(other, DataObjectChoice): |
| 1265 | # adding one collection to another |
| 1266 | members = self.members + other.members |
| 1267 | return DataObjectChoice(self.name, self.desc, members) |
| 1268 | elif isinstance(other, DataObject): |
| 1269 | # adding a member to a collection |
| 1270 | return DataObjectChoice(self.name, self.desc, self.members + [other]) |
| 1271 | else: |
| 1272 | raise TypeError |
| 1273 | |
| 1274 | # 'codec' interface |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1275 | def decode(self, binary: bytes) -> Tuple[dict, bytes]: |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1276 | """Decode a single DOs from the choice based on the tag. |
| 1277 | Args: |
| 1278 | binary : binary bytes of encoded data |
| 1279 | Returns: |
| 1280 | tuple of (decoded_result, binary_remainder) |
| 1281 | """ |
| 1282 | tag = binary[0] |
| 1283 | if tag == 0xff: |
| 1284 | return (None, binary) |
| 1285 | if not tag in self.members_by_tag: |
| 1286 | raise ValueError('%s: Unknown Tag 0x%02x in %s; expected %s' % |
| 1287 | (self, tag, binary, self.members_by_tag.keys())) |
| 1288 | obj = self.members_by_tag[tag] |
| 1289 | remainder = obj.from_tlv(binary) |
| 1290 | return (obj.to_dict(), remainder) |
| 1291 | |
| 1292 | # 'codec' interface |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1293 | def encode(self, decoded) -> bytes: |
Harald Welte | 785d484 | 2022-04-05 14:24:22 +0200 | [diff] [blame] | 1294 | obj = self.members_by_name[list(decoded)[0]] |
| 1295 | obj.decoded = list(decoded.values())[0] |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1296 | return obj.to_tlv() |
| 1297 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1298 | |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1299 | class DataObjectSequence: |
| 1300 | """A sequence of DataObjects or DataObjectChoices. This allows us to express a certain |
| 1301 | ordered sequence of DOs or choices of DOs that have to appear as per the specification. |
| 1302 | By wrapping them into this formal DataObjectSequence, we can offer convenience methods |
| 1303 | for encoding or decoding an entire sequence.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1304 | |
Harald Welte | 425038f | 2022-02-10 19:32:04 +0100 | [diff] [blame] | 1305 | def __init__(self, name: str, desc: Optional[str] = None, sequence=None): |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1306 | self.sequence = sequence or [] |
| 1307 | self.name = name |
| 1308 | self.desc = desc |
| 1309 | |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1310 | def __str__(self) -> str: |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1311 | member_strs = [str(x) for x in self.sequence] |
| 1312 | return '%s(%s)' % (self.name, ','.join(member_strs)) |
| 1313 | |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1314 | def __repr__(self) -> str: |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1315 | member_strs = [repr(x) for x in self.sequence] |
| 1316 | return '%s(%s)' % (self.__class__, ','.join(member_strs)) |
| 1317 | |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1318 | def __add__(self, other) -> 'DataObjectSequence': |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1319 | """Add (append) a DataObject or DataObjectChoice to the sequence.""" |
| 1320 | if isinstance(other, 'DataObject'): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1321 | return DataObjectSequence(self.name, self.desc, self.sequence + [other]) |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1322 | elif isinstance(other, 'DataObjectChoice'): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1323 | return DataObjectSequence(self.name, self.desc, self.sequence + [other]) |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1324 | elif isinstance(other, 'DataObjectSequence'): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1325 | return DataObjectSequence(self.name, self.desc, self.sequence + other.sequence) |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1326 | |
| 1327 | # 'codec' interface |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1328 | def decode(self, binary: bytes) -> Tuple[list, bytes]: |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1329 | """Decode a sequence by calling the decoder of each element in the sequence. |
| 1330 | Args: |
| 1331 | binary : binary bytes of encoded data |
| 1332 | Returns: |
| 1333 | tuple of (decoded_result, binary_remainder) |
| 1334 | """ |
| 1335 | remainder = binary |
| 1336 | res = [] |
| 1337 | for e in self.sequence: |
| 1338 | (r, remainder) = e.decode(remainder) |
| 1339 | if r: |
| 1340 | res.append(r) |
| 1341 | return (res, remainder) |
| 1342 | |
| 1343 | # 'codec' interface |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1344 | def decode_multi(self, do: bytes) -> Tuple[list, bytes]: |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1345 | """Decode multiple occurrences of the sequence from the binary input data. |
| 1346 | Args: |
| 1347 | do : binary input data to be decoded |
| 1348 | Returns: |
| 1349 | list of results of the decoder of this sequences |
| 1350 | """ |
| 1351 | remainder = do |
| 1352 | res = [] |
| 1353 | while len(remainder): |
| 1354 | (r, remainder2) = self.decode(remainder) |
| 1355 | if r: |
| 1356 | res.append(r) |
| 1357 | if len(remainder2) < len(remainder): |
| 1358 | remainder = remainder2 |
| 1359 | else: |
| 1360 | remainder = remainder2 |
| 1361 | break |
| 1362 | return (res, remainder) |
| 1363 | |
| 1364 | # 'codec' interface |
Harald Welte | 5036877 | 2022-02-10 15:22:22 +0100 | [diff] [blame] | 1365 | def encode(self, decoded) -> bytes: |
Harald Welte | 3de6ca2 | 2021-05-02 20:05:56 +0200 | [diff] [blame] | 1366 | """Encode a sequence by calling the encoder of each element in the sequence.""" |
| 1367 | encoded = bytearray() |
| 1368 | i = 0 |
| 1369 | for e in self.sequence: |
| 1370 | encoded += e.encode(decoded[i]) |
| 1371 | i += 1 |
| 1372 | return encoded |
Harald Welte | 9044143 | 2021-05-02 21:28:12 +0200 | [diff] [blame] | 1373 | |
Harald Welte | 0dcdfbf | 2022-04-05 14:42:48 +0200 | [diff] [blame] | 1374 | def encode_multi(self, decoded) -> bytes: |
| 1375 | """Encode multiple occurrences of the sequence from the decoded input data. |
| 1376 | Args: |
| 1377 | decoded : list of json-serializable input data; one sequence per list item |
| 1378 | Returns: |
| 1379 | binary encoded output data |
| 1380 | """ |
| 1381 | encoded = bytearray() |
| 1382 | for d in decoded: |
| 1383 | encoded += self.encode(d) |
| 1384 | return encoded |
| 1385 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1386 | |
Harald Welte | 9044143 | 2021-05-02 21:28:12 +0200 | [diff] [blame] | 1387 | class CardCommand: |
| 1388 | """A single card command / instruction.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1389 | |
Harald Welte | 9044143 | 2021-05-02 21:28:12 +0200 | [diff] [blame] | 1390 | def __init__(self, name, ins, cla_list=None, desc=None): |
| 1391 | self.name = name |
| 1392 | self.ins = ins |
| 1393 | self.cla_list = cla_list or [] |
| 1394 | self.cla_list = [x.lower() for x in self.cla_list] |
| 1395 | self.desc = desc |
| 1396 | |
| 1397 | def __str__(self): |
| 1398 | return self.name |
| 1399 | |
| 1400 | def __repr__(self): |
| 1401 | return '%s(INS=%02x,CLA=%s)' % (self.name, self.ins, self.cla_list) |
| 1402 | |
| 1403 | def match_cla(self, cla): |
| 1404 | """Does the given CLA match the CLA list of the command?.""" |
| 1405 | if not isinstance(cla, str): |
| 1406 | cla = '%02u' % cla |
| 1407 | cla = cla.lower() |
| 1408 | for cla_match in self.cla_list: |
| 1409 | cla_masked = "" |
| 1410 | for i in range(0, 2): |
| 1411 | if cla_match[i] == 'x': |
| 1412 | cla_masked += 'x' |
| 1413 | else: |
| 1414 | cla_masked += cla[i] |
| 1415 | if cla_masked == cla_match: |
| 1416 | return True |
| 1417 | return False |
| 1418 | |
| 1419 | |
| 1420 | class CardCommandSet: |
| 1421 | """A set of card instructions, typically specified within one spec.""" |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1422 | |
Harald Welte | 9044143 | 2021-05-02 21:28:12 +0200 | [diff] [blame] | 1423 | def __init__(self, name, cmds=[]): |
| 1424 | self.name = name |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1425 | self.cmds = {c.ins: c for c in cmds} |
Harald Welte | 9044143 | 2021-05-02 21:28:12 +0200 | [diff] [blame] | 1426 | |
| 1427 | def __str__(self): |
| 1428 | return self.name |
| 1429 | |
| 1430 | def __getitem__(self, idx): |
| 1431 | return self.cmds[idx] |
| 1432 | |
| 1433 | def __add__(self, other): |
| 1434 | if isinstance(other, CardCommand): |
| 1435 | if other.ins in self.cmds: |
| 1436 | raise ValueError('%s: INS 0x%02x already defined: %s' % |
| 1437 | (self, other.ins, self.cmds[other.ins])) |
| 1438 | self.cmds[other.ins] = other |
| 1439 | elif isinstance(other, CardCommandSet): |
| 1440 | for c in other.cmds.keys(): |
| 1441 | self.cmds[c] = other.cmds[c] |
| 1442 | else: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1443 | raise ValueError( |
| 1444 | '%s: Unsupported type to add operator: %s' % (self, other)) |
Harald Welte | 9044143 | 2021-05-02 21:28:12 +0200 | [diff] [blame] | 1445 | |
| 1446 | def lookup(self, ins, cla=None): |
| 1447 | """look-up the command within the CommandSet.""" |
| 1448 | ins = int(ins) |
| 1449 | if not ins in self.cmds: |
| 1450 | return None |
| 1451 | cmd = self.cmds[ins] |
| 1452 | if cla and not cmd.match_cla(cla): |
| 1453 | return None |
| 1454 | return cmd |
Philipp Maier | a028c7d | 2021-11-08 16:12:03 +0100 | [diff] [blame] | 1455 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1456 | |
Philipp Maier | a028c7d | 2021-11-08 16:12:03 +0100 | [diff] [blame] | 1457 | def all_subclasses(cls) -> set: |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 1458 | """Recursively get all subclasses of a specified class""" |
| 1459 | return set(cls.__subclasses__()).union([s for c in cls.__subclasses__() for s in all_subclasses(c)]) |