blob: 5320b597c769e389215940139c2b32e8fd9bc480 [file] [log] [blame]
Sylvain Munaut76504e02010-12-07 00:24:32 +01001# -*- coding: utf-8 -*-
2
3""" pySim: various utilities
4"""
5
6#
7# Copyright (C) 2009-2010 Sylvain Munaut <tnt@246tNt.com>
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 2 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <http://www.gnu.org/licenses/>.
21#
22
23
24def h2b(s):
Harald Welte4f6ca432021-02-01 17:51:56 +010025 """convert from a string of hex nibbles to a sequence of bytes"""
26 return bytearray.fromhex(s)
Sylvain Munaut76504e02010-12-07 00:24:32 +010027
Harald Welte4f6ca432021-02-01 17:51:56 +010028def b2h(b):
29 """convert from a sequence of bytes to a string of hex nibbles"""
30 return ''.join(['%02x'%(x) for x in b])
Sylvain Munaut76504e02010-12-07 00:24:32 +010031
32def h2i(s):
33 return [(int(x,16)<<4)+int(y,16) for x,y in zip(s[0::2], s[1::2])]
34
35def i2h(s):
36 return ''.join(['%02x'%(x) for x in s])
37
Alexander Chemerisa5f0ea62017-07-18 16:48:47 +030038def h2s(s):
Vadim Yanitskiyeb06b452020-05-10 02:32:46 +070039 return ''.join([chr((int(x,16)<<4)+int(y,16)) for x,y in zip(s[0::2], s[1::2])
40 if int(x + y, 16) != 0xff])
Alexander Chemerisa5f0ea62017-07-18 16:48:47 +030041
42def s2h(s):
Harald Welte4f6ca432021-02-01 17:51:56 +010043 b = bytearray()
44 b.extend(map(ord, s))
45 return b2h(b)
Alexander Chemerisa5f0ea62017-07-18 16:48:47 +030046
Supreeth Herle7d77d2d2020-05-11 09:07:08 +020047# List of bytes to string
48def i2s(s):
49 return ''.join([chr(x) for x in s])
50
Sylvain Munaut76504e02010-12-07 00:24:32 +010051def swap_nibbles(s):
52 return ''.join([x+y for x,y in zip(s[1::2], s[0::2])])
53
54def rpad(s, l, c='f'):
55 return s + c * (l - len(s))
56
57def lpad(s, l, c='f'):
58 return c * (l - len(s)) + s
Alexander Chemeris5e96c3d2013-07-04 17:33:33 +040059
Ben Fox-Moore0ec14752018-09-24 15:47:02 +020060def half_round_up(n):
61 return (n + 1)//2
62
63# IMSI encoded format:
64# For IMSI 0123456789ABCDE:
65#
66# | byte 1 | 2 upper | 2 lower | 3 upper | 3 lower | ... | 9 upper | 9 lower |
67# | length in bytes | 0 | odd/even | 2 | 1 | ... | E | D |
68#
69# If the IMSI is less than 15 characters, it should be padded with 'f' from the end.
70#
71# The length is the total number of bytes used to encoded the IMSI. This includes the odd/even
72# parity bit. E.g. an IMSI of length 14 is 8 bytes long, not 7, as it uses bytes 2 to 9 to
73# encode itself.
74#
75# Because of this, an odd length IMSI fits exactly into len(imsi) + 1 // 2 bytes, whereas an
76# even length IMSI only uses half of the last byte.
77
Alexander Chemeris7be92ff2013-07-10 11:18:06 +040078def enc_imsi(imsi):
79 """Converts a string imsi into the value of the EF"""
Ben Fox-Moore0ec14752018-09-24 15:47:02 +020080 l = half_round_up(len(imsi) + 1) # Required bytes - include space for odd/even indicator
Alexander Chemeris7be92ff2013-07-10 11:18:06 +040081 oe = len(imsi) & 1 # Odd (1) / Even (0)
Ben Fox-Moore0ec14752018-09-24 15:47:02 +020082 ei = '%02x' % l + swap_nibbles('%01x%s' % ((oe<<3)|1, rpad(imsi, 15)))
Alexander Chemeris7be92ff2013-07-10 11:18:06 +040083 return ei
84
Alexander Chemeris5e96c3d2013-07-04 17:33:33 +040085def dec_imsi(ef):
86 """Converts an EF value to the imsi string representation"""
87 if len(ef) < 4:
88 return None
Pau Espin Pedrol665bd222017-12-29 20:30:35 +010089 l = int(ef[0:2], 16) * 2 # Length of the IMSI string
Ben Fox-Moore0ec14752018-09-24 15:47:02 +020090 l = l - 1 # Encoded length byte includes oe nibble
91 swapped = swap_nibbles(ef[2:]).rstrip('f')
Philipp Maiercd3d6262020-05-11 21:41:56 +020092 if len(swapped) < 1:
93 return None
Alexander Chemeris5e96c3d2013-07-04 17:33:33 +040094 oe = (int(swapped[0])>>3) & 1 # Odd (1) / Even (0)
Ben Fox-Moore0ec14752018-09-24 15:47:02 +020095 if not oe:
96 # if even, only half of last byte was used
Alexander Chemeris5e96c3d2013-07-04 17:33:33 +040097 l = l-1
Ben Fox-Moore0ec14752018-09-24 15:47:02 +020098 if l != len(swapped) - 1:
Alexander Chemeris5e96c3d2013-07-04 17:33:33 +040099 return None
Ben Fox-Moore0ec14752018-09-24 15:47:02 +0200100 imsi = swapped[1:]
Alexander Chemeris5e96c3d2013-07-04 17:33:33 +0400101 return imsi
102
103def dec_iccid(ef):
104 return swap_nibbles(ef).strip('f')
Alexander Chemeris7be92ff2013-07-10 11:18:06 +0400105
106def enc_iccid(iccid):
107 return swap_nibbles(rpad(iccid, 20))
108
109def enc_plmn(mcc, mnc):
Alexander Chemerisdddbf522017-07-18 16:49:59 +0300110 """Converts integer MCC/MNC into 3 bytes for EF"""
Harald Welte7f1d3c42020-05-12 21:12:44 +0200111 if len(mnc) == 2:
112 mnc = "F%s" % mnc
113 return swap_nibbles("%s%s" % (mcc, mnc))
Alexander Chemerisa5f0ea62017-07-18 16:48:47 +0300114
115def dec_spn(ef):
116 byte1 = int(ef[0:2])
117 hplmn_disp = (byte1&0x01 == 0x01)
118 oplmn_disp = (byte1&0x02 == 0x02)
119 name = h2s(ef[2:])
120 return (name, hplmn_disp, oplmn_disp)
121
122def enc_spn(name, hplmn_disp=False, oplmn_disp=False):
123 byte1 = 0x00
124 if hplmn_disp: byte1 = byte1|0x01
125 if oplmn_disp: byte1 = byte1|0x02
126 return i2h([byte1])+s2h(name)
Alexander Chemeris19fffa12018-01-11 13:06:43 +0900127
Supreeth Herlef3948532020-03-24 12:23:51 +0100128def hexstr_to_Nbytearr(s, nbytes):
129 return [s[i:i+(nbytes*2)] for i in range(0, len(s), (nbytes*2)) ]
130
Daniel Laszlo Sitzer851e9c02018-12-04 19:40:08 +0100131# Accepts hex string representing three bytes
132def dec_mcc_from_plmn(plmn):
133 ia = h2i(plmn)
134 digit1 = ia[0] & 0x0F # 1st byte, LSB
135 digit2 = (ia[0] & 0xF0) >> 4 # 1st byte, MSB
136 digit3 = ia[1] & 0x0F # 2nd byte, LSB
137 if digit3 == 0xF and digit2 == 0xF and digit1 == 0xF:
138 return 0xFFF # 4095
Supreeth Herled24f1632019-11-30 10:37:09 +0100139 return derive_mcc(digit1, digit2, digit3)
Daniel Laszlo Sitzer851e9c02018-12-04 19:40:08 +0100140
141def dec_mnc_from_plmn(plmn):
142 ia = h2i(plmn)
herlesupreethbdf3d352021-02-11 06:59:29 +0100143 digit1 = (ia[1] & 0xF0) >>4 # 2nd byte, MSB
144 digit2 = ia[2] & 0x0F # 3rd byte, LSB
145 digit3 = (ia[2] & 0xF0) >> 4 # 3nd byte, MSB
Daniel Laszlo Sitzer851e9c02018-12-04 19:40:08 +0100146 if digit3 == 0xF and digit2 == 0xF and digit1 == 0xF:
147 return 0xFFF # 4095
Supreeth Herled24f1632019-11-30 10:37:09 +0100148 return derive_mnc(digit1, digit2, digit3)
Daniel Laszlo Sitzer851e9c02018-12-04 19:40:08 +0100149
150def dec_act(twohexbytes):
151 act_list = [
152 {'bit': 15, 'name': "UTRAN"},
153 {'bit': 14, 'name': "E-UTRAN"},
154 {'bit': 7, 'name': "GSM"},
155 {'bit': 6, 'name': "GSM COMPACT"},
156 {'bit': 5, 'name': "cdma2000 HRPD"},
157 {'bit': 4, 'name': "cdma2000 1xRTT"},
158 ]
159 ia = h2i(twohexbytes)
160 u16t = (ia[0] << 8)|ia[1]
161 sel = []
162 for a in act_list:
163 if u16t & (1 << a['bit']):
164 sel.append(a['name'])
165 return sel
166
167def dec_xplmn_w_act(fivehexbytes):
168 res = {'mcc': 0, 'mnc': 0, 'act': []}
169 plmn_chars = 6
170 act_chars = 4
171 plmn_str = fivehexbytes[:plmn_chars] # first three bytes (six ascii hex chars)
172 act_str = fivehexbytes[plmn_chars:plmn_chars + act_chars] # two bytes after first three bytes
173 res['mcc'] = dec_mcc_from_plmn(plmn_str)
174 res['mnc'] = dec_mnc_from_plmn(plmn_str)
175 res['act'] = dec_act(act_str)
176 return res
177
178def format_xplmn_w_act(hexstr):
179 s = ""
herlesupreeth45fa6042020-09-18 15:32:20 +0200180 for rec_data in hexstr_to_Nbytearr(hexstr, 5):
Daniel Laszlo Sitzer851e9c02018-12-04 19:40:08 +0100181 rec_info = dec_xplmn_w_act(rec_data)
182 if rec_info['mcc'] == 0xFFF and rec_info['mnc'] == 0xFFF:
183 rec_str = "unused"
184 else:
Supreeth Herled24f1632019-11-30 10:37:09 +0100185 rec_str = "MCC: %03d MNC: %03d AcT: %s" % (rec_info['mcc'], rec_info['mnc'], ", ".join(rec_info['act']))
Daniel Laszlo Sitzer851e9c02018-12-04 19:40:08 +0100186 s += "\t%s # %s\n" % (rec_data, rec_str)
187 return s
188
Sebastian Vivianie61170c2020-06-03 08:57:00 +0100189def dec_loci(hexstr):
190 res = {'tmsi': '', 'mcc': 0, 'mnc': 0, 'lac': '', 'status': 0}
191 res['tmsi'] = hexstr[:8]
192 res['mcc'] = dec_mcc_from_plmn(hexstr[8:14])
193 res['mnc'] = dec_mnc_from_plmn(hexstr[8:14])
194 res['lac'] = hexstr[14:18]
195 res['status'] = h2i(hexstr[20:22])
196 return res
197
198def dec_psloci(hexstr):
199 res = {'p-tmsi': '', 'p-tmsi-sig': '', 'mcc': 0, 'mnc': 0, 'lac': '', 'rac': '', 'status': 0}
200 res['p-tmsi'] = hexstr[:8]
201 res['p-tmsi-sig'] = hexstr[8:14]
202 res['mcc'] = dec_mcc_from_plmn(hexstr[14:20])
203 res['mnc'] = dec_mnc_from_plmn(hexstr[14:20])
204 res['lac'] = hexstr[20:24]
205 res['rac'] = hexstr[24:26]
206 res['status'] = h2i(hexstr[26:28])
207 return res
208
209def dec_epsloci(hexstr):
210 res = {'guti': '', 'mcc': 0, 'mnc': 0, 'tac': '', 'status': 0}
211 res['guti'] = hexstr[:24]
212 res['tai'] = hexstr[24:34]
213 res['mcc'] = dec_mcc_from_plmn(hexstr[24:30])
214 res['mnc'] = dec_mnc_from_plmn(hexstr[24:30])
215 res['tac'] = hexstr[30:34]
216 res['status'] = h2i(hexstr[34:36])
217 return res
218
Harald Welteca673942020-06-03 15:19:40 +0200219def dec_xplmn(threehexbytes):
220 res = {'mcc': 0, 'mnc': 0, 'act': []}
221 plmn_chars = 6
222 plmn_str = threehexbytes[:plmn_chars] # first three bytes (six ascii hex chars)
223 res['mcc'] = dec_mcc_from_plmn(plmn_str)
224 res['mnc'] = dec_mnc_from_plmn(plmn_str)
225 return res
226
227def format_xplmn(hexstr):
228 s = ""
herlesupreeth45fa6042020-09-18 15:32:20 +0200229 for rec_data in hexstr_to_Nbytearr(hexstr, 3):
Harald Welteca673942020-06-03 15:19:40 +0200230 rec_info = dec_xplmn(rec_data)
231 if rec_info['mcc'] == 0xFFF and rec_info['mnc'] == 0xFFF:
232 rec_str = "unused"
233 else:
234 rec_str = "MCC: %03d MNC: %03d" % (rec_info['mcc'], rec_info['mnc'])
235 s += "\t%s # %s\n" % (rec_data, rec_str)
236 return s
237
Alexander Chemeris19fffa12018-01-11 13:06:43 +0900238def derive_milenage_opc(ki_hex, op_hex):
239 """
240 Run the milenage algorithm to calculate OPC from Ki and OP
241 """
242 from Crypto.Cipher import AES
243 from Crypto.Util.strxor import strxor
244 from pySim.utils import b2h
245
246 # We pass in hex string and now need to work on bytes
247 aes = AES.new(h2b(ki_hex))
248 opc_bytes = aes.encrypt(h2b(op_hex))
249 return b2h(strxor(opc_bytes, h2b(op_hex)))
250
251def calculate_luhn(cc):
252 """
253 Calculate Luhn checksum used in e.g. ICCID and IMEI
254 """
Daniel Willmanndd014ea2020-10-19 10:35:11 +0200255 num = list(map(int, str(cc)))
Alexander Chemeris19fffa12018-01-11 13:06:43 +0900256 check_digit = 10 - sum(num[-2::-2] + [sum(divmod(d * 2, 10)) for d in num[::-2]]) % 10
257 return 0 if check_digit == 10 else check_digit
Philipp Maier7592eee2019-09-12 13:03:23 +0200258
259def mcc_from_imsi(imsi):
260 """
261 Derive the MCC (Mobile Country Code) from the first three digits of an IMSI
262 """
263 if imsi == None:
264 return None
265
266 if len(imsi) > 3:
267 return imsi[:3]
268 else:
269 return None
270
271def mnc_from_imsi(imsi, long=False):
272 """
273 Derive the MNC (Mobile Country Code) from the 4th to 6th digit of an IMSI
274 """
275 if imsi == None:
276 return None
277
278 if len(imsi) > 3:
279 if long:
280 return imsi[3:6]
281 else:
282 return imsi[3:5]
283 else:
284 return None
Supreeth Herled24f1632019-11-30 10:37:09 +0100285
286def derive_mcc(digit1, digit2, digit3):
287 """
288 Derive decimal representation of the MCC (Mobile Country Code)
289 from three given digits.
290 """
291
292 mcc = 0
293
294 if digit1 != 0x0f:
295 mcc += digit1 * 100
296 if digit2 != 0x0f:
297 mcc += digit2 * 10
298 if digit3 != 0x0f:
299 mcc += digit3
300
301 return mcc
302
303def derive_mnc(digit1, digit2, digit3=0x0f):
304 """
305 Derive decimal representation of the MNC (Mobile Network Code)
306 from two or (optionally) three given digits.
307 """
308
309 mnc = 0
310
311 # 3-rd digit is optional for the MNC. If present
312 # the algorythm is the same as for the MCC.
313 if digit3 != 0x0f:
314 return derive_mcc(digit1, digit2, digit3)
315
316 if digit1 != 0x0f:
317 mnc += digit1 * 10
318 if digit2 != 0x0f:
319 mnc += digit2
320
321 return mnc
Supreeth Herle4b1c7632019-12-22 09:00:59 +0100322
323def dec_msisdn(ef_msisdn):
324 """
325 Decode MSISDN from EF.MSISDN or EF.ADN (same structure).
326 See 3GPP TS 31.102, section 4.2.26 and 4.4.2.3.
327 """
328
329 # Convert from str to (kind of) 'bytes'
330 ef_msisdn = h2b(ef_msisdn)
331
332 # Make sure mandatory fields are present
333 if len(ef_msisdn) < 14:
334 raise ValueError("EF.MSISDN is too short")
335
336 # Skip optional Alpha Identifier
337 xlen = len(ef_msisdn) - 14
338 msisdn_lhv = ef_msisdn[xlen:]
339
340 # Parse the length (in bytes) of the BCD encoded number
Harald Welte4f6ca432021-02-01 17:51:56 +0100341 bcd_len = msisdn_lhv[0]
Supreeth Herle4b1c7632019-12-22 09:00:59 +0100342 # BCD length = length of dial num (max. 10 bytes) + 1 byte ToN and NPI
343 if bcd_len == 0xff:
344 return None
345 elif bcd_len > 11 or bcd_len < 1:
346 raise ValueError("Length of MSISDN (%d bytes) is out of range" % bcd_len)
347
348 # Parse ToN / NPI
Harald Welte4f6ca432021-02-01 17:51:56 +0100349 ton = (msisdn_lhv[1] >> 4) & 0x07
350 npi = msisdn_lhv[1] & 0x0f
Supreeth Herle4b1c7632019-12-22 09:00:59 +0100351 bcd_len -= 1
352
353 # No MSISDN?
354 if not bcd_len:
355 return (npi, ton, None)
356
357 msisdn = swap_nibbles(b2h(msisdn_lhv[2:][:bcd_len])).rstrip('f')
358 # International number 10.5.118/3GPP TS 24.008
Vadim Yanitskiy7ba24282020-02-27 00:04:13 +0700359 if ton == 0x01:
Supreeth Herle4b1c7632019-12-22 09:00:59 +0100360 msisdn = '+' + msisdn
361
362 return (npi, ton, msisdn)
Supreeth Herle5a541012019-12-22 08:59:16 +0100363
364def enc_msisdn(msisdn, npi=0x01, ton=0x03):
365 """
366 Encode MSISDN as LHV so it can be stored to EF.MSISDN.
367 See 3GPP TS 31.102, section 4.2.26 and 4.4.2.3.
368
369 Default NPI / ToN values:
370 - NPI: ISDN / telephony numbering plan (E.164 / E.163),
371 - ToN: network specific or international number (if starts with '+').
372 """
373
374 # Leading '+' indicates International Number
375 if msisdn[0] == '+':
376 msisdn = msisdn[1:]
377 ton = 0x01
378
379 # Append 'f' padding if number of digits is odd
380 if len(msisdn) % 2 > 0:
381 msisdn += 'f'
382
383 # BCD length also includes NPI/ToN header
384 bcd_len = len(msisdn) // 2 + 1
385 npi_ton = (npi & 0x0f) | ((ton & 0x07) << 4) | 0x80
386 bcd = rpad(swap_nibbles(msisdn), 10 * 2) # pad to 10 octets
387
388 return ('%02x' % bcd_len) + ('%02x' % npi_ton) + bcd
Supreeth Herle441c4a72020-03-24 10:19:15 +0100389
Supreeth Herle0c4d82d2020-04-20 13:28:31 +0200390def dec_st(st, table="sim"):
391 """
392 Parses the EF S/U/IST and prints the list of available services in EF S/U/IST
393 """
394
Supreeth Herledf330372020-04-20 14:48:55 +0200395 if table == "isim":
396 from pySim.ts_31_103 import EF_IST_map
397 lookup_map = EF_IST_map
398 elif table == "usim":
Supreeth Herle0c4d82d2020-04-20 13:28:31 +0200399 from pySim.ts_31_102 import EF_UST_map
400 lookup_map = EF_UST_map
401 else:
402 from pySim.ts_51_011 import EF_SST_map
403 lookup_map = EF_SST_map
404
405 st_bytes = [st[i:i+2] for i in range(0, len(st), 2) ]
406
407 avail_st = ""
408 # Get each byte and check for available services
409 for i in range(0, len(st_bytes)):
410 # Byte i contains info about Services num (8i+1) to num (8i+8)
411 byte = int(st_bytes[i], 16)
412 # Services in each byte are in order MSB to LSB
413 # MSB - Service (8i+8)
414 # LSB - Service (8i+1)
415 for j in range(1, 9):
416 if byte&0x01 == 0x01 and ((8*i) + j in lookup_map):
417 # Byte X contains info about Services num (8X-7) to num (8X)
418 # bit = 1: service available
419 # bit = 0: service not available
420 avail_st += '\tService %d - %s\n' % ((8*i) + j, lookup_map[(8*i) + j])
421 byte = byte >> 1
422 return avail_st
Supreeth Herle98370552020-05-11 09:04:41 +0200423
424def first_TLV_parser(bytelist):
425 '''
426 first_TLV_parser([0xAA, 0x02, 0xAB, 0xCD, 0xFF, 0x00]) -> (170, 2, [171, 205])
427
428 parses first TLV format record in a list of bytelist
429 returns a 3-Tuple: Tag, Length, Value
430 Value is a list of bytes
431 parsing of length is ETSI'style 101.220
432 '''
433 Tag = bytelist[0]
434 if bytelist[1] == 0xFF:
435 Len = bytelist[2]*256 + bytelist[3]
436 Val = bytelist[4:4+Len]
437 else:
438 Len = bytelist[1]
439 Val = bytelist[2:2+Len]
440 return (Tag, Len, Val)
441
442def TLV_parser(bytelist):
443 '''
444 TLV_parser([0xAA, ..., 0xFF]) -> [(T, L, [V]), (T, L, [V]), ...]
445
446 loops on the input list of bytes with the "first_TLV_parser()" function
447 returns a list of 3-Tuples
448 '''
449 ret = []
450 while len(bytelist) > 0:
451 T, L, V = first_TLV_parser(bytelist)
452 if T == 0xFF:
453 # padding bytes
454 break
455 ret.append( (T, L, V) )
456 # need to manage length of L
457 if L > 0xFE:
458 bytelist = bytelist[ L+4 : ]
459 else:
460 bytelist = bytelist[ L+2 : ]
461 return ret
Supreeth Herled572ede2020-03-22 09:55:04 +0100462
Supreeth Herled84daa12020-03-24 12:20:40 +0100463def enc_st(st, service, state=1):
464 """
465 Encodes the EF S/U/IST/EST and returns the updated Service Table
466
467 Parameters:
468 st - Current value of SIM/USIM/ISIM Service Table
469 service - Service Number to encode as activated/de-activated
470 state - 1 mean activate, 0 means de-activate
471
472 Returns:
473 s - Modified value of SIM/USIM/ISIM Service Table
474
475 Default values:
476 - state: 1 - Sets the particular Service bit to 1
477 """
478 st_bytes = [st[i:i+2] for i in range(0, len(st), 2) ]
479
480 s = ""
481 # Check whether the requested service is present in each byte
482 for i in range(0, len(st_bytes)):
483 # Byte i contains info about Services num (8i+1) to num (8i+8)
484 if service in range((8*i) + 1, (8*i) + 9):
485 byte = int(st_bytes[i], 16)
486 # Services in each byte are in order MSB to LSB
487 # MSB - Service (8i+8)
488 # LSB - Service (8i+1)
489 mod_byte = 0x00
490 # Copy bit by bit contents of byte to mod_byte with modified bit
491 # for requested service
492 for j in range(1, 9):
493 mod_byte = mod_byte >> 1
494 if service == (8*i) + j:
495 mod_byte = state == 1 and mod_byte|0x80 or mod_byte&0x7f
496 else:
497 mod_byte = byte&0x01 == 0x01 and mod_byte|0x80 or mod_byte&0x7f
498 byte = byte >> 1
499
500 s += ('%02x' % (mod_byte))
501 else:
502 s += st_bytes[i]
503
504 return s
505
Supreeth Herle3b342c22020-03-24 16:15:02 +0100506def dec_addr_tlv(hexstr):
Supreeth Herled572ede2020-03-22 09:55:04 +0100507 """
Supreeth Herle3b342c22020-03-24 16:15:02 +0100508 Decode hex string to get EF.P-CSCF Address or EF.ePDGId or EF.ePDGIdEm.
509 See 3GPP TS 31.102 version 13.4.0 Release 13, section 4.2.8, 4.2.102 and 4.2.104.
Supreeth Herled572ede2020-03-22 09:55:04 +0100510 """
511
512 # Convert from hex str to int bytes list
Supreeth Herle3b342c22020-03-24 16:15:02 +0100513 addr_tlv_bytes = h2i(hexstr)
Supreeth Herled572ede2020-03-22 09:55:04 +0100514
515 s = ""
516
517 # Get list of tuples containing parsed TLVs
Supreeth Herle3b342c22020-03-24 16:15:02 +0100518 tlvs = TLV_parser(addr_tlv_bytes)
Supreeth Herled572ede2020-03-22 09:55:04 +0100519
520 for tlv in tlvs:
521 # tlv = (T, L, [V])
522 # T = Tag
523 # L = Length
524 # [V] = List of value
525
526 # Invalid Tag value scenario
527 if tlv[0] != 0x80:
528 continue
529
Supreeth Herled6a5ec52020-06-01 12:27:51 +0200530 # Empty field - Zero length
531 if tlv[1] == 0:
532 continue
533
Supreeth Herled572ede2020-03-22 09:55:04 +0100534 # First byte in the value has the address type
535 addr_type = tlv[2][0]
Supreeth Herle43fd03b2020-03-25 14:52:46 +0100536 # TODO: Support parsing of IPv6
Supreeth Herle3b342c22020-03-24 16:15:02 +0100537 # Address Type: 0x00 (FQDN), 0x01 (IPv4), 0x02 (IPv6), other (Reserved)
Supreeth Herled572ede2020-03-22 09:55:04 +0100538 if addr_type == 0x00: #FQDN
539 # Skip address tye byte i.e. first byte in value list
540 content = tlv[2][1:]
541 s += "\t%s # %s\n" % (i2h(content), i2s(content))
Supreeth Herle43fd03b2020-03-25 14:52:46 +0100542 elif addr_type == 0x01: #IPv4
543 # Skip address tye byte i.e. first byte in value list
544 # Skip the unused byte in Octect 4 after address type byte as per 3GPP TS 31.102
545 ipv4 = tlv[2][2:]
546 content = '.'.join(str(x) for x in ipv4)
547 s += "\t%s # %s\n" % (i2h(ipv4), content)
Supreeth Herled572ede2020-03-22 09:55:04 +0100548
549 return s
Philipp Maierff84c232020-05-12 17:24:18 +0200550
Supreeth Herle3b342c22020-03-24 16:15:02 +0100551def enc_addr_tlv(addr, addr_type='00'):
Supreeth Herle3c0bd7a2020-03-23 11:59:33 +0100552 """
Supreeth Herle3b342c22020-03-24 16:15:02 +0100553 Encode address TLV object used in EF.P-CSCF Address, EF.ePDGId and EF.ePDGIdEm.
554 See 3GPP TS 31.102 version 13.4.0 Release 13, section 4.2.8, 4.2.102 and 4.2.104.
Supreeth Herle3c0bd7a2020-03-23 11:59:33 +0100555
556 Default values:
Supreeth Herle3b342c22020-03-24 16:15:02 +0100557 - addr_type: 00 - FQDN format of Address
Supreeth Herle3c0bd7a2020-03-23 11:59:33 +0100558 """
559
560 s = ""
561
Supreeth Herle654eca72020-03-25 14:25:38 +0100562 # TODO: Encoding of IPv6 address
563 if addr_type == '00': #FQDN
Supreeth Herle3b342c22020-03-24 16:15:02 +0100564 hex_str = s2h(addr)
Supreeth Herle3c0bd7a2020-03-23 11:59:33 +0100565 s += '80' + ('%02x' % ((len(hex_str)//2)+1)) + '00' + hex_str
Supreeth Herle654eca72020-03-25 14:25:38 +0100566 elif addr_type == '01': #IPv4
567 ipv4_list = addr.split('.')
568 ipv4_str = ""
569 for i in ipv4_list:
570 ipv4_str += ('%02x' % (int(i)))
571
572 # Unused bytes shall be set to 'ff'. i.e 4th Octet after Address Type is not used
573 # IPv4 Address is in octet 5 to octet 8 of the TLV data object
574 s += '80' + ('%02x' % ((len(ipv4_str)//2)+2)) + '01' + 'ff' + ipv4_str
Supreeth Herle3c0bd7a2020-03-23 11:59:33 +0100575
576 return s
577
Harald Welte79b5ba42021-01-08 21:22:38 +0100578def sanitize_pin_adm(pin_adm, pin_adm_hex = None):
Philipp Maiere8536c02020-05-11 21:35:01 +0200579 """
580 The ADM pin can be supplied either in its hexadecimal form or as
581 ascii string. This function checks the supplied opts parameter and
582 returns the pin_adm as hex encoded string, regardles in which form
583 it was originally supplied by the user
584 """
585
Harald Welte79b5ba42021-01-08 21:22:38 +0100586 if pin_adm is not None:
587 if len(pin_adm) <= 8:
588 pin_adm = ''.join(['%02x'%(ord(x)) for x in pin_adm])
Philipp Maiere8536c02020-05-11 21:35:01 +0200589 pin_adm = rpad(pin_adm, 16)
590
591 else:
592 raise ValueError("PIN-ADM needs to be <=8 digits (ascii)")
593
Harald Welte79b5ba42021-01-08 21:22:38 +0100594 if pin_adm_hex is not None:
595 if len(pin_adm_hex) == 16:
596 pin_adm = pin_adm_hex
Philipp Maiere8536c02020-05-11 21:35:01 +0200597 # Ensure that it's hex-encoded
598 try:
599 try_encode = h2b(pin_adm)
600 except ValueError:
601 raise ValueError("PIN-ADM needs to be hex encoded using this option")
602 else:
603 raise ValueError("PIN-ADM needs to be exactly 16 digits (hex encoded)")
604
605 return pin_adm
606
Philipp Maierff84c232020-05-12 17:24:18 +0200607def init_reader(opts):
608 """
609 Init card reader driver
610 """
Philipp Maierc8caec22021-02-22 16:07:53 +0100611 try:
612 if opts.pcsc_dev is not None:
613 print("Using PC/SC reader interface")
614 from pySim.transport.pcsc import PcscSimLink
615 sl = PcscSimLink(opts.pcsc_dev)
616 elif opts.osmocon_sock is not None:
617 print("Using Calypso-based (OsmocomBB) reader interface")
618 from pySim.transport.calypso import CalypsoSimLink
619 sl = CalypsoSimLink(sock_path=opts.osmocon_sock)
620 elif opts.modem_dev is not None:
621 print("Using modem for Generic SIM Access (3GPP TS 27.007)")
622 from pySim.transport.modem_atcmd import ModemATCommandLink
623 sl = ModemATCommandLink(device=opts.modem_dev, baudrate=opts.modem_baud)
624 else: # Serial reader is default
625 print("Using serial reader interface")
626 from pySim.transport.serial import SerialSimLink
627 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
628 return sl
629 except Exception as e:
630 print("Card reader initialization failed with exception:\n" + str(e))
631 return None
Philipp Maierff84c232020-05-12 17:24:18 +0200632
Supreeth Herle95b4e8d2020-03-24 12:49:16 +0100633
Supreeth Herle95ec7722020-03-24 13:09:03 +0100634def enc_ePDGSelection(hexstr, mcc, mnc, epdg_priority='0001', epdg_fqdn_format='00'):
635 """
636 Encode ePDGSelection so it can be stored at EF.ePDGSelection or EF.ePDGSelectionEm.
637 See 3GPP TS 31.102 version 15.2.0 Release 15, section 4.2.104 and 4.2.106.
638
639 Default values:
640 - epdg_priority: '0001' - 1st Priority
641 - epdg_fqdn_format: '00' - Operator Identifier FQDN
642 """
643
644 plmn1 = enc_plmn(mcc, mnc) + epdg_priority + epdg_fqdn_format
645 # TODO: Handle encoding of Length field for length more than 127 Bytes
646 content = '80' + ('%02x' % (len(plmn1)//2)) + plmn1
647 content = rpad(content, len(hexstr))
648 return content
649
Supreeth Herle95b4e8d2020-03-24 12:49:16 +0100650def dec_ePDGSelection(sixhexbytes):
651 """
652 Decode ePDGSelection to get EF.ePDGSelection or EF.ePDGSelectionEm.
653 See 3GPP TS 31.102 version 15.2.0 Release 15, section 4.2.104 and 4.2.106.
654 """
655
656 res = {'mcc': 0, 'mnc': 0, 'epdg_priority': 0, 'epdg_fqdn_format': ''}
657 plmn_chars = 6
658 epdg_priority_chars = 4
659 epdg_fqdn_format_chars = 2
660 # first three bytes (six ascii hex chars)
661 plmn_str = sixhexbytes[:plmn_chars]
662 # two bytes after first three bytes
663 epdg_priority_str = sixhexbytes[plmn_chars:plmn_chars + epdg_priority_chars]
664 # one byte after first five bytes
665 epdg_fqdn_format_str = sixhexbytes[plmn_chars + epdg_priority_chars:plmn_chars + epdg_priority_chars + epdg_fqdn_format_chars]
666 res['mcc'] = dec_mcc_from_plmn(plmn_str)
667 res['mnc'] = dec_mnc_from_plmn(plmn_str)
668 res['epdg_priority'] = epdg_priority_str
669 res['epdg_fqdn_format'] = epdg_fqdn_format_str == '00' and 'Operator Identifier FQDN' or 'Location based FQDN'
670 return res
671
672def format_ePDGSelection(hexstr):
673 ePDGSelection_info_tag_chars = 2
674 ePDGSelection_info_tag_str = hexstr[:2]
herlesupreeth3a261d32021-01-05 09:20:11 +0100675 s = ""
Supreeth Herle95b4e8d2020-03-24 12:49:16 +0100676 # Minimum length
677 len_chars = 2
678 # TODO: Need to determine length properly - definite length support only
679 # Inconsistency in spec: 3GPP TS 31.102 version 15.2.0 Release 15, 4.2.104
680 # As per spec, length is 5n, n - number of PLMNs
681 # But, each PLMN entry is made of PLMN (3 Bytes) + ePDG Priority (2 Bytes) + ePDG FQDN format (1 Byte)
682 # Totalling to 6 Bytes, maybe length should be 6n
683 len_str = hexstr[ePDGSelection_info_tag_chars:ePDGSelection_info_tag_chars+len_chars]
herlesupreeth3a261d32021-01-05 09:20:11 +0100684
685 # Not programmed scenario
686 if int(len_str, 16) == 255 or int(ePDGSelection_info_tag_str, 16) == 255:
687 len_chars = 0
688 ePDGSelection_info_tag_chars = 0
Supreeth Herle95b4e8d2020-03-24 12:49:16 +0100689 if len_str[0] == '8':
690 # The bits 7 to 1 denotes the number of length octets if length > 127
691 if int(len_str[1]) > 0:
692 # Update number of length octets
693 len_chars = len_chars * int(len_str[1])
694 len_str = hexstr[ePDGSelection_info_tag_chars:len_chars]
695
696 content_str = hexstr[ePDGSelection_info_tag_chars+len_chars:]
697 # Right pad to prevent index out of range - multiple of 6 bytes
698 content_str = rpad(content_str, len(content_str) + (12 - (len(content_str) % 12)))
Supreeth Herle95b4e8d2020-03-24 12:49:16 +0100699 for rec_data in hexstr_to_Nbytearr(content_str, 6):
700 rec_info = dec_ePDGSelection(rec_data)
701 if rec_info['mcc'] == 0xFFF and rec_info['mnc'] == 0xFFF:
702 rec_str = "unused"
703 else:
704 rec_str = "MCC: %03d MNC: %03d ePDG Priority: %s ePDG FQDN format: %s" % \
705 (rec_info['mcc'], rec_info['mnc'], rec_info['epdg_priority'], rec_info['epdg_fqdn_format'])
706 s += "\t%s # %s\n" % (rec_data, rec_str)
707 return s
Supreeth Herle556b0fe2020-03-25 11:26:57 +0100708
709def get_addr_type(addr):
710 """
711 Validates the given address and returns it's type (FQDN or IPv4 or IPv6)
712 Return: 0x00 (FQDN), 0x01 (IPv4), 0x02 (IPv6), None (Bad address argument given)
713
714 TODO: Handle IPv6
715 """
716
717 # Empty address string
718 if not len(addr):
719 return None
720
721 import sys
722 # Handle python3 and python2 - unicode
723 if sys.version_info[0] < 3:
724 addr_str = unicode(addr)
725 else:
726 addr_str = addr
727
728 addr_list = addr.split('.')
729
730 # Check for IPv4/IPv6
731 try:
732 import ipaddress
733 # Throws ValueError if addr is not correct
734 ipa = ipaddress.ip_address(addr_str)
735
736 if ipa.version == 4:
737 return 0x01
738 elif ipa.version == 6:
739 return 0x02
740 except Exception as e:
741 invalid_ipv4 = True
742 for i in addr_list:
743 # Invalid IPv4 may qualify for a valid FQDN, so make check here
744 # e.g. 172.24.15.300
745 import re
746 if not re.match('^[0-9_]+$', i):
747 invalid_ipv4 = False
748 break
749
750 if invalid_ipv4:
751 return None
752
753 fqdn_flag = True
754 for i in addr_list:
755 # Only Alpha-numeric characters and hyphen - RFC 1035
756 import re
757 if not re.match("^[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)?$", i):
758 fqdn_flag = False
759 break
760
761 # FQDN
762 if fqdn_flag:
763 return 0x00
764
765 return None
Harald Welte67d551a2021-01-21 14:50:01 +0100766
767def sw_match(sw, pattern):
768 """Match given SW against given pattern."""
769 # Create a masked version of the returned status word
770 sw_lower = sw.lower()
771 sw_masked = ""
772 for i in range(0, 4):
773 if sw_lower[i] == '?':
774 sw_masked = sw_masked + '?'
775 elif sw_lower[i] == 'x':
776 sw_masked = sw_masked + 'x'
777 else:
778 sw_masked = sw_masked + sw_lower[i]
779 return sw_masked == pattern