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