blob: 7ad57e64c2375e9abc5d7b3a1ecfa93928714e8e [file] [log] [blame]
Daniel Willmannde07b952020-10-19 10:32:34 +02001#!/usr/bin/env python3
Sylvain Munaut76504e02010-12-07 00:24:32 +01002
3#
4# Utility to deal with sim cards and program the 'magic' ones easily
5#
6#
7# Part of the sim link code of inspired by pySimReader-Serial-src-v2
8#
9#
10# Copyright (C) 2009 Sylvain Munaut <tnt@246tNt.com>
11# Copyright (C) 2010 Harald Welte <laforge@gnumonks.org>
12#
13# This program is free software: you can redistribute it and/or modify
14# it under the terms of the GNU General Public License as published by
15# the Free Software Foundation, either version 2 of the License, or
16# (at your option) any later version.
17#
18# This program is distributed in the hope that it will be useful,
19# but WITHOUT ANY WARRANTY; without even the implied warranty of
20# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21# GNU General Public License for more details.
22#
23# You should have received a copy of the GNU General Public License
24# along with this program. If not, see <http://www.gnu.org/licenses/>.
25#
26
27import hashlib
28from optparse import OptionParser
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +010029import os
Sylvain Munaut76504e02010-12-07 00:24:32 +010030import random
31import re
32import sys
Philipp Maierc5b422e2019-08-30 11:41:02 +020033import traceback
Sylvain Munaut76504e02010-12-07 00:24:32 +010034
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +010035try:
36 import json
Holger Hans Peter Freyther5dffefb2011-11-22 21:18:06 +010037except ImportError:
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +010038 # Python < 2.5
39 import simplejson as json
40
Sylvain Munaut76504e02010-12-07 00:24:32 +010041from pySim.commands import SimCardCommands
Supreeth Herle4c306ab2020-03-18 11:38:00 +010042from pySim.cards import _cards_classes, card_detect
Philipp Maierff84c232020-05-12 17:24:18 +020043from pySim.utils import h2b, swap_nibbles, rpad, derive_milenage_opc, calculate_luhn, dec_iccid, init_reader
Philipp Maierf7792312018-06-11 17:11:39 +020044from pySim.ts_51_011 import EF
Philipp Maierc5b422e2019-08-30 11:41:02 +020045from pySim.card_handler import *
Philipp Maier7592eee2019-09-12 13:03:23 +020046from pySim.utils import *
Sylvain Munaut76504e02010-12-07 00:24:32 +010047
48def parse_options():
49
50 parser = OptionParser(usage="usage: %prog [options]")
51
52 parser.add_option("-d", "--device", dest="device", metavar="DEV",
53 help="Serial Device for SIM access [default: %default]",
54 default="/dev/ttyUSB0",
55 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010056 parser.add_option("-b", "--baud", dest="baudrate", type="int", metavar="BAUD",
57 help="Baudrate used for SIM access [default: %default]",
58 default=9600,
59 )
Sylvain Munaut9c8729a2010-12-08 23:20:27 +010060 parser.add_option("-p", "--pcsc-device", dest="pcsc_dev", type='int', metavar="PCSC",
Sylvain Munaute9fdecb2010-12-08 22:33:19 +010061 help="Which PC/SC reader number for SIM access",
62 default=None,
63 )
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070064 parser.add_option("--modem-device", dest="modem_dev", metavar="DEV",
65 help="Serial port of modem for Generic SIM Access (3GPP TS 27.007)",
66 default=None,
67 )
68 parser.add_option("--modem-baud", dest="modem_baud", type="int", metavar="BAUD",
69 help="Baudrate used for modem's port [default: %default]",
70 default=115200,
71 )
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +070072 parser.add_option("--osmocon", dest="osmocon_sock", metavar="PATH",
73 help="Socket path for Calypso (e.g. Motorola C1XX) based reader (via OsmocomBB)",
74 default=None,
75 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010076 parser.add_option("-t", "--type", dest="type",
77 help="Card type (user -t list to view) [default: %default]",
78 default="auto",
79 )
Philipp Maierac9dde62018-07-04 11:05:14 +020080 parser.add_option("-T", "--probe", dest="probe",
81 help="Determine card type",
82 default=False, action="store_true"
83 )
Jan Balkec3ebd332015-01-26 12:22:55 +010084 parser.add_option("-a", "--pin-adm", dest="pin_adm",
85 help="ADM PIN used for provisioning (overwrites default)",
86 )
Daniel Willmannf432b2b2018-06-15 07:31:50 +020087 parser.add_option("-A", "--pin-adm-hex", dest="pin_adm_hex",
88 help="ADM PIN used for provisioning, as hex string (16 characters long",
89 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010090 parser.add_option("-e", "--erase", dest="erase", action='store_true',
91 help="Erase beforehand [default: %default]",
92 default=False,
93 )
94
Harald Welte7f62cec2012-08-13 20:07:41 +020095 parser.add_option("-S", "--source", dest="source",
96 help="Data Source[default: %default]",
97 default="cmdline",
98 )
99
100 # if mode is "cmdline"
Sylvain Munaut76504e02010-12-07 00:24:32 +0100101 parser.add_option("-n", "--name", dest="name",
102 help="Operator name [default: %default]",
103 default="Magic",
104 )
105 parser.add_option("-c", "--country", dest="country", type="int", metavar="CC",
106 help="Country code [default: %default]",
107 default=1,
108 )
Harald Welte7f1d3c42020-05-12 21:12:44 +0200109 parser.add_option("-x", "--mcc", dest="mcc", type="string",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100110 help="Mobile Country Code [default: %default]",
Harald Welte7f1d3c42020-05-12 21:12:44 +0200111 default="901",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100112 )
Harald Welte7f1d3c42020-05-12 21:12:44 +0200113 parser.add_option("-y", "--mnc", dest="mnc", type="string",
Sylvain Munaut17716032010-12-08 22:33:51 +0100114 help="Mobile Network Code [default: %default]",
Harald Welte7f1d3c42020-05-12 21:12:44 +0200115 default="55",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100116 )
Supreeth Herlefc83e432020-05-06 11:48:46 +0200117 parser.add_option("--mnclen", dest="mnclen", type="choice",
118 help="Length of Mobile Network Code [default: %default]",
119 default=2,
120 choices=[2, 3],
121 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100122 parser.add_option("-m", "--smsc", dest="smsc",
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200123 help="SMSC number (Start with + for international no.) [default: '00 + country code + 5555']",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100124 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100125 parser.add_option("-M", "--smsp", dest="smsp",
126 help="Raw SMSP content in hex [default: auto from SMSC]",
127 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100128
129 parser.add_option("-s", "--iccid", dest="iccid", metavar="ID",
130 help="Integrated Circuit Card ID",
131 )
132 parser.add_option("-i", "--imsi", dest="imsi",
133 help="International Mobile Subscriber Identity",
134 )
Supreeth Herle5a541012019-12-22 08:59:16 +0100135 parser.add_option("--msisdn", dest="msisdn",
136 help="Mobile Subscriber Integrated Services Digital Number",
137 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100138 parser.add_option("-k", "--ki", dest="ki",
139 help="Ki (default is to randomize)",
140 )
Harald Welte93b38cd2012-03-22 14:31:36 +0100141 parser.add_option("-o", "--opc", dest="opc",
142 help="OPC (default is to randomize)",
143 )
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100144 parser.add_option("--op", dest="op",
145 help="Set OP to derive OPC from OP and KI",
146 )
Alexander Chemeris21885242013-07-02 16:56:55 +0400147 parser.add_option("--acc", dest="acc",
148 help="Set ACC bits (Access Control Code). not all card types are supported",
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200149 )
Supreeth Herle8e0fccd2020-03-23 12:10:56 +0100150 parser.add_option("--epdgid", dest="epdgid",
151 help="Set Home Evolved Packet Data Gateway (ePDG) Identifier. (Only FQDN format supported)",
152 )
Supreeth Herlef964df42020-03-24 13:15:37 +0100153 parser.add_option("--epdgSelection", dest="epdgSelection",
154 help="Set PLMN for ePDG Selection Information. (Only Operator Identifier FQDN format supported)",
155 )
Supreeth Herlecf727f22020-03-24 17:32:21 +0100156 parser.add_option("--pcscf", dest="pcscf",
157 help="Set Proxy Call Session Control Function (P-CSCF) Address. (Only FQDN format supported)",
158 )
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200159 parser.add_option("--read-imsi", dest="read_imsi", action="store_true",
160 help="Read the IMSI from the CARD", default=False
Alexander Chemeris21885242013-07-02 16:56:55 +0400161 )
Daniel Willmann164b9632019-09-03 19:13:51 +0200162 parser.add_option("--read-iccid", dest="read_iccid", action="store_true",
163 help="Read the ICCID from the CARD", default=False
164 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100165 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
166 help="Secret used for ICCID/IMSI autogen",
167 )
168 parser.add_option("-j", "--num", dest="num", type=int,
169 help="Card # used for ICCID/IMSI autogen",
170 )
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100171 parser.add_option("--batch", dest="batch_mode",
172 help="Enable batch mode [default: %default]",
173 default=False, action='store_true',
174 )
175 parser.add_option("--batch-state", dest="batch_state", metavar="FILE",
176 help="Optional batch state file",
177 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100178
Harald Welte7f62cec2012-08-13 20:07:41 +0200179 # if mode is "csv"
180 parser.add_option("--read-csv", dest="read_csv", metavar="FILE",
181 help="Read parameters from CSV file rather than command line")
182
183
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100184 parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
185 help="Append generated parameters in CSV file",
186 )
187 parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
188 help="Append generated parameters to OpenBSC HLR sqlite3",
189 )
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200190 parser.add_option("--dry-run", dest="dry_run",
191 help="Perform a 'dry run', don't actually program the card",
192 default=False, action="store_true")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200193 parser.add_option("--card_handler", dest="card_handler", metavar="FILE",
194 help="Use automatic card handling machine")
195
Sylvain Munaut76504e02010-12-07 00:24:32 +0100196 (options, args) = parser.parse_args()
197
198 if options.type == 'list':
199 for kls in _cards_classes:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700200 print(kls.name)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100201 sys.exit(0)
202
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200203 if options.probe:
204 return options
Philipp Maierac9dde62018-07-04 11:05:14 +0200205
Harald Welte7f62cec2012-08-13 20:07:41 +0200206 if options.source == 'csv':
Daniel Willmann164b9632019-09-03 19:13:51 +0200207 if (options.imsi is None) and (options.batch_mode is False) and (options.read_imsi is False) and (options.read_iccid is False):
208 parser.error("CSV mode needs either an IMSI, --read-imsi, --read-iccid or batch mode")
Harald Welte7f62cec2012-08-13 20:07:41 +0200209 if options.read_csv is None:
210 parser.error("CSV mode requires a CSV input file")
211 elif options.source == 'cmdline':
212 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
213 parser.error("If either IMSI or ICCID isn't specified, num is required")
214 else:
215 parser.error("Only `cmdline' and `csv' sources supported")
216
217 if (options.read_csv is not None) and (options.source != 'csv'):
218 parser.error("You cannot specify a CSV input file in source != csv")
219
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100220 if (options.batch_mode) and (options.num is None):
221 options.num = 0
222
Sylvain Munaut98d2b852010-12-23 20:27:25 +0100223 if (options.batch_mode):
224 if (options.imsi is not None) or (options.iccid is not None):
225 parser.error("Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more informations")
226
Sylvain Munaut76504e02010-12-07 00:24:32 +0100227 if args:
228 parser.error("Extraneous arguments")
229
230 return options
231
232
233def _digits(secret, usage, len, num):
Jeremy Herbert3b00dbf2020-10-25 20:56:05 +1000234 seed = secret + usage + '%d' % num
235 s = hashlib.sha1(seed.encode())
236 d = ''.join(['%02d' % x for x in s.digest()])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100237 return d[0:len]
238
239def _mcc_mnc_digits(mcc, mnc):
Harald Welte7f1d3c42020-05-12 21:12:44 +0200240 return '%s%s' % (mcc, mnc)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100241
242def _cc_digits(cc):
243 return ('%03d' if cc > 100 else '%02d') % cc
244
245def _isnum(s, l=-1):
246 return s.isdigit() and ((l== -1) or (len(s) == l))
247
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100248def _ishex(s, l=-1):
249 hc = '0123456789abcdef'
250 return all([x in hc for x in s.lower()]) and ((l== -1) or (len(s) == l))
251
Sylvain Munaut76504e02010-12-07 00:24:32 +0100252
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100253def _dbi_binary_quote(s):
254 # Count usage of each char
255 cnt = {}
256 for c in s:
257 cnt[c] = cnt.get(c, 0) + 1
258
259 # Find best offset
260 e = 0
261 m = len(s)
262 for i in range(1, 256):
263 if i == 39:
264 continue
265 sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
266 if sum_ < m:
267 m = sum_
268 e = i
269 if m == 0: # No overhead ? use this !
Daniel Willmann677d41b2020-10-19 10:34:31 +0200270 break
Sylvain Munaut1a914432011-12-08 20:08:26 +0100271
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100272 # Generate output
273 out = []
274 out.append( chr(e) ) # Offset
275 for c in s:
276 x = (256 + ord(c) - e) % 256
277 if x in (0, 1, 39):
278 out.append('\x01')
279 out.append(chr(x+1))
280 else:
281 out.append(chr(x))
282
283 return ''.join(out)
284
Sylvain Munaut76504e02010-12-07 00:24:32 +0100285def gen_parameters(opts):
Jan Balkec3ebd332015-01-26 12:22:55 +0100286 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki, PIN-ADM from the
Sylvain Munaut76504e02010-12-07 00:24:32 +0100287 options given by the user"""
288
289 # MCC/MNC
290 mcc = opts.mcc
291 mnc = opts.mnc
292
Harald Welte7f1d3c42020-05-12 21:12:44 +0200293 if not mcc.isdigit() or not mnc.isdigit():
294 raise ValueError('mcc & mnc must only contain decimal digits')
295 if len(mcc) < 1 or len(mcc) > 3:
296 raise ValueError('mcc must be between 1 .. 3 digits')
297 if len(mnc) < 1 or len(mnc) > 3:
298 raise ValueError('mnc must be between 1 .. 3 digits')
299
300 # MCC always has 3 digits
301 mcc = lpad(mcc, 3, "0")
302 # MNC must be at least 2 digits
303 mnc = lpad(mnc, 2, "0")
Sylvain Munaut76504e02010-12-07 00:24:32 +0100304
305 # Digitize country code (2 or 3 digits)
306 cc_digits = _cc_digits(opts.country)
307
308 # Digitize MCC/MNC (5 or 6 digits)
309 plmn_digits = _mcc_mnc_digits(mcc, mnc)
310
Supreeth Herle840a9e22020-01-21 13:32:46 +0100311 if opts.name is not None:
312 if len(opts.name) > 16:
Daniel Willmann677d41b2020-10-19 10:34:31 +0200313 raise ValueError('Service Provider Name must max 16 characters!')
Supreeth Herle840a9e22020-01-21 13:32:46 +0100314
Supreeth Herle5a541012019-12-22 08:59:16 +0100315 if opts.msisdn is not None:
316 msisdn = opts.msisdn
317 if msisdn[0] == '+':
318 msisdn = msisdn[1:]
319 if not msisdn.isdigit():
320 raise ValueError('MSISDN must be digits only! '
321 'Start with \'+\' for international numbers.')
322 if len(msisdn) > 10 * 2:
323 # TODO: Support MSISDN of length > 20 (10 Bytes)
324 raise ValueError('MSISDNs longer than 20 digits are not (yet) supported.')
325
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100326 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
Sylvain Munaut76504e02010-12-07 00:24:32 +0100327 if opts.iccid is not None:
328 iccid = opts.iccid
Todd Neal9eeadfc2018-04-25 15:36:29 -0500329 if not _isnum(iccid, 19) and not _isnum(iccid, 20):
Daniel Willmann677d41b2020-10-19 10:34:31 +0200330 raise ValueError('ICCID must be 19 or 20 digits !')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100331
332 else:
333 if opts.num is None:
334 raise ValueError('Neither ICCID nor card number specified !')
335
336 iccid = (
337 '89' + # Common prefix (telecom)
338 cc_digits + # Country Code on 2/3 digits
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200339 plmn_digits # MCC/MNC on 5/6 digits
Sylvain Munaut76504e02010-12-07 00:24:32 +0100340 )
341
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100342 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100343
344 if opts.secret is None:
345 # The raw number
346 iccid += ('%%0%dd' % ml) % opts.num
347 else:
348 # Randomized digits
349 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
350
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100351 # Add checksum digit
352 iccid += ('%1d' % calculate_luhn(iccid))
353
Sylvain Munaut76504e02010-12-07 00:24:32 +0100354 # IMSI (15 digits usually)
355 if opts.imsi is not None:
356 imsi = opts.imsi
357 if not _isnum(imsi):
358 raise ValueError('IMSI must be digits only !')
359
360 else:
361 if opts.num is None:
362 raise ValueError('Neither IMSI nor card number specified !')
363
364 ml = 15 - len(plmn_digits)
365
366 if opts.secret is None:
367 # The raw number
368 msin = ('%%0%dd' % ml) % opts.num
369 else:
370 # Randomized digits
371 msin = _digits(opts.secret, 'imsi', ml, opts.num)
372
373 imsi = (
374 plmn_digits + # MCC/MNC on 5/6 digits
375 msin # MSIN
376 )
377
378 # SMSP
379 if opts.smsp is not None:
380 smsp = opts.smsp
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100381 if not _ishex(smsp):
382 raise ValueError('SMSP must be hex digits only !')
383 if len(smsp) < 28*2:
384 raise ValueError('SMSP must be at least 28 bytes')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100385
386 else:
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200387 ton = "81"
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100388 if opts.smsc is not None:
389 smsc = opts.smsc
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200390 if smsc[0] == '+':
391 ton = "91"
392 smsc = smsc[1:]
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100393 if not _isnum(smsc):
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200394 raise ValueError('SMSC must be digits only!\n \
395 Start with \'+\' for international numbers')
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100396 else:
397 smsc = '00%d' % opts.country + '5555' # Hack ...
398
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200399 smsc = '%02d' % ((len(smsc) + 3)//2,) + ton + swap_nibbles(rpad(smsc, 20))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100400
401 smsp = (
402 'e1' + # Parameters indicator
403 'ff' * 12 + # TP-Destination address
404 smsc + # TP-Service Centre Address
405 '00' + # TP-Protocol identifier
406 '00' + # TP-Data coding scheme
407 '00' # TP-Validity period
408 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100409
Alexander Chemeris21885242013-07-02 16:56:55 +0400410 # ACC
411 if opts.acc is not None:
412 acc = opts.acc
413 if not _ishex(acc):
414 raise ValueError('ACC must be hex digits only !')
415 if len(acc) != 2*2:
416 raise ValueError('ACC must be exactly 2 bytes')
417
418 else:
419 acc = None
420
Sylvain Munaut76504e02010-12-07 00:24:32 +0100421 # Ki (random)
422 if opts.ki is not None:
423 ki = opts.ki
424 if not re.match('^[0-9a-fA-F]{32}$', ki):
425 raise ValueError('Ki needs to be 128 bits, in hex format')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100426 else:
427 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
428
Alexander Chemerisd17ca3d2017-07-18 16:40:58 +0300429 # OPC (random)
Harald Welte93b38cd2012-03-22 14:31:36 +0100430 if opts.opc is not None:
431 opc = opts.opc
432 if not re.match('^[0-9a-fA-F]{32}$', opc):
433 raise ValueError('OPC needs to be 128 bits, in hex format')
434
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100435 elif opts.op is not None:
436 opc = derive_milenage_opc(ki, opts.op)
Harald Welte93b38cd2012-03-22 14:31:36 +0100437 else:
438 opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
439
Philipp Maiere8536c02020-05-11 21:35:01 +0200440 pin_adm = sanitize_pin_adm(opts)
Harald Welte93b38cd2012-03-22 14:31:36 +0100441
Supreeth Herlef964df42020-03-24 13:15:37 +0100442 # ePDG Selection Information
443 if opts.epdgSelection:
444 if len(opts.epdgSelection) < 5 or len(opts.epdgSelection) > 6:
445 raise ValueError('ePDG Selection Information is not valid')
446 epdg_mcc = opts.epdgSelection[:3]
447 epdg_mnc = opts.epdgSelection[3:]
448 if not epdg_mcc.isdigit() or not epdg_mnc.isdigit():
449 raise ValueError('PLMN for ePDG Selection must only contain decimal digits')
450
Sylvain Munaut76504e02010-12-07 00:24:32 +0100451 # Return that
452 return {
453 'name' : opts.name,
454 'iccid' : iccid,
455 'mcc' : mcc,
456 'mnc' : mnc,
457 'imsi' : imsi,
458 'smsp' : smsp,
459 'ki' : ki,
Harald Welte93b38cd2012-03-22 14:31:36 +0100460 'opc' : opc,
Alexander Chemeris21885242013-07-02 16:56:55 +0400461 'acc' : acc,
Jan Balkec3ebd332015-01-26 12:22:55 +0100462 'pin_adm' : pin_adm,
Supreeth Herle5a541012019-12-22 08:59:16 +0100463 'msisdn' : opts.msisdn,
Supreeth Herle8e0fccd2020-03-23 12:10:56 +0100464 'epdgid' : opts.epdgid,
Supreeth Herlef964df42020-03-24 13:15:37 +0100465 'epdgSelection' : opts.epdgSelection,
Supreeth Herlecf727f22020-03-24 17:32:21 +0100466 'pcscf' : opts.pcscf,
Sylvain Munaut76504e02010-12-07 00:24:32 +0100467 }
468
469
470def print_parameters(params):
471
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200472 s = ["Generated card parameters :"]
473 if 'name' in params:
474 s.append(" > Name : %(name)s")
475 if 'smsp' in params:
476 s.append(" > SMSP : %(smsp)s")
477 s.append(" > ICCID : %(iccid)s")
Philipp Maierbe069e22019-09-12 12:52:43 +0200478 s.append(" > MCC/MNC : %(mcc)s/%(mnc)s")
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200479 s.append(" > IMSI : %(imsi)s")
480 s.append(" > Ki : %(ki)s")
481 s.append(" > OPC : %(opc)s")
482 if 'acc' in params:
483 s.append(" > ACC : %(acc)s")
484 s.append(" > ADM1(hex): %(pin_adm)s")
485 print("\n".join(s) % params)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100486
487
Harald Welte130524b2012-08-13 15:53:43 +0200488def write_params_csv(opts, params):
489 # csv
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100490 if opts.write_csv:
491 import csv
Harald Welte93b38cd2012-03-22 14:31:36 +0100492 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100493 f = open(opts.write_csv, 'a')
494 cw = csv.writer(f)
495 cw.writerow([params[x] for x in row])
496 f.close()
497
Daniel Willmann164b9632019-09-03 19:13:51 +0200498def _read_params_csv(opts, iccid=None, imsi=None):
Harald Welte7f62cec2012-08-13 20:07:41 +0200499 import csv
Harald Welte7f62cec2012-08-13 20:07:41 +0200500 f = open(opts.read_csv, 'r')
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200501 cr = csv.DictReader(f)
Philipp Maier120a0002019-09-12 13:11:45 +0200502
503 # Lower-case fieldnames
504 cr.fieldnames = [ field.lower() for field in cr.fieldnames ]
505
Harald Welte7f62cec2012-08-13 20:07:41 +0200506 i = 0
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200507 if not 'iccid' in cr.fieldnames:
508 raise Exception("CSV file in wrong format!")
Harald Welte7f62cec2012-08-13 20:07:41 +0200509 for row in cr:
Daniel Willmann164b9632019-09-03 19:13:51 +0200510 if opts.num is not None and opts.read_iccid is False and opts.read_imsi is False:
Harald Welte7f62cec2012-08-13 20:07:41 +0200511 if opts.num == i:
Harald Weltec26b8292012-08-15 15:25:51 +0200512 f.close()
Daniel Willmann677d41b2020-10-19 10:34:31 +0200513 return row
Harald Weltec26b8292012-08-15 15:25:51 +0200514 i += 1
Daniel Willmann164b9632019-09-03 19:13:51 +0200515 if row['iccid'] == iccid:
516 f.close()
Daniel Willmann677d41b2020-10-19 10:34:31 +0200517 return row
Daniel Willmann164b9632019-09-03 19:13:51 +0200518
Harald Welte7f62cec2012-08-13 20:07:41 +0200519 if row['imsi'] == imsi:
Harald Weltec26b8292012-08-15 15:25:51 +0200520 f.close()
Daniel Willmann677d41b2020-10-19 10:34:31 +0200521 return row
Harald Welte7f62cec2012-08-13 20:07:41 +0200522
523 f.close()
Harald Weltec26b8292012-08-15 15:25:51 +0200524 return None
525
Daniel Willmann164b9632019-09-03 19:13:51 +0200526def read_params_csv(opts, imsi=None, iccid=None):
527 row = _read_params_csv(opts, iccid=iccid, imsi=imsi)
Harald Weltec26b8292012-08-15 15:25:51 +0200528 if row is not None:
Philipp Maier7592eee2019-09-12 13:03:23 +0200529 row['mcc'] = row.get('mcc', mcc_from_imsi(row.get('imsi')))
530 row['mnc'] = row.get('mnc', mnc_from_imsi(row.get('imsi')))
531
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200532 pin_adm = None
533 # We need to escape the pin_adm we get from the csv
534 if 'pin_adm' in row:
535 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['pin_adm']])
536 # Stay compatible to the odoo csv format
537 elif 'adm1' in row:
538 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['adm1']])
539 if pin_adm:
540 row['pin_adm'] = rpad(pin_adm, 16)
Philipp Maiere053da52019-09-05 13:08:36 +0200541
542 # If the CSV-File defines a pin_adm_hex field use this field to
543 # generate pin_adm from that.
544 pin_adm_hex = row.get('pin_adm_hex')
545 if pin_adm_hex:
546 if len(pin_adm_hex) == 16:
547 row['pin_adm'] = pin_adm_hex
548 # Ensure that it's hex-encoded
549 try:
550 try_encode = h2b(pin_adm)
551 except ValueError:
552 raise ValueError("pin_adm_hex needs to be hex encoded using this option")
553 else:
554 raise ValueError("pin_adm_hex needs to be exactly 16 digits (hex encoded)")
555
Harald Welte7f62cec2012-08-13 20:07:41 +0200556 return row
557
Harald Weltec26b8292012-08-15 15:25:51 +0200558
Harald Welte130524b2012-08-13 15:53:43 +0200559def write_params_hlr(opts, params):
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100560 # SQLite3 OpenBSC HLR
561 if opts.write_hlr:
562 import sqlite3
563 conn = sqlite3.connect(opts.write_hlr)
564
565 c = conn.execute(
566 'INSERT INTO Subscriber ' +
567 '(imsi, name, extension, authorized, created, updated) ' +
568 'VALUES ' +
569 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
570 [
571 params['imsi'],
572 params['name'],
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200573 '9' + params['iccid'][-5:-1]
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100574 ],
575 )
576 sub_id = c.lastrowid
577 c.close()
578
579 c = conn.execute(
580 'INSERT INTO AuthKeys ' +
581 '(subscriber_id, algorithm_id, a3a8_ki)' +
582 'VALUES ' +
583 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100584 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100585 )
586
587 conn.commit()
588 conn.close()
589
Harald Welte130524b2012-08-13 15:53:43 +0200590def write_parameters(opts, params):
591 write_params_csv(opts, params)
Harald Welte7f62cec2012-08-13 20:07:41 +0200592 write_params_hlr(opts, params)
Harald Welte130524b2012-08-13 15:53:43 +0200593
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100594
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100595BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
596BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100597
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100598def init_batch(opts):
599 # Need to do something ?
600 if not opts.batch_mode:
601 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100602
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100603 for k in BATCH_INCOMPATIBLE:
604 if getattr(opts, k):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700605 print("Incompatible option with batch_state: %s" % (k,))
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100606 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100607
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100608 # Don't load state if there is none ...
609 if not opts.batch_state:
610 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100611
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100612 if not os.path.isfile(opts.batch_state):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700613 print("No state file yet")
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100614 return
615
616 # Get stored data
617 fh = open(opts.batch_state)
618 d = json.loads(fh.read())
619 fh.close()
620
621 for k,v in d.iteritems():
622 setattr(opts, k, v)
623
624
625def save_batch(opts):
626 # Need to do something ?
627 if not opts.batch_mode or not opts.batch_state:
628 return
629
630 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
631 fh = open(opts.batch_state, 'w')
632 fh.write(d)
633 fh.close()
634
635
Philipp Maierc5b422e2019-08-30 11:41:02 +0200636def process_card(opts, first, card_handler):
637
638 if opts.dry_run is False:
639 # Connect transport
640 card_handler.get(first)
641
642 if opts.dry_run is False:
643 # Get card
Supreeth Herle4c306ab2020-03-18 11:38:00 +0100644 card = card_detect(opts.type, scc)
Philipp Maierc5b422e2019-08-30 11:41:02 +0200645 if card is None:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700646 print("No card detected!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200647 return -1
648
649 # Probe only
650 if opts.probe:
651 return 0
652
653 # Erase if requested
654 if opts.erase:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700655 print("Formatting ...")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200656 card.erase()
657 card.reset()
658
659 # Generate parameters
660 if opts.source == 'cmdline':
661 cp = gen_parameters(opts)
662 elif opts.source == 'csv':
663 imsi = None
664 iccid = None
665 if opts.read_iccid:
666 if opts.dry_run:
667 # Connect transport
Daniel Willmanndd014ea2020-10-19 10:35:11 +0200668 card_handler.get(False)
Philipp Maierc5b422e2019-08-30 11:41:02 +0200669 (res,_) = scc.read_binary(['3f00', '2fe2'], length=10)
670 iccid = dec_iccid(res)
671 elif opts.read_imsi:
672 if opts.dry_run:
673 # Connect transport
Daniel Willmanndd014ea2020-10-19 10:35:11 +0200674 card_handler.get(False)
Philipp Maierc5b422e2019-08-30 11:41:02 +0200675 (res,_) = scc.read_binary(EF['IMSI'])
676 imsi = swap_nibbles(res)[3:]
677 else:
678 imsi = opts.imsi
679 cp = read_params_csv(opts, imsi=imsi, iccid=iccid)
680 if cp is None:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700681 print("Error reading parameters from CSV file!\n")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200682 return 2
683 print_parameters(cp)
684
685 if opts.dry_run is False:
686 # Program the card
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700687 print("Programming ...")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200688 card.program(cp)
689 else:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700690 print("Dry Run: NOT PROGRAMMING!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200691
692 # Write parameters permanently
693 write_parameters(opts, cp)
694
695 # Batch mode state update and save
696 if opts.num is not None:
697 opts.num += 1
698 save_batch(opts)
699
700 card_handler.done()
701 return 0
702
703
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100704if __name__ == '__main__':
705
706 # Parse options
707 opts = parse_options()
708
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700709 # Init card reader driver
Philipp Maierff84c232020-05-12 17:24:18 +0200710 sl = init_reader(opts)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100711
712 # Create command layer
713 scc = SimCardCommands(transport=sl)
714
Philipp Maier196b08c2019-09-12 11:49:44 +0200715 # If we use a CSV file as data input, check if the CSV file exists.
716 if opts.source == 'csv':
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700717 print("Using CSV file as data input: " + str(opts.read_csv))
Philipp Maier196b08c2019-09-12 11:49:44 +0200718 if not os.path.isfile(opts.read_csv):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700719 print("CSV file not found!")
Philipp Maier196b08c2019-09-12 11:49:44 +0200720 sys.exit(1)
721
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100722 # Batch mode init
723 init_batch(opts)
724
Philipp Maierc5b422e2019-08-30 11:41:02 +0200725 if opts.card_handler:
726 card_handler = card_handler_auto(sl, opts.card_handler)
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200727 else:
Philipp Maierc5b422e2019-08-30 11:41:02 +0200728 card_handler = card_handler(sl)
729
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100730 # Iterate
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100731 first = True
732 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100733
Philipp Maierc5b422e2019-08-30 11:41:02 +0200734 while 1:
735 try:
736 rc = process_card(opts, first, card_handler)
737 except (KeyboardInterrupt):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700738 print("")
739 print("Terminated by user!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200740 sys.exit(0)
741 except (SystemExit):
742 raise
743 except:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700744 print("")
745 print("Card programming failed with an execption:")
746 print("---------------------8<---------------------")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200747 traceback.print_exc()
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700748 print("---------------------8<---------------------")
749 print("")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200750 rc = -1
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200751
Philipp Maierc5b422e2019-08-30 11:41:02 +0200752 # Something did not work as well as expected, however, lets
753 # make sure the card is pulled from the reader.
754 if rc != 0:
755 card_handler.error()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100756
Philipp Maierc5b422e2019-08-30 11:41:02 +0200757 # If we are not in batch mode we are done in any case, so lets
758 # exit here.
759 if not opts.batch_mode:
760 sys.exit(rc)
761
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100762 first = False