blob: c7099596e4eeb4faab06b583745b6c02502b068f [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 )
Supreeth Herlefc83e432020-05-06 11:48:46 +0200109 parser.add_option("--mnclen", dest="mnclen", type="choice",
110 help="Length of Mobile Network Code [default: %default]",
111 default=2,
112 choices=[2, 3],
113 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100114 parser.add_option("-m", "--smsc", dest="smsc",
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200115 help="SMSC number (Start with + for international no.) [default: '00 + country code + 5555']",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100116 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100117 parser.add_option("-M", "--smsp", dest="smsp",
118 help="Raw SMSP content in hex [default: auto from SMSC]",
119 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100120
121 parser.add_option("-s", "--iccid", dest="iccid", metavar="ID",
122 help="Integrated Circuit Card ID",
123 )
124 parser.add_option("-i", "--imsi", dest="imsi",
125 help="International Mobile Subscriber Identity",
126 )
Supreeth Herle5a541012019-12-22 08:59:16 +0100127 parser.add_option("--msisdn", dest="msisdn",
128 help="Mobile Subscriber Integrated Services Digital Number",
129 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100130 parser.add_option("-k", "--ki", dest="ki",
131 help="Ki (default is to randomize)",
132 )
Harald Welte93b38cd2012-03-22 14:31:36 +0100133 parser.add_option("-o", "--opc", dest="opc",
134 help="OPC (default is to randomize)",
135 )
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100136 parser.add_option("--op", dest="op",
137 help="Set OP to derive OPC from OP and KI",
138 )
Alexander Chemeris21885242013-07-02 16:56:55 +0400139 parser.add_option("--acc", dest="acc",
140 help="Set ACC bits (Access Control Code). not all card types are supported",
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200141 )
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200142 parser.add_option("--read-imsi", dest="read_imsi", action="store_true",
143 help="Read the IMSI from the CARD", default=False
Alexander Chemeris21885242013-07-02 16:56:55 +0400144 )
Daniel Willmann164b9632019-09-03 19:13:51 +0200145 parser.add_option("--read-iccid", dest="read_iccid", action="store_true",
146 help="Read the ICCID from the CARD", default=False
147 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100148 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
149 help="Secret used for ICCID/IMSI autogen",
150 )
151 parser.add_option("-j", "--num", dest="num", type=int,
152 help="Card # used for ICCID/IMSI autogen",
153 )
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100154 parser.add_option("--batch", dest="batch_mode",
155 help="Enable batch mode [default: %default]",
156 default=False, action='store_true',
157 )
158 parser.add_option("--batch-state", dest="batch_state", metavar="FILE",
159 help="Optional batch state file",
160 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100161
Harald Welte7f62cec2012-08-13 20:07:41 +0200162 # if mode is "csv"
163 parser.add_option("--read-csv", dest="read_csv", metavar="FILE",
164 help="Read parameters from CSV file rather than command line")
165
166
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100167 parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
168 help="Append generated parameters in CSV file",
169 )
170 parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
171 help="Append generated parameters to OpenBSC HLR sqlite3",
172 )
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200173 parser.add_option("--dry-run", dest="dry_run",
174 help="Perform a 'dry run', don't actually program the card",
175 default=False, action="store_true")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200176 parser.add_option("--card_handler", dest="card_handler", metavar="FILE",
177 help="Use automatic card handling machine")
178
Sylvain Munaut76504e02010-12-07 00:24:32 +0100179 (options, args) = parser.parse_args()
180
181 if options.type == 'list':
182 for kls in _cards_classes:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700183 print(kls.name)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100184 sys.exit(0)
185
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200186 if options.probe:
187 return options
Philipp Maierac9dde62018-07-04 11:05:14 +0200188
Harald Welte7f62cec2012-08-13 20:07:41 +0200189 if options.source == 'csv':
Daniel Willmann164b9632019-09-03 19:13:51 +0200190 if (options.imsi is None) and (options.batch_mode is False) and (options.read_imsi is False) and (options.read_iccid is False):
191 parser.error("CSV mode needs either an IMSI, --read-imsi, --read-iccid or batch mode")
Harald Welte7f62cec2012-08-13 20:07:41 +0200192 if options.read_csv is None:
193 parser.error("CSV mode requires a CSV input file")
194 elif options.source == 'cmdline':
195 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
196 parser.error("If either IMSI or ICCID isn't specified, num is required")
197 else:
198 parser.error("Only `cmdline' and `csv' sources supported")
199
200 if (options.read_csv is not None) and (options.source != 'csv'):
201 parser.error("You cannot specify a CSV input file in source != csv")
202
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100203 if (options.batch_mode) and (options.num is None):
204 options.num = 0
205
Sylvain Munaut98d2b852010-12-23 20:27:25 +0100206 if (options.batch_mode):
207 if (options.imsi is not None) or (options.iccid is not None):
208 parser.error("Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more informations")
209
Sylvain Munaut76504e02010-12-07 00:24:32 +0100210 if args:
211 parser.error("Extraneous arguments")
212
213 return options
214
215
216def _digits(secret, usage, len, num):
217 s = hashlib.sha1(secret + usage + '%d' % num)
218 d = ''.join(['%02d'%ord(x) for x in s.digest()])
219 return d[0:len]
220
221def _mcc_mnc_digits(mcc, mnc):
222 return ('%03d%03d' if mnc > 100 else '%03d%02d') % (mcc, mnc)
223
224def _cc_digits(cc):
225 return ('%03d' if cc > 100 else '%02d') % cc
226
227def _isnum(s, l=-1):
228 return s.isdigit() and ((l== -1) or (len(s) == l))
229
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100230def _ishex(s, l=-1):
231 hc = '0123456789abcdef'
232 return all([x in hc for x in s.lower()]) and ((l== -1) or (len(s) == l))
233
Sylvain Munaut76504e02010-12-07 00:24:32 +0100234
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100235def _dbi_binary_quote(s):
236 # Count usage of each char
237 cnt = {}
238 for c in s:
239 cnt[c] = cnt.get(c, 0) + 1
240
241 # Find best offset
242 e = 0
243 m = len(s)
244 for i in range(1, 256):
245 if i == 39:
246 continue
247 sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
248 if sum_ < m:
249 m = sum_
250 e = i
251 if m == 0: # No overhead ? use this !
252 break;
Sylvain Munaut1a914432011-12-08 20:08:26 +0100253
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100254 # Generate output
255 out = []
256 out.append( chr(e) ) # Offset
257 for c in s:
258 x = (256 + ord(c) - e) % 256
259 if x in (0, 1, 39):
260 out.append('\x01')
261 out.append(chr(x+1))
262 else:
263 out.append(chr(x))
264
265 return ''.join(out)
266
Sylvain Munaut76504e02010-12-07 00:24:32 +0100267def gen_parameters(opts):
Jan Balkec3ebd332015-01-26 12:22:55 +0100268 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki, PIN-ADM from the
Sylvain Munaut76504e02010-12-07 00:24:32 +0100269 options given by the user"""
270
271 # MCC/MNC
272 mcc = opts.mcc
273 mnc = opts.mnc
274
275 if not ((0 < mcc < 999) and (0 < mnc < 999)):
276 raise ValueError('mcc & mnc must be between 0 and 999')
277
278 # Digitize country code (2 or 3 digits)
279 cc_digits = _cc_digits(opts.country)
280
281 # Digitize MCC/MNC (5 or 6 digits)
282 plmn_digits = _mcc_mnc_digits(mcc, mnc)
283
Supreeth Herle840a9e22020-01-21 13:32:46 +0100284 if opts.name is not None:
285 if len(opts.name) > 16:
286 raise ValueError('Service Provider Name must max 16 characters!');
287
Supreeth Herle5a541012019-12-22 08:59:16 +0100288 if opts.msisdn is not None:
289 msisdn = opts.msisdn
290 if msisdn[0] == '+':
291 msisdn = msisdn[1:]
292 if not msisdn.isdigit():
293 raise ValueError('MSISDN must be digits only! '
294 'Start with \'+\' for international numbers.')
295 if len(msisdn) > 10 * 2:
296 # TODO: Support MSISDN of length > 20 (10 Bytes)
297 raise ValueError('MSISDNs longer than 20 digits are not (yet) supported.')
298
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100299 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
Sylvain Munaut76504e02010-12-07 00:24:32 +0100300 if opts.iccid is not None:
301 iccid = opts.iccid
Todd Neal9eeadfc2018-04-25 15:36:29 -0500302 if not _isnum(iccid, 19) and not _isnum(iccid, 20):
303 raise ValueError('ICCID must be 19 or 20 digits !');
Sylvain Munaut76504e02010-12-07 00:24:32 +0100304
305 else:
306 if opts.num is None:
307 raise ValueError('Neither ICCID nor card number specified !')
308
309 iccid = (
310 '89' + # Common prefix (telecom)
311 cc_digits + # Country Code on 2/3 digits
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200312 plmn_digits # MCC/MNC on 5/6 digits
Sylvain Munaut76504e02010-12-07 00:24:32 +0100313 )
314
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100315 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100316
317 if opts.secret is None:
318 # The raw number
319 iccid += ('%%0%dd' % ml) % opts.num
320 else:
321 # Randomized digits
322 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
323
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100324 # Add checksum digit
325 iccid += ('%1d' % calculate_luhn(iccid))
326
Sylvain Munaut76504e02010-12-07 00:24:32 +0100327 # IMSI (15 digits usually)
328 if opts.imsi is not None:
329 imsi = opts.imsi
330 if not _isnum(imsi):
331 raise ValueError('IMSI must be digits only !')
332
333 else:
334 if opts.num is None:
335 raise ValueError('Neither IMSI nor card number specified !')
336
337 ml = 15 - len(plmn_digits)
338
339 if opts.secret is None:
340 # The raw number
341 msin = ('%%0%dd' % ml) % opts.num
342 else:
343 # Randomized digits
344 msin = _digits(opts.secret, 'imsi', ml, opts.num)
345
346 imsi = (
347 plmn_digits + # MCC/MNC on 5/6 digits
348 msin # MSIN
349 )
350
351 # SMSP
352 if opts.smsp is not None:
353 smsp = opts.smsp
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100354 if not _ishex(smsp):
355 raise ValueError('SMSP must be hex digits only !')
356 if len(smsp) < 28*2:
357 raise ValueError('SMSP must be at least 28 bytes')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100358
359 else:
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200360 ton = "81"
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100361 if opts.smsc is not None:
362 smsc = opts.smsc
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200363 if smsc[0] == '+':
364 ton = "91"
365 smsc = smsc[1:]
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100366 if not _isnum(smsc):
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200367 raise ValueError('SMSC must be digits only!\n \
368 Start with \'+\' for international numbers')
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100369 else:
370 smsc = '00%d' % opts.country + '5555' # Hack ...
371
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200372 smsc = '%02d' % ((len(smsc) + 3)//2,) + ton + swap_nibbles(rpad(smsc, 20))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100373
374 smsp = (
375 'e1' + # Parameters indicator
376 'ff' * 12 + # TP-Destination address
377 smsc + # TP-Service Centre Address
378 '00' + # TP-Protocol identifier
379 '00' + # TP-Data coding scheme
380 '00' # TP-Validity period
381 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100382
Alexander Chemeris21885242013-07-02 16:56:55 +0400383 # ACC
384 if opts.acc is not None:
385 acc = opts.acc
386 if not _ishex(acc):
387 raise ValueError('ACC must be hex digits only !')
388 if len(acc) != 2*2:
389 raise ValueError('ACC must be exactly 2 bytes')
390
391 else:
392 acc = None
393
Sylvain Munaut76504e02010-12-07 00:24:32 +0100394 # Ki (random)
395 if opts.ki is not None:
396 ki = opts.ki
397 if not re.match('^[0-9a-fA-F]{32}$', ki):
398 raise ValueError('Ki needs to be 128 bits, in hex format')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100399 else:
400 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
401
Alexander Chemerisd17ca3d2017-07-18 16:40:58 +0300402 # OPC (random)
Harald Welte93b38cd2012-03-22 14:31:36 +0100403 if opts.opc is not None:
404 opc = opts.opc
405 if not re.match('^[0-9a-fA-F]{32}$', opc):
406 raise ValueError('OPC needs to be 128 bits, in hex format')
407
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100408 elif opts.op is not None:
409 opc = derive_milenage_opc(ki, opts.op)
Harald Welte93b38cd2012-03-22 14:31:36 +0100410 else:
411 opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
412
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200413
414 pin_adm = None
415
Jan Balkec3ebd332015-01-26 12:22:55 +0100416 if opts.pin_adm is not None:
Philipp Maierd9824882018-06-13 09:21:59 +0200417 if len(opts.pin_adm) <= 8:
418 pin_adm = ''.join(['%02x'%(ord(x)) for x in opts.pin_adm])
419 pin_adm = rpad(pin_adm, 16)
Jan Balkec3ebd332015-01-26 12:22:55 +0100420
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200421 else:
422 raise ValueError("PIN-ADM needs to be <=8 digits (ascii)")
423
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200424 if opts.pin_adm_hex is not None:
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200425 if len(opts.pin_adm_hex) == 16:
426 pin_adm = opts.pin_adm_hex
427 # Ensure that it's hex-encoded
428 try:
429 try_encode = h2b(pin_adm)
430 except ValueError:
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200431 raise ValueError("PIN-ADM needs to be hex encoded using this option")
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200432 else:
433 raise ValueError("PIN-ADM needs to be exactly 16 digits (hex encoded)")
Harald Welte93b38cd2012-03-22 14:31:36 +0100434
Sylvain Munaut76504e02010-12-07 00:24:32 +0100435 # Return that
436 return {
437 'name' : opts.name,
438 'iccid' : iccid,
439 'mcc' : mcc,
440 'mnc' : mnc,
441 'imsi' : imsi,
442 'smsp' : smsp,
443 'ki' : ki,
Harald Welte93b38cd2012-03-22 14:31:36 +0100444 'opc' : opc,
Alexander Chemeris21885242013-07-02 16:56:55 +0400445 'acc' : acc,
Jan Balkec3ebd332015-01-26 12:22:55 +0100446 'pin_adm' : pin_adm,
Supreeth Herle5a541012019-12-22 08:59:16 +0100447 'msisdn' : opts.msisdn,
Sylvain Munaut76504e02010-12-07 00:24:32 +0100448 }
449
450
451def print_parameters(params):
452
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200453 s = ["Generated card parameters :"]
454 if 'name' in params:
455 s.append(" > Name : %(name)s")
456 if 'smsp' in params:
457 s.append(" > SMSP : %(smsp)s")
458 s.append(" > ICCID : %(iccid)s")
Philipp Maierbe069e22019-09-12 12:52:43 +0200459 s.append(" > MCC/MNC : %(mcc)s/%(mnc)s")
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200460 s.append(" > IMSI : %(imsi)s")
461 s.append(" > Ki : %(ki)s")
462 s.append(" > OPC : %(opc)s")
463 if 'acc' in params:
464 s.append(" > ACC : %(acc)s")
465 s.append(" > ADM1(hex): %(pin_adm)s")
466 print("\n".join(s) % params)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100467
468
Harald Welte130524b2012-08-13 15:53:43 +0200469def write_params_csv(opts, params):
470 # csv
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100471 if opts.write_csv:
472 import csv
Harald Welte93b38cd2012-03-22 14:31:36 +0100473 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100474 f = open(opts.write_csv, 'a')
475 cw = csv.writer(f)
476 cw.writerow([params[x] for x in row])
477 f.close()
478
Daniel Willmann164b9632019-09-03 19:13:51 +0200479def _read_params_csv(opts, iccid=None, imsi=None):
Harald Welte7f62cec2012-08-13 20:07:41 +0200480 import csv
Harald Welte7f62cec2012-08-13 20:07:41 +0200481 f = open(opts.read_csv, 'r')
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200482 cr = csv.DictReader(f)
Philipp Maier120a0002019-09-12 13:11:45 +0200483
484 # Lower-case fieldnames
485 cr.fieldnames = [ field.lower() for field in cr.fieldnames ]
486
Harald Welte7f62cec2012-08-13 20:07:41 +0200487 i = 0
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200488 if not 'iccid' in cr.fieldnames:
489 raise Exception("CSV file in wrong format!")
Harald Welte7f62cec2012-08-13 20:07:41 +0200490 for row in cr:
Daniel Willmann164b9632019-09-03 19:13:51 +0200491 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 +0200492 if opts.num == i:
Harald Weltec26b8292012-08-15 15:25:51 +0200493 f.close()
494 return row;
495 i += 1
Daniel Willmann164b9632019-09-03 19:13:51 +0200496 if row['iccid'] == iccid:
497 f.close()
498 return row;
499
Harald Welte7f62cec2012-08-13 20:07:41 +0200500 if row['imsi'] == imsi:
Harald Weltec26b8292012-08-15 15:25:51 +0200501 f.close()
502 return row;
Harald Welte7f62cec2012-08-13 20:07:41 +0200503
504 f.close()
Harald Weltec26b8292012-08-15 15:25:51 +0200505 return None
506
Daniel Willmann164b9632019-09-03 19:13:51 +0200507def read_params_csv(opts, imsi=None, iccid=None):
508 row = _read_params_csv(opts, iccid=iccid, imsi=imsi)
Harald Weltec26b8292012-08-15 15:25:51 +0200509 if row is not None:
Philipp Maier7592eee2019-09-12 13:03:23 +0200510 row['mcc'] = row.get('mcc', mcc_from_imsi(row.get('imsi')))
511 row['mnc'] = row.get('mnc', mnc_from_imsi(row.get('imsi')))
512
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200513 pin_adm = None
514 # We need to escape the pin_adm we get from the csv
515 if 'pin_adm' in row:
516 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['pin_adm']])
517 # Stay compatible to the odoo csv format
518 elif 'adm1' in row:
519 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['adm1']])
520 if pin_adm:
521 row['pin_adm'] = rpad(pin_adm, 16)
Philipp Maiere053da52019-09-05 13:08:36 +0200522
523 # If the CSV-File defines a pin_adm_hex field use this field to
524 # generate pin_adm from that.
525 pin_adm_hex = row.get('pin_adm_hex')
526 if pin_adm_hex:
527 if len(pin_adm_hex) == 16:
528 row['pin_adm'] = pin_adm_hex
529 # Ensure that it's hex-encoded
530 try:
531 try_encode = h2b(pin_adm)
532 except ValueError:
533 raise ValueError("pin_adm_hex needs to be hex encoded using this option")
534 else:
535 raise ValueError("pin_adm_hex needs to be exactly 16 digits (hex encoded)")
536
Harald Welte7f62cec2012-08-13 20:07:41 +0200537 return row
538
Harald Weltec26b8292012-08-15 15:25:51 +0200539
Harald Welte130524b2012-08-13 15:53:43 +0200540def write_params_hlr(opts, params):
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100541 # SQLite3 OpenBSC HLR
542 if opts.write_hlr:
543 import sqlite3
544 conn = sqlite3.connect(opts.write_hlr)
545
546 c = conn.execute(
547 'INSERT INTO Subscriber ' +
548 '(imsi, name, extension, authorized, created, updated) ' +
549 'VALUES ' +
550 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
551 [
552 params['imsi'],
553 params['name'],
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200554 '9' + params['iccid'][-5:-1]
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100555 ],
556 )
557 sub_id = c.lastrowid
558 c.close()
559
560 c = conn.execute(
561 'INSERT INTO AuthKeys ' +
562 '(subscriber_id, algorithm_id, a3a8_ki)' +
563 'VALUES ' +
564 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100565 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100566 )
567
568 conn.commit()
569 conn.close()
570
Harald Welte130524b2012-08-13 15:53:43 +0200571def write_parameters(opts, params):
572 write_params_csv(opts, params)
Harald Welte7f62cec2012-08-13 20:07:41 +0200573 write_params_hlr(opts, params)
Harald Welte130524b2012-08-13 15:53:43 +0200574
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100575
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100576BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
577BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100578
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100579def init_batch(opts):
580 # Need to do something ?
581 if not opts.batch_mode:
582 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100583
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100584 for k in BATCH_INCOMPATIBLE:
585 if getattr(opts, k):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700586 print("Incompatible option with batch_state: %s" % (k,))
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100587 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100588
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100589 # Don't load state if there is none ...
590 if not opts.batch_state:
591 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100592
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100593 if not os.path.isfile(opts.batch_state):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700594 print("No state file yet")
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100595 return
596
597 # Get stored data
598 fh = open(opts.batch_state)
599 d = json.loads(fh.read())
600 fh.close()
601
602 for k,v in d.iteritems():
603 setattr(opts, k, v)
604
605
606def save_batch(opts):
607 # Need to do something ?
608 if not opts.batch_mode or not opts.batch_state:
609 return
610
611 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
612 fh = open(opts.batch_state, 'w')
613 fh.write(d)
614 fh.close()
615
616
Philipp Maierc5b422e2019-08-30 11:41:02 +0200617def process_card(opts, first, card_handler):
618
619 if opts.dry_run is False:
620 # Connect transport
621 card_handler.get(first)
622
623 if opts.dry_run is False:
624 # Get card
Supreeth Herle4c306ab2020-03-18 11:38:00 +0100625 card = card_detect(opts.type, scc)
Philipp Maierc5b422e2019-08-30 11:41:02 +0200626 if card is None:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700627 print("No card detected!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200628 return -1
629
630 # Probe only
631 if opts.probe:
632 return 0
633
634 # Erase if requested
635 if opts.erase:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700636 print("Formatting ...")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200637 card.erase()
638 card.reset()
639
640 # Generate parameters
641 if opts.source == 'cmdline':
642 cp = gen_parameters(opts)
643 elif opts.source == 'csv':
644 imsi = None
645 iccid = None
646 if opts.read_iccid:
647 if opts.dry_run:
648 # Connect transport
649 card_handler.get(false)
650 (res,_) = scc.read_binary(['3f00', '2fe2'], length=10)
651 iccid = dec_iccid(res)
652 elif opts.read_imsi:
653 if opts.dry_run:
654 # Connect transport
655 card_handler.get(false)
656 (res,_) = scc.read_binary(EF['IMSI'])
657 imsi = swap_nibbles(res)[3:]
658 else:
659 imsi = opts.imsi
660 cp = read_params_csv(opts, imsi=imsi, iccid=iccid)
661 if cp is None:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700662 print("Error reading parameters from CSV file!\n")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200663 return 2
664 print_parameters(cp)
665
666 if opts.dry_run is False:
667 # Program the card
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700668 print("Programming ...")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200669 card.program(cp)
670 else:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700671 print("Dry Run: NOT PROGRAMMING!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200672
673 # Write parameters permanently
674 write_parameters(opts, cp)
675
676 # Batch mode state update and save
677 if opts.num is not None:
678 opts.num += 1
679 save_batch(opts)
680
681 card_handler.done()
682 return 0
683
684
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100685if __name__ == '__main__':
686
687 # Parse options
688 opts = parse_options()
689
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700690 # Init card reader driver
691 if opts.pcsc_dev is not None:
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700692 print("Using PC/SC reader (dev=%d) interface"
693 % opts.pcsc_dev)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100694 from pySim.transport.pcsc import PcscSimLink
695 sl = PcscSimLink(opts.pcsc_dev)
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +0700696 elif opts.osmocon_sock is not None:
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700697 print("Using Calypso-based (OsmocomBB, sock=%s) reader interface"
698 % opts.osmocon_sock)
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +0700699 from pySim.transport.calypso import CalypsoSimLink
700 sl = CalypsoSimLink(sock_path=opts.osmocon_sock)
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700701 else: # Serial reader is default
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700702 print("Using serial reader (port=%s, baudrate=%d) interface"
703 % (opts.device, opts.baudrate))
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700704 from pySim.transport.serial import SerialSimLink
705 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100706
707 # Create command layer
708 scc = SimCardCommands(transport=sl)
709
Philipp Maier196b08c2019-09-12 11:49:44 +0200710 # If we use a CSV file as data input, check if the CSV file exists.
711 if opts.source == 'csv':
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700712 print("Using CSV file as data input: " + str(opts.read_csv))
Philipp Maier196b08c2019-09-12 11:49:44 +0200713 if not os.path.isfile(opts.read_csv):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700714 print("CSV file not found!")
Philipp Maier196b08c2019-09-12 11:49:44 +0200715 sys.exit(1)
716
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100717 # Batch mode init
718 init_batch(opts)
719
Philipp Maierc5b422e2019-08-30 11:41:02 +0200720 if opts.card_handler:
721 card_handler = card_handler_auto(sl, opts.card_handler)
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200722 else:
Philipp Maierc5b422e2019-08-30 11:41:02 +0200723 card_handler = card_handler(sl)
724
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100725 # Iterate
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100726 first = True
727 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100728
Philipp Maierc5b422e2019-08-30 11:41:02 +0200729 while 1:
730 try:
731 rc = process_card(opts, first, card_handler)
732 except (KeyboardInterrupt):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700733 print("")
734 print("Terminated by user!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200735 sys.exit(0)
736 except (SystemExit):
737 raise
738 except:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700739 print("")
740 print("Card programming failed with an execption:")
741 print("---------------------8<---------------------")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200742 traceback.print_exc()
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700743 print("---------------------8<---------------------")
744 print("")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200745 rc = -1
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200746
Philipp Maierc5b422e2019-08-30 11:41:02 +0200747 # Something did not work as well as expected, however, lets
748 # make sure the card is pulled from the reader.
749 if rc != 0:
750 card_handler.error()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100751
Philipp Maierc5b422e2019-08-30 11:41:02 +0200752 # If we are not in batch mode we are done in any case, so lets
753 # exit here.
754 if not opts.batch_mode:
755 sys.exit(rc)
756
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100757 first = False