blob: e3045a6ba3fdd4ba3404353c3629acc2a9dc9f50 [file] [log] [blame]
Pau Espin Pedrolac23ad52017-12-29 20:30:35 +01001#!/usr/bin/env python2
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
Daniel Willmann164b9632019-09-03 19:13:51 +020043from pySim.utils import h2b, swap_nibbles, rpad, derive_milenage_opc, calculate_luhn, dec_iccid
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 Yanitskiy9f9f5a62018-10-27 02:10:34 +070064 parser.add_option("--osmocon", dest="osmocon_sock", metavar="PATH",
65 help="Socket path for Calypso (e.g. Motorola C1XX) based reader (via OsmocomBB)",
66 default=None,
67 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010068 parser.add_option("-t", "--type", dest="type",
69 help="Card type (user -t list to view) [default: %default]",
70 default="auto",
71 )
Philipp Maierac9dde62018-07-04 11:05:14 +020072 parser.add_option("-T", "--probe", dest="probe",
73 help="Determine card type",
74 default=False, action="store_true"
75 )
Jan Balkec3ebd332015-01-26 12:22:55 +010076 parser.add_option("-a", "--pin-adm", dest="pin_adm",
77 help="ADM PIN used for provisioning (overwrites default)",
78 )
Daniel Willmannf432b2b2018-06-15 07:31:50 +020079 parser.add_option("-A", "--pin-adm-hex", dest="pin_adm_hex",
80 help="ADM PIN used for provisioning, as hex string (16 characters long",
81 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010082 parser.add_option("-e", "--erase", dest="erase", action='store_true',
83 help="Erase beforehand [default: %default]",
84 default=False,
85 )
86
Harald Welte7f62cec2012-08-13 20:07:41 +020087 parser.add_option("-S", "--source", dest="source",
88 help="Data Source[default: %default]",
89 default="cmdline",
90 )
91
92 # if mode is "cmdline"
Sylvain Munaut76504e02010-12-07 00:24:32 +010093 parser.add_option("-n", "--name", dest="name",
94 help="Operator name [default: %default]",
95 default="Magic",
96 )
97 parser.add_option("-c", "--country", dest="country", type="int", metavar="CC",
98 help="Country code [default: %default]",
99 default=1,
100 )
101 parser.add_option("-x", "--mcc", dest="mcc", type="int",
102 help="Mobile Country Code [default: %default]",
103 default=901,
104 )
105 parser.add_option("-y", "--mnc", dest="mnc", type="int",
Sylvain Munaut17716032010-12-08 22:33:51 +0100106 help="Mobile Network Code [default: %default]",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100107 default=55,
108 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100109 parser.add_option("-m", "--smsc", dest="smsc",
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200110 help="SMSC number (Start with + for international no.) [default: '00 + country code + 5555']",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100111 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100112 parser.add_option("-M", "--smsp", dest="smsp",
113 help="Raw SMSP content in hex [default: auto from SMSC]",
114 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100115
116 parser.add_option("-s", "--iccid", dest="iccid", metavar="ID",
117 help="Integrated Circuit Card ID",
118 )
119 parser.add_option("-i", "--imsi", dest="imsi",
120 help="International Mobile Subscriber Identity",
121 )
Supreeth Herle5a541012019-12-22 08:59:16 +0100122 parser.add_option("--msisdn", dest="msisdn",
123 help="Mobile Subscriber Integrated Services Digital Number",
124 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100125 parser.add_option("-k", "--ki", dest="ki",
126 help="Ki (default is to randomize)",
127 )
Harald Welte93b38cd2012-03-22 14:31:36 +0100128 parser.add_option("-o", "--opc", dest="opc",
129 help="OPC (default is to randomize)",
130 )
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100131 parser.add_option("--op", dest="op",
132 help="Set OP to derive OPC from OP and KI",
133 )
Alexander Chemeris21885242013-07-02 16:56:55 +0400134 parser.add_option("--acc", dest="acc",
135 help="Set ACC bits (Access Control Code). not all card types are supported",
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200136 )
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200137 parser.add_option("--read-imsi", dest="read_imsi", action="store_true",
138 help="Read the IMSI from the CARD", default=False
Alexander Chemeris21885242013-07-02 16:56:55 +0400139 )
Daniel Willmann164b9632019-09-03 19:13:51 +0200140 parser.add_option("--read-iccid", dest="read_iccid", action="store_true",
141 help="Read the ICCID from the CARD", default=False
142 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100143 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
144 help="Secret used for ICCID/IMSI autogen",
145 )
146 parser.add_option("-j", "--num", dest="num", type=int,
147 help="Card # used for ICCID/IMSI autogen",
148 )
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100149 parser.add_option("--batch", dest="batch_mode",
150 help="Enable batch mode [default: %default]",
151 default=False, action='store_true',
152 )
153 parser.add_option("--batch-state", dest="batch_state", metavar="FILE",
154 help="Optional batch state file",
155 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100156
Harald Welte7f62cec2012-08-13 20:07:41 +0200157 # if mode is "csv"
158 parser.add_option("--read-csv", dest="read_csv", metavar="FILE",
159 help="Read parameters from CSV file rather than command line")
160
161
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100162 parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
163 help="Append generated parameters in CSV file",
164 )
165 parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
166 help="Append generated parameters to OpenBSC HLR sqlite3",
167 )
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200168 parser.add_option("--dry-run", dest="dry_run",
169 help="Perform a 'dry run', don't actually program the card",
170 default=False, action="store_true")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200171 parser.add_option("--card_handler", dest="card_handler", metavar="FILE",
172 help="Use automatic card handling machine")
173
Sylvain Munaut76504e02010-12-07 00:24:32 +0100174 (options, args) = parser.parse_args()
175
176 if options.type == 'list':
177 for kls in _cards_classes:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700178 print(kls.name)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100179 sys.exit(0)
180
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200181 if options.probe:
182 return options
Philipp Maierac9dde62018-07-04 11:05:14 +0200183
Harald Welte7f62cec2012-08-13 20:07:41 +0200184 if options.source == 'csv':
Daniel Willmann164b9632019-09-03 19:13:51 +0200185 if (options.imsi is None) and (options.batch_mode is False) and (options.read_imsi is False) and (options.read_iccid is False):
186 parser.error("CSV mode needs either an IMSI, --read-imsi, --read-iccid or batch mode")
Harald Welte7f62cec2012-08-13 20:07:41 +0200187 if options.read_csv is None:
188 parser.error("CSV mode requires a CSV input file")
189 elif options.source == 'cmdline':
190 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
191 parser.error("If either IMSI or ICCID isn't specified, num is required")
192 else:
193 parser.error("Only `cmdline' and `csv' sources supported")
194
195 if (options.read_csv is not None) and (options.source != 'csv'):
196 parser.error("You cannot specify a CSV input file in source != csv")
197
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100198 if (options.batch_mode) and (options.num is None):
199 options.num = 0
200
Sylvain Munaut98d2b852010-12-23 20:27:25 +0100201 if (options.batch_mode):
202 if (options.imsi is not None) or (options.iccid is not None):
203 parser.error("Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more informations")
204
Sylvain Munaut76504e02010-12-07 00:24:32 +0100205 if args:
206 parser.error("Extraneous arguments")
207
208 return options
209
210
211def _digits(secret, usage, len, num):
212 s = hashlib.sha1(secret + usage + '%d' % num)
213 d = ''.join(['%02d'%ord(x) for x in s.digest()])
214 return d[0:len]
215
216def _mcc_mnc_digits(mcc, mnc):
217 return ('%03d%03d' if mnc > 100 else '%03d%02d') % (mcc, mnc)
218
219def _cc_digits(cc):
220 return ('%03d' if cc > 100 else '%02d') % cc
221
222def _isnum(s, l=-1):
223 return s.isdigit() and ((l== -1) or (len(s) == l))
224
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100225def _ishex(s, l=-1):
226 hc = '0123456789abcdef'
227 return all([x in hc for x in s.lower()]) and ((l== -1) or (len(s) == l))
228
Sylvain Munaut76504e02010-12-07 00:24:32 +0100229
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100230def _dbi_binary_quote(s):
231 # Count usage of each char
232 cnt = {}
233 for c in s:
234 cnt[c] = cnt.get(c, 0) + 1
235
236 # Find best offset
237 e = 0
238 m = len(s)
239 for i in range(1, 256):
240 if i == 39:
241 continue
242 sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
243 if sum_ < m:
244 m = sum_
245 e = i
246 if m == 0: # No overhead ? use this !
247 break;
Sylvain Munaut1a914432011-12-08 20:08:26 +0100248
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100249 # Generate output
250 out = []
251 out.append( chr(e) ) # Offset
252 for c in s:
253 x = (256 + ord(c) - e) % 256
254 if x in (0, 1, 39):
255 out.append('\x01')
256 out.append(chr(x+1))
257 else:
258 out.append(chr(x))
259
260 return ''.join(out)
261
Sylvain Munaut76504e02010-12-07 00:24:32 +0100262def gen_parameters(opts):
Jan Balkec3ebd332015-01-26 12:22:55 +0100263 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki, PIN-ADM from the
Sylvain Munaut76504e02010-12-07 00:24:32 +0100264 options given by the user"""
265
266 # MCC/MNC
267 mcc = opts.mcc
268 mnc = opts.mnc
269
270 if not ((0 < mcc < 999) and (0 < mnc < 999)):
271 raise ValueError('mcc & mnc must be between 0 and 999')
272
273 # Digitize country code (2 or 3 digits)
274 cc_digits = _cc_digits(opts.country)
275
276 # Digitize MCC/MNC (5 or 6 digits)
277 plmn_digits = _mcc_mnc_digits(mcc, mnc)
278
Supreeth Herle840a9e22020-01-21 13:32:46 +0100279 if opts.name is not None:
280 if len(opts.name) > 16:
281 raise ValueError('Service Provider Name must max 16 characters!');
282
Supreeth Herle5a541012019-12-22 08:59:16 +0100283 if opts.msisdn is not None:
284 msisdn = opts.msisdn
285 if msisdn[0] == '+':
286 msisdn = msisdn[1:]
287 if not msisdn.isdigit():
288 raise ValueError('MSISDN must be digits only! '
289 'Start with \'+\' for international numbers.')
290 if len(msisdn) > 10 * 2:
291 # TODO: Support MSISDN of length > 20 (10 Bytes)
292 raise ValueError('MSISDNs longer than 20 digits are not (yet) supported.')
293
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100294 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
Sylvain Munaut76504e02010-12-07 00:24:32 +0100295 if opts.iccid is not None:
296 iccid = opts.iccid
Todd Neal9eeadfc2018-04-25 15:36:29 -0500297 if not _isnum(iccid, 19) and not _isnum(iccid, 20):
298 raise ValueError('ICCID must be 19 or 20 digits !');
Sylvain Munaut76504e02010-12-07 00:24:32 +0100299
300 else:
301 if opts.num is None:
302 raise ValueError('Neither ICCID nor card number specified !')
303
304 iccid = (
305 '89' + # Common prefix (telecom)
306 cc_digits + # Country Code on 2/3 digits
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200307 plmn_digits # MCC/MNC on 5/6 digits
Sylvain Munaut76504e02010-12-07 00:24:32 +0100308 )
309
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100310 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100311
312 if opts.secret is None:
313 # The raw number
314 iccid += ('%%0%dd' % ml) % opts.num
315 else:
316 # Randomized digits
317 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
318
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100319 # Add checksum digit
320 iccid += ('%1d' % calculate_luhn(iccid))
321
Sylvain Munaut76504e02010-12-07 00:24:32 +0100322 # IMSI (15 digits usually)
323 if opts.imsi is not None:
324 imsi = opts.imsi
325 if not _isnum(imsi):
326 raise ValueError('IMSI must be digits only !')
327
328 else:
329 if opts.num is None:
330 raise ValueError('Neither IMSI nor card number specified !')
331
332 ml = 15 - len(plmn_digits)
333
334 if opts.secret is None:
335 # The raw number
336 msin = ('%%0%dd' % ml) % opts.num
337 else:
338 # Randomized digits
339 msin = _digits(opts.secret, 'imsi', ml, opts.num)
340
341 imsi = (
342 plmn_digits + # MCC/MNC on 5/6 digits
343 msin # MSIN
344 )
345
346 # SMSP
347 if opts.smsp is not None:
348 smsp = opts.smsp
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100349 if not _ishex(smsp):
350 raise ValueError('SMSP must be hex digits only !')
351 if len(smsp) < 28*2:
352 raise ValueError('SMSP must be at least 28 bytes')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100353
354 else:
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200355 ton = "81"
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100356 if opts.smsc is not None:
357 smsc = opts.smsc
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200358 if smsc[0] == '+':
359 ton = "91"
360 smsc = smsc[1:]
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100361 if not _isnum(smsc):
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200362 raise ValueError('SMSC must be digits only!\n \
363 Start with \'+\' for international numbers')
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100364 else:
365 smsc = '00%d' % opts.country + '5555' # Hack ...
366
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200367 smsc = '%02d' % ((len(smsc) + 3)//2,) + ton + swap_nibbles(rpad(smsc, 20))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100368
369 smsp = (
370 'e1' + # Parameters indicator
371 'ff' * 12 + # TP-Destination address
372 smsc + # TP-Service Centre Address
373 '00' + # TP-Protocol identifier
374 '00' + # TP-Data coding scheme
375 '00' # TP-Validity period
376 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100377
Alexander Chemeris21885242013-07-02 16:56:55 +0400378 # ACC
379 if opts.acc is not None:
380 acc = opts.acc
381 if not _ishex(acc):
382 raise ValueError('ACC must be hex digits only !')
383 if len(acc) != 2*2:
384 raise ValueError('ACC must be exactly 2 bytes')
385
386 else:
387 acc = None
388
Sylvain Munaut76504e02010-12-07 00:24:32 +0100389 # Ki (random)
390 if opts.ki is not None:
391 ki = opts.ki
392 if not re.match('^[0-9a-fA-F]{32}$', ki):
393 raise ValueError('Ki needs to be 128 bits, in hex format')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100394 else:
395 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
396
Alexander Chemerisd17ca3d2017-07-18 16:40:58 +0300397 # OPC (random)
Harald Welte93b38cd2012-03-22 14:31:36 +0100398 if opts.opc is not None:
399 opc = opts.opc
400 if not re.match('^[0-9a-fA-F]{32}$', opc):
401 raise ValueError('OPC needs to be 128 bits, in hex format')
402
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100403 elif opts.op is not None:
404 opc = derive_milenage_opc(ki, opts.op)
Harald Welte93b38cd2012-03-22 14:31:36 +0100405 else:
406 opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
407
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200408
409 pin_adm = None
410
Jan Balkec3ebd332015-01-26 12:22:55 +0100411 if opts.pin_adm is not None:
Philipp Maierd9824882018-06-13 09:21:59 +0200412 if len(opts.pin_adm) <= 8:
413 pin_adm = ''.join(['%02x'%(ord(x)) for x in opts.pin_adm])
414 pin_adm = rpad(pin_adm, 16)
Jan Balkec3ebd332015-01-26 12:22:55 +0100415
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200416 else:
417 raise ValueError("PIN-ADM needs to be <=8 digits (ascii)")
418
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200419 if opts.pin_adm_hex is not None:
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200420 if len(opts.pin_adm_hex) == 16:
421 pin_adm = opts.pin_adm_hex
422 # Ensure that it's hex-encoded
423 try:
424 try_encode = h2b(pin_adm)
425 except ValueError:
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200426 raise ValueError("PIN-ADM needs to be hex encoded using this option")
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200427 else:
428 raise ValueError("PIN-ADM needs to be exactly 16 digits (hex encoded)")
Harald Welte93b38cd2012-03-22 14:31:36 +0100429
Sylvain Munaut76504e02010-12-07 00:24:32 +0100430 # Return that
431 return {
432 'name' : opts.name,
433 'iccid' : iccid,
434 'mcc' : mcc,
435 'mnc' : mnc,
436 'imsi' : imsi,
437 'smsp' : smsp,
438 'ki' : ki,
Harald Welte93b38cd2012-03-22 14:31:36 +0100439 'opc' : opc,
Alexander Chemeris21885242013-07-02 16:56:55 +0400440 'acc' : acc,
Jan Balkec3ebd332015-01-26 12:22:55 +0100441 'pin_adm' : pin_adm,
Supreeth Herle5a541012019-12-22 08:59:16 +0100442 'msisdn' : opts.msisdn,
Sylvain Munaut76504e02010-12-07 00:24:32 +0100443 }
444
445
446def print_parameters(params):
447
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200448 s = ["Generated card parameters :"]
449 if 'name' in params:
450 s.append(" > Name : %(name)s")
451 if 'smsp' in params:
452 s.append(" > SMSP : %(smsp)s")
453 s.append(" > ICCID : %(iccid)s")
Philipp Maierbe069e22019-09-12 12:52:43 +0200454 s.append(" > MCC/MNC : %(mcc)s/%(mnc)s")
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200455 s.append(" > IMSI : %(imsi)s")
456 s.append(" > Ki : %(ki)s")
457 s.append(" > OPC : %(opc)s")
458 if 'acc' in params:
459 s.append(" > ACC : %(acc)s")
460 s.append(" > ADM1(hex): %(pin_adm)s")
461 print("\n".join(s) % params)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100462
463
Harald Welte130524b2012-08-13 15:53:43 +0200464def write_params_csv(opts, params):
465 # csv
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100466 if opts.write_csv:
467 import csv
Harald Welte93b38cd2012-03-22 14:31:36 +0100468 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100469 f = open(opts.write_csv, 'a')
470 cw = csv.writer(f)
471 cw.writerow([params[x] for x in row])
472 f.close()
473
Daniel Willmann164b9632019-09-03 19:13:51 +0200474def _read_params_csv(opts, iccid=None, imsi=None):
Harald Welte7f62cec2012-08-13 20:07:41 +0200475 import csv
Harald Welte7f62cec2012-08-13 20:07:41 +0200476 f = open(opts.read_csv, 'r')
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200477 cr = csv.DictReader(f)
Philipp Maier120a0002019-09-12 13:11:45 +0200478
479 # Lower-case fieldnames
480 cr.fieldnames = [ field.lower() for field in cr.fieldnames ]
481
Harald Welte7f62cec2012-08-13 20:07:41 +0200482 i = 0
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200483 if not 'iccid' in cr.fieldnames:
484 raise Exception("CSV file in wrong format!")
Harald Welte7f62cec2012-08-13 20:07:41 +0200485 for row in cr:
Daniel Willmann164b9632019-09-03 19:13:51 +0200486 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 +0200487 if opts.num == i:
Harald Weltec26b8292012-08-15 15:25:51 +0200488 f.close()
489 return row;
490 i += 1
Daniel Willmann164b9632019-09-03 19:13:51 +0200491 if row['iccid'] == iccid:
492 f.close()
493 return row;
494
Harald Welte7f62cec2012-08-13 20:07:41 +0200495 if row['imsi'] == imsi:
Harald Weltec26b8292012-08-15 15:25:51 +0200496 f.close()
497 return row;
Harald Welte7f62cec2012-08-13 20:07:41 +0200498
499 f.close()
Harald Weltec26b8292012-08-15 15:25:51 +0200500 return None
501
Daniel Willmann164b9632019-09-03 19:13:51 +0200502def read_params_csv(opts, imsi=None, iccid=None):
503 row = _read_params_csv(opts, iccid=iccid, imsi=imsi)
Harald Weltec26b8292012-08-15 15:25:51 +0200504 if row is not None:
Philipp Maier7592eee2019-09-12 13:03:23 +0200505 row['mcc'] = row.get('mcc', mcc_from_imsi(row.get('imsi')))
506 row['mnc'] = row.get('mnc', mnc_from_imsi(row.get('imsi')))
507
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200508 pin_adm = None
509 # We need to escape the pin_adm we get from the csv
510 if 'pin_adm' in row:
511 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['pin_adm']])
512 # Stay compatible to the odoo csv format
513 elif 'adm1' in row:
514 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['adm1']])
515 if pin_adm:
516 row['pin_adm'] = rpad(pin_adm, 16)
Philipp Maiere053da52019-09-05 13:08:36 +0200517
518 # If the CSV-File defines a pin_adm_hex field use this field to
519 # generate pin_adm from that.
520 pin_adm_hex = row.get('pin_adm_hex')
521 if pin_adm_hex:
522 if len(pin_adm_hex) == 16:
523 row['pin_adm'] = pin_adm_hex
524 # Ensure that it's hex-encoded
525 try:
526 try_encode = h2b(pin_adm)
527 except ValueError:
528 raise ValueError("pin_adm_hex needs to be hex encoded using this option")
529 else:
530 raise ValueError("pin_adm_hex needs to be exactly 16 digits (hex encoded)")
531
Harald Welte7f62cec2012-08-13 20:07:41 +0200532 return row
533
Harald Weltec26b8292012-08-15 15:25:51 +0200534
Harald Welte130524b2012-08-13 15:53:43 +0200535def write_params_hlr(opts, params):
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100536 # SQLite3 OpenBSC HLR
537 if opts.write_hlr:
538 import sqlite3
539 conn = sqlite3.connect(opts.write_hlr)
540
541 c = conn.execute(
542 'INSERT INTO Subscriber ' +
543 '(imsi, name, extension, authorized, created, updated) ' +
544 'VALUES ' +
545 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
546 [
547 params['imsi'],
548 params['name'],
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200549 '9' + params['iccid'][-5:-1]
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100550 ],
551 )
552 sub_id = c.lastrowid
553 c.close()
554
555 c = conn.execute(
556 'INSERT INTO AuthKeys ' +
557 '(subscriber_id, algorithm_id, a3a8_ki)' +
558 'VALUES ' +
559 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100560 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100561 )
562
563 conn.commit()
564 conn.close()
565
Harald Welte130524b2012-08-13 15:53:43 +0200566def write_parameters(opts, params):
567 write_params_csv(opts, params)
Harald Welte7f62cec2012-08-13 20:07:41 +0200568 write_params_hlr(opts, params)
Harald Welte130524b2012-08-13 15:53:43 +0200569
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100570
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100571BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
572BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100573
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100574def init_batch(opts):
575 # Need to do something ?
576 if not opts.batch_mode:
577 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100578
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100579 for k in BATCH_INCOMPATIBLE:
580 if getattr(opts, k):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700581 print("Incompatible option with batch_state: %s" % (k,))
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100582 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100583
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100584 # Don't load state if there is none ...
585 if not opts.batch_state:
586 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100587
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100588 if not os.path.isfile(opts.batch_state):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700589 print("No state file yet")
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100590 return
591
592 # Get stored data
593 fh = open(opts.batch_state)
594 d = json.loads(fh.read())
595 fh.close()
596
597 for k,v in d.iteritems():
598 setattr(opts, k, v)
599
600
601def save_batch(opts):
602 # Need to do something ?
603 if not opts.batch_mode or not opts.batch_state:
604 return
605
606 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
607 fh = open(opts.batch_state, 'w')
608 fh.write(d)
609 fh.close()
610
611
Philipp Maierc5b422e2019-08-30 11:41:02 +0200612def process_card(opts, first, card_handler):
613
614 if opts.dry_run is False:
615 # Connect transport
616 card_handler.get(first)
617
618 if opts.dry_run is False:
619 # Get card
Supreeth Herle4c306ab2020-03-18 11:38:00 +0100620 card = card_detect(opts.type, scc)
Philipp Maierc5b422e2019-08-30 11:41:02 +0200621 if card is None:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700622 print("No card detected!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200623 return -1
624
625 # Probe only
626 if opts.probe:
627 return 0
628
629 # Erase if requested
630 if opts.erase:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700631 print("Formatting ...")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200632 card.erase()
633 card.reset()
634
635 # Generate parameters
636 if opts.source == 'cmdline':
637 cp = gen_parameters(opts)
638 elif opts.source == 'csv':
639 imsi = None
640 iccid = None
641 if opts.read_iccid:
642 if opts.dry_run:
643 # Connect transport
644 card_handler.get(false)
645 (res,_) = scc.read_binary(['3f00', '2fe2'], length=10)
646 iccid = dec_iccid(res)
647 elif opts.read_imsi:
648 if opts.dry_run:
649 # Connect transport
650 card_handler.get(false)
651 (res,_) = scc.read_binary(EF['IMSI'])
652 imsi = swap_nibbles(res)[3:]
653 else:
654 imsi = opts.imsi
655 cp = read_params_csv(opts, imsi=imsi, iccid=iccid)
656 if cp is None:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700657 print("Error reading parameters from CSV file!\n")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200658 return 2
659 print_parameters(cp)
660
661 if opts.dry_run is False:
662 # Program the card
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700663 print("Programming ...")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200664 card.program(cp)
665 else:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700666 print("Dry Run: NOT PROGRAMMING!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200667
668 # Write parameters permanently
669 write_parameters(opts, cp)
670
671 # Batch mode state update and save
672 if opts.num is not None:
673 opts.num += 1
674 save_batch(opts)
675
676 card_handler.done()
677 return 0
678
679
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100680if __name__ == '__main__':
681
682 # Parse options
683 opts = parse_options()
684
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700685 # Init card reader driver
686 if opts.pcsc_dev is not None:
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700687 print("Using PC/SC reader (dev=%d) interface"
688 % opts.pcsc_dev)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100689 from pySim.transport.pcsc import PcscSimLink
690 sl = PcscSimLink(opts.pcsc_dev)
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +0700691 elif opts.osmocon_sock is not None:
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700692 print("Using Calypso-based (OsmocomBB, sock=%s) reader interface"
693 % opts.osmocon_sock)
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +0700694 from pySim.transport.calypso import CalypsoSimLink
695 sl = CalypsoSimLink(sock_path=opts.osmocon_sock)
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700696 else: # Serial reader is default
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700697 print("Using serial reader (port=%s, baudrate=%d) interface"
698 % (opts.device, opts.baudrate))
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700699 from pySim.transport.serial import SerialSimLink
700 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100701
702 # Create command layer
703 scc = SimCardCommands(transport=sl)
704
Philipp Maier196b08c2019-09-12 11:49:44 +0200705 # If we use a CSV file as data input, check if the CSV file exists.
706 if opts.source == 'csv':
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700707 print("Using CSV file as data input: " + str(opts.read_csv))
Philipp Maier196b08c2019-09-12 11:49:44 +0200708 if not os.path.isfile(opts.read_csv):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700709 print("CSV file not found!")
Philipp Maier196b08c2019-09-12 11:49:44 +0200710 sys.exit(1)
711
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100712 # Batch mode init
713 init_batch(opts)
714
Philipp Maierc5b422e2019-08-30 11:41:02 +0200715 if opts.card_handler:
716 card_handler = card_handler_auto(sl, opts.card_handler)
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200717 else:
Philipp Maierc5b422e2019-08-30 11:41:02 +0200718 card_handler = card_handler(sl)
719
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100720 # Iterate
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100721 first = True
722 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100723
Philipp Maierc5b422e2019-08-30 11:41:02 +0200724 while 1:
725 try:
726 rc = process_card(opts, first, card_handler)
727 except (KeyboardInterrupt):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700728 print("")
729 print("Terminated by user!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200730 sys.exit(0)
731 except (SystemExit):
732 raise
733 except:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700734 print("")
735 print("Card programming failed with an execption:")
736 print("---------------------8<---------------------")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200737 traceback.print_exc()
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700738 print("---------------------8<---------------------")
739 print("")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200740 rc = -1
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200741
Philipp Maierc5b422e2019-08-30 11:41:02 +0200742 # Something did not work as well as expected, however, lets
743 # make sure the card is pulled from the reader.
744 if rc != 0:
745 card_handler.error()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100746
Philipp Maierc5b422e2019-08-30 11:41:02 +0200747 # If we are not in batch mode we are done in any case, so lets
748 # exit here.
749 if not opts.batch_mode:
750 sys.exit(rc)
751
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100752 first = False