blob: 13e8bb54545193e67969fbefaea6b6f7da7a784d [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
33
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +010034try:
35 import json
Holger Hans Peter Freyther5dffefb2011-11-22 21:18:06 +010036except ImportError:
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +010037 # Python < 2.5
38 import simplejson as json
39
Sylvain Munaut76504e02010-12-07 00:24:32 +010040from pySim.commands import SimCardCommands
41from pySim.cards import _cards_classes
Daniel Willmann164b9632019-09-03 19:13:51 +020042from pySim.utils import h2b, swap_nibbles, rpad, derive_milenage_opc, calculate_luhn, dec_iccid
Philipp Maierf7792312018-06-11 17:11:39 +020043from pySim.ts_51_011 import EF
Sylvain Munaut76504e02010-12-07 00:24:32 +010044
45def parse_options():
46
47 parser = OptionParser(usage="usage: %prog [options]")
48
49 parser.add_option("-d", "--device", dest="device", metavar="DEV",
50 help="Serial Device for SIM access [default: %default]",
51 default="/dev/ttyUSB0",
52 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010053 parser.add_option("-b", "--baud", dest="baudrate", type="int", metavar="BAUD",
54 help="Baudrate used for SIM access [default: %default]",
55 default=9600,
56 )
Sylvain Munaut9c8729a2010-12-08 23:20:27 +010057 parser.add_option("-p", "--pcsc-device", dest="pcsc_dev", type='int', metavar="PCSC",
Sylvain Munaute9fdecb2010-12-08 22:33:19 +010058 help="Which PC/SC reader number for SIM access",
59 default=None,
60 )
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +070061 parser.add_option("--osmocon", dest="osmocon_sock", metavar="PATH",
62 help="Socket path for Calypso (e.g. Motorola C1XX) based reader (via OsmocomBB)",
63 default=None,
64 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010065 parser.add_option("-t", "--type", dest="type",
66 help="Card type (user -t list to view) [default: %default]",
67 default="auto",
68 )
Philipp Maierac9dde62018-07-04 11:05:14 +020069 parser.add_option("-T", "--probe", dest="probe",
70 help="Determine card type",
71 default=False, action="store_true"
72 )
Jan Balkec3ebd332015-01-26 12:22:55 +010073 parser.add_option("-a", "--pin-adm", dest="pin_adm",
74 help="ADM PIN used for provisioning (overwrites default)",
75 )
Daniel Willmannf432b2b2018-06-15 07:31:50 +020076 parser.add_option("-A", "--pin-adm-hex", dest="pin_adm_hex",
77 help="ADM PIN used for provisioning, as hex string (16 characters long",
78 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010079 parser.add_option("-e", "--erase", dest="erase", action='store_true',
80 help="Erase beforehand [default: %default]",
81 default=False,
82 )
83
Harald Welte7f62cec2012-08-13 20:07:41 +020084 parser.add_option("-S", "--source", dest="source",
85 help="Data Source[default: %default]",
86 default="cmdline",
87 )
88
89 # if mode is "cmdline"
Sylvain Munaut76504e02010-12-07 00:24:32 +010090 parser.add_option("-n", "--name", dest="name",
91 help="Operator name [default: %default]",
92 default="Magic",
93 )
94 parser.add_option("-c", "--country", dest="country", type="int", metavar="CC",
95 help="Country code [default: %default]",
96 default=1,
97 )
98 parser.add_option("-x", "--mcc", dest="mcc", type="int",
99 help="Mobile Country Code [default: %default]",
100 default=901,
101 )
102 parser.add_option("-y", "--mnc", dest="mnc", type="int",
Sylvain Munaut17716032010-12-08 22:33:51 +0100103 help="Mobile Network Code [default: %default]",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100104 default=55,
105 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100106 parser.add_option("-m", "--smsc", dest="smsc",
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200107 help="SMSC number (Start with + for international no.) [default: '00 + country code + 5555']",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100108 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100109 parser.add_option("-M", "--smsp", dest="smsp",
110 help="Raw SMSP content in hex [default: auto from SMSC]",
111 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100112
113 parser.add_option("-s", "--iccid", dest="iccid", metavar="ID",
114 help="Integrated Circuit Card ID",
115 )
116 parser.add_option("-i", "--imsi", dest="imsi",
117 help="International Mobile Subscriber Identity",
118 )
119 parser.add_option("-k", "--ki", dest="ki",
120 help="Ki (default is to randomize)",
121 )
Harald Welte93b38cd2012-03-22 14:31:36 +0100122 parser.add_option("-o", "--opc", dest="opc",
123 help="OPC (default is to randomize)",
124 )
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100125 parser.add_option("--op", dest="op",
126 help="Set OP to derive OPC from OP and KI",
127 )
Alexander Chemeris21885242013-07-02 16:56:55 +0400128 parser.add_option("--acc", dest="acc",
129 help="Set ACC bits (Access Control Code). not all card types are supported",
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200130 )
131 parser.add_option("--read-imsi", dest="read_imsi", action="store_true",
132 help="Read the IMSI from the CARD", default=False
Alexander Chemeris21885242013-07-02 16:56:55 +0400133 )
Daniel Willmann164b9632019-09-03 19:13:51 +0200134 parser.add_option("--read-iccid", dest="read_iccid", action="store_true",
135 help="Read the ICCID from the CARD", default=False
136 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100137 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
138 help="Secret used for ICCID/IMSI autogen",
139 )
140 parser.add_option("-j", "--num", dest="num", type=int,
141 help="Card # used for ICCID/IMSI autogen",
142 )
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100143 parser.add_option("--batch", dest="batch_mode",
144 help="Enable batch mode [default: %default]",
145 default=False, action='store_true',
146 )
147 parser.add_option("--batch-state", dest="batch_state", metavar="FILE",
148 help="Optional batch state file",
149 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100150
Harald Welte7f62cec2012-08-13 20:07:41 +0200151 # if mode is "csv"
152 parser.add_option("--read-csv", dest="read_csv", metavar="FILE",
153 help="Read parameters from CSV file rather than command line")
154
155
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100156 parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
157 help="Append generated parameters in CSV file",
158 )
159 parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
160 help="Append generated parameters to OpenBSC HLR sqlite3",
161 )
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200162 parser.add_option("--dry-run", dest="dry_run",
163 help="Perform a 'dry run', don't actually program the card",
164 default=False, action="store_true")
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100165
Sylvain Munaut76504e02010-12-07 00:24:32 +0100166 (options, args) = parser.parse_args()
167
168 if options.type == 'list':
169 for kls in _cards_classes:
170 print kls.name
171 sys.exit(0)
172
Philipp Maierac9dde62018-07-04 11:05:14 +0200173 if options.probe:
174 return options
175
Harald Welte7f62cec2012-08-13 20:07:41 +0200176 if options.source == 'csv':
Daniel Willmann164b9632019-09-03 19:13:51 +0200177 if (options.imsi is None) and (options.batch_mode is False) and (options.read_imsi is False) and (options.read_iccid is False):
178 parser.error("CSV mode needs either an IMSI, --read-imsi, --read-iccid or batch mode")
Harald Welte7f62cec2012-08-13 20:07:41 +0200179 if options.read_csv is None:
180 parser.error("CSV mode requires a CSV input file")
181 elif options.source == 'cmdline':
182 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
183 parser.error("If either IMSI or ICCID isn't specified, num is required")
184 else:
185 parser.error("Only `cmdline' and `csv' sources supported")
186
187 if (options.read_csv is not None) and (options.source != 'csv'):
188 parser.error("You cannot specify a CSV input file in source != csv")
189
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100190 if (options.batch_mode) and (options.num is None):
191 options.num = 0
192
Sylvain Munaut98d2b852010-12-23 20:27:25 +0100193 if (options.batch_mode):
194 if (options.imsi is not None) or (options.iccid is not None):
195 parser.error("Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more informations")
196
Sylvain Munaut76504e02010-12-07 00:24:32 +0100197 if args:
198 parser.error("Extraneous arguments")
199
200 return options
201
202
203def _digits(secret, usage, len, num):
204 s = hashlib.sha1(secret + usage + '%d' % num)
205 d = ''.join(['%02d'%ord(x) for x in s.digest()])
206 return d[0:len]
207
208def _mcc_mnc_digits(mcc, mnc):
209 return ('%03d%03d' if mnc > 100 else '%03d%02d') % (mcc, mnc)
210
211def _cc_digits(cc):
212 return ('%03d' if cc > 100 else '%02d') % cc
213
214def _isnum(s, l=-1):
215 return s.isdigit() and ((l== -1) or (len(s) == l))
216
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100217def _ishex(s, l=-1):
218 hc = '0123456789abcdef'
219 return all([x in hc for x in s.lower()]) and ((l== -1) or (len(s) == l))
220
Sylvain Munaut76504e02010-12-07 00:24:32 +0100221
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100222def _dbi_binary_quote(s):
223 # Count usage of each char
224 cnt = {}
225 for c in s:
226 cnt[c] = cnt.get(c, 0) + 1
227
228 # Find best offset
229 e = 0
230 m = len(s)
231 for i in range(1, 256):
232 if i == 39:
233 continue
234 sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
235 if sum_ < m:
236 m = sum_
237 e = i
238 if m == 0: # No overhead ? use this !
239 break;
Sylvain Munaut1a914432011-12-08 20:08:26 +0100240
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100241 # Generate output
242 out = []
243 out.append( chr(e) ) # Offset
244 for c in s:
245 x = (256 + ord(c) - e) % 256
246 if x in (0, 1, 39):
247 out.append('\x01')
248 out.append(chr(x+1))
249 else:
250 out.append(chr(x))
251
252 return ''.join(out)
253
Sylvain Munaut76504e02010-12-07 00:24:32 +0100254def gen_parameters(opts):
Jan Balkec3ebd332015-01-26 12:22:55 +0100255 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki, PIN-ADM from the
Sylvain Munaut76504e02010-12-07 00:24:32 +0100256 options given by the user"""
257
258 # MCC/MNC
259 mcc = opts.mcc
260 mnc = opts.mnc
261
262 if not ((0 < mcc < 999) and (0 < mnc < 999)):
263 raise ValueError('mcc & mnc must be between 0 and 999')
264
265 # Digitize country code (2 or 3 digits)
266 cc_digits = _cc_digits(opts.country)
267
268 # Digitize MCC/MNC (5 or 6 digits)
269 plmn_digits = _mcc_mnc_digits(mcc, mnc)
270
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100271 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
Sylvain Munaut76504e02010-12-07 00:24:32 +0100272 if opts.iccid is not None:
273 iccid = opts.iccid
Todd Neal9eeadfc2018-04-25 15:36:29 -0500274 if not _isnum(iccid, 19) and not _isnum(iccid, 20):
275 raise ValueError('ICCID must be 19 or 20 digits !');
Sylvain Munaut76504e02010-12-07 00:24:32 +0100276
277 else:
278 if opts.num is None:
279 raise ValueError('Neither ICCID nor card number specified !')
280
281 iccid = (
282 '89' + # Common prefix (telecom)
283 cc_digits + # Country Code on 2/3 digits
284 plmn_digits # MCC/MNC on 5/6 digits
285 )
286
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100287 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100288
289 if opts.secret is None:
290 # The raw number
291 iccid += ('%%0%dd' % ml) % opts.num
292 else:
293 # Randomized digits
294 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
295
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100296 # Add checksum digit
297 iccid += ('%1d' % calculate_luhn(iccid))
298
Sylvain Munaut76504e02010-12-07 00:24:32 +0100299 # IMSI (15 digits usually)
300 if opts.imsi is not None:
301 imsi = opts.imsi
302 if not _isnum(imsi):
303 raise ValueError('IMSI must be digits only !')
304
305 else:
306 if opts.num is None:
307 raise ValueError('Neither IMSI nor card number specified !')
308
309 ml = 15 - len(plmn_digits)
310
311 if opts.secret is None:
312 # The raw number
313 msin = ('%%0%dd' % ml) % opts.num
314 else:
315 # Randomized digits
316 msin = _digits(opts.secret, 'imsi', ml, opts.num)
317
318 imsi = (
319 plmn_digits + # MCC/MNC on 5/6 digits
320 msin # MSIN
321 )
322
323 # SMSP
324 if opts.smsp is not None:
325 smsp = opts.smsp
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100326 if not _ishex(smsp):
327 raise ValueError('SMSP must be hex digits only !')
328 if len(smsp) < 28*2:
329 raise ValueError('SMSP must be at least 28 bytes')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100330
331 else:
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200332 ton = "81"
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100333 if opts.smsc is not None:
334 smsc = opts.smsc
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200335 if smsc[0] == '+':
336 ton = "91"
337 smsc = smsc[1:]
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100338 if not _isnum(smsc):
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200339 raise ValueError('SMSC must be digits only!\n \
340 Start with \'+\' for international numbers')
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100341 else:
342 smsc = '00%d' % opts.country + '5555' # Hack ...
343
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200344 smsc = '%02d' % ((len(smsc) + 3)//2,) + ton + swap_nibbles(rpad(smsc, 20))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100345
346 smsp = (
347 'e1' + # Parameters indicator
348 'ff' * 12 + # TP-Destination address
349 smsc + # TP-Service Centre Address
350 '00' + # TP-Protocol identifier
351 '00' + # TP-Data coding scheme
352 '00' # TP-Validity period
353 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100354
Alexander Chemeris21885242013-07-02 16:56:55 +0400355 # ACC
356 if opts.acc is not None:
357 acc = opts.acc
358 if not _ishex(acc):
359 raise ValueError('ACC must be hex digits only !')
360 if len(acc) != 2*2:
361 raise ValueError('ACC must be exactly 2 bytes')
362
363 else:
364 acc = None
365
Sylvain Munaut76504e02010-12-07 00:24:32 +0100366 # Ki (random)
367 if opts.ki is not None:
368 ki = opts.ki
369 if not re.match('^[0-9a-fA-F]{32}$', ki):
370 raise ValueError('Ki needs to be 128 bits, in hex format')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100371 else:
372 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
373
Alexander Chemerisd17ca3d2017-07-18 16:40:58 +0300374 # OPC (random)
Harald Welte93b38cd2012-03-22 14:31:36 +0100375 if opts.opc is not None:
376 opc = opts.opc
377 if not re.match('^[0-9a-fA-F]{32}$', opc):
378 raise ValueError('OPC needs to be 128 bits, in hex format')
379
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100380 elif opts.op is not None:
381 opc = derive_milenage_opc(ki, opts.op)
Harald Welte93b38cd2012-03-22 14:31:36 +0100382 else:
383 opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
384
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200385
386 pin_adm = None
387
Jan Balkec3ebd332015-01-26 12:22:55 +0100388 if opts.pin_adm is not None:
Philipp Maierd9824882018-06-13 09:21:59 +0200389 if len(opts.pin_adm) <= 8:
390 pin_adm = ''.join(['%02x'%(ord(x)) for x in opts.pin_adm])
391 pin_adm = rpad(pin_adm, 16)
Jan Balkec3ebd332015-01-26 12:22:55 +0100392
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200393 else:
394 raise ValueError("PIN-ADM needs to be <=8 digits (ascii)")
395
396 if opts.pin_adm_hex is not None:
397 if len(opts.pin_adm_hex) == 16:
398 pin_adm = opts.pin_adm_hex
399 # Ensure that it's hex-encoded
400 try:
401 try_encode = h2b(pin_adm)
402 except ValueError:
403 raise ValueError("PIN-ADM needs to be hex encoded using this option")
404 else:
405 raise ValueError("PIN-ADM needs to be exactly 16 digits (hex encoded)")
Harald Welte93b38cd2012-03-22 14:31:36 +0100406
Sylvain Munaut76504e02010-12-07 00:24:32 +0100407 # Return that
408 return {
409 'name' : opts.name,
410 'iccid' : iccid,
411 'mcc' : mcc,
412 'mnc' : mnc,
413 'imsi' : imsi,
414 'smsp' : smsp,
415 'ki' : ki,
Harald Welte93b38cd2012-03-22 14:31:36 +0100416 'opc' : opc,
Alexander Chemeris21885242013-07-02 16:56:55 +0400417 'acc' : acc,
Jan Balkec3ebd332015-01-26 12:22:55 +0100418 'pin_adm' : pin_adm,
Sylvain Munaut76504e02010-12-07 00:24:32 +0100419 }
420
421
422def print_parameters(params):
423
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200424 s = ["Generated card parameters :"]
425 if 'name' in params:
426 s.append(" > Name : %(name)s")
427 if 'smsp' in params:
428 s.append(" > SMSP : %(smsp)s")
429 s.append(" > ICCID : %(iccid)s")
430 s.append(" > MCC/MNC : %(mcc)d/%(mnc)d")
431 s.append(" > IMSI : %(imsi)s")
432 s.append(" > Ki : %(ki)s")
433 s.append(" > OPC : %(opc)s")
434 if 'acc' in params:
435 s.append(" > ACC : %(acc)s")
436 s.append(" > ADM1(hex): %(pin_adm)s")
437 print("\n".join(s) % params)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100438
439
Harald Welte130524b2012-08-13 15:53:43 +0200440def write_params_csv(opts, params):
441 # csv
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100442 if opts.write_csv:
443 import csv
Harald Welte93b38cd2012-03-22 14:31:36 +0100444 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100445 f = open(opts.write_csv, 'a')
446 cw = csv.writer(f)
447 cw.writerow([params[x] for x in row])
448 f.close()
449
Daniel Willmann164b9632019-09-03 19:13:51 +0200450def _read_params_csv(opts, iccid=None, imsi=None):
Harald Welte7f62cec2012-08-13 20:07:41 +0200451 import csv
Harald Welte7f62cec2012-08-13 20:07:41 +0200452 f = open(opts.read_csv, 'r')
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200453 cr = csv.DictReader(f)
Harald Welte7f62cec2012-08-13 20:07:41 +0200454 i = 0
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200455 if not 'iccid' in cr.fieldnames:
456 raise Exception("CSV file in wrong format!")
Harald Welte7f62cec2012-08-13 20:07:41 +0200457 for row in cr:
Daniel Willmann164b9632019-09-03 19:13:51 +0200458 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 +0200459 if opts.num == i:
Harald Weltec26b8292012-08-15 15:25:51 +0200460 f.close()
461 return row;
462 i += 1
Daniel Willmann164b9632019-09-03 19:13:51 +0200463 if row['iccid'] == iccid:
464 f.close()
465 return row;
466
Harald Welte7f62cec2012-08-13 20:07:41 +0200467 if row['imsi'] == imsi:
Harald Weltec26b8292012-08-15 15:25:51 +0200468 f.close()
469 return row;
Harald Welte7f62cec2012-08-13 20:07:41 +0200470
471 f.close()
Harald Weltec26b8292012-08-15 15:25:51 +0200472 return None
473
Daniel Willmann164b9632019-09-03 19:13:51 +0200474def read_params_csv(opts, imsi=None, iccid=None):
475 row = _read_params_csv(opts, iccid=iccid, imsi=imsi)
Harald Weltec26b8292012-08-15 15:25:51 +0200476 if row is not None:
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200477 row['mcc'] = int(row.get('mcc', row['imsi'][0:3]))
478 row['mnc'] = int(row.get('mnc', row['imsi'][3:5]))
479 pin_adm = None
480 # We need to escape the pin_adm we get from the csv
481 if 'pin_adm' in row:
482 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['pin_adm']])
483 # Stay compatible to the odoo csv format
484 elif 'adm1' in row:
485 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['adm1']])
486 if pin_adm:
487 row['pin_adm'] = rpad(pin_adm, 16)
Philipp Maiere053da52019-09-05 13:08:36 +0200488
489 # If the CSV-File defines a pin_adm_hex field use this field to
490 # generate pin_adm from that.
491 pin_adm_hex = row.get('pin_adm_hex')
492 if pin_adm_hex:
493 if len(pin_adm_hex) == 16:
494 row['pin_adm'] = pin_adm_hex
495 # Ensure that it's hex-encoded
496 try:
497 try_encode = h2b(pin_adm)
498 except ValueError:
499 raise ValueError("pin_adm_hex needs to be hex encoded using this option")
500 else:
501 raise ValueError("pin_adm_hex needs to be exactly 16 digits (hex encoded)")
502
Harald Welte7f62cec2012-08-13 20:07:41 +0200503 return row
504
Harald Weltec26b8292012-08-15 15:25:51 +0200505
Harald Welte130524b2012-08-13 15:53:43 +0200506def write_params_hlr(opts, params):
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100507 # SQLite3 OpenBSC HLR
508 if opts.write_hlr:
509 import sqlite3
510 conn = sqlite3.connect(opts.write_hlr)
511
512 c = conn.execute(
513 'INSERT INTO Subscriber ' +
514 '(imsi, name, extension, authorized, created, updated) ' +
515 'VALUES ' +
516 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
517 [
518 params['imsi'],
519 params['name'],
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200520 '9' + params['iccid'][-5:-1]
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100521 ],
522 )
523 sub_id = c.lastrowid
524 c.close()
525
526 c = conn.execute(
527 'INSERT INTO AuthKeys ' +
528 '(subscriber_id, algorithm_id, a3a8_ki)' +
529 'VALUES ' +
530 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100531 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100532 )
533
534 conn.commit()
535 conn.close()
536
Harald Welte130524b2012-08-13 15:53:43 +0200537def write_parameters(opts, params):
538 write_params_csv(opts, params)
Harald Welte7f62cec2012-08-13 20:07:41 +0200539 write_params_hlr(opts, params)
Harald Welte130524b2012-08-13 15:53:43 +0200540
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100541
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100542BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
543BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100544
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100545def init_batch(opts):
546 # Need to do something ?
547 if not opts.batch_mode:
548 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100549
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100550 for k in BATCH_INCOMPATIBLE:
551 if getattr(opts, k):
552 print "Incompatible option with batch_state: %s" % (k,)
553 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100554
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100555 # Don't load state if there is none ...
556 if not opts.batch_state:
557 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100558
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100559 if not os.path.isfile(opts.batch_state):
560 print "No state file yet"
561 return
562
563 # Get stored data
564 fh = open(opts.batch_state)
565 d = json.loads(fh.read())
566 fh.close()
567
568 for k,v in d.iteritems():
569 setattr(opts, k, v)
570
571
572def save_batch(opts):
573 # Need to do something ?
574 if not opts.batch_mode or not opts.batch_state:
575 return
576
577 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
578 fh = open(opts.batch_state, 'w')
579 fh.write(d)
580 fh.close()
581
582
583def card_detect(opts, scc):
Sylvain Munautbdca2522010-12-09 13:31:58 +0100584
Sylvain Munaut76504e02010-12-07 00:24:32 +0100585 # Detect type if needed
586 card = None
587 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
588
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100589 if opts.type in ("auto", "auto_once"):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100590 for kls in _cards_classes:
591 card = kls.autodetect(scc)
592 if card:
Philipp Maierac9dde62018-07-04 11:05:14 +0200593 print "Autodetected card type: %s" % card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100594 card.reset()
595 break
596
597 if card is None:
598 print "Autodetection failed"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100599 return
600
601 if opts.type == "auto_once":
602 opts.type = card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100603
604 elif opts.type in ctypes:
605 card = ctypes[opts.type](scc)
606
607 else:
Philipp Maierac9dde62018-07-04 11:05:14 +0200608 raise ValueError("Unknown card type: %s" % opts.type)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100609
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100610 return card
Sylvain Munaut76504e02010-12-07 00:24:32 +0100611
Sylvain Munaut76504e02010-12-07 00:24:32 +0100612
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100613if __name__ == '__main__':
614
615 # Parse options
616 opts = parse_options()
617
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700618 # Init card reader driver
619 if opts.pcsc_dev is not None:
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700620 print("Using PC/SC reader (dev=%d) interface"
621 % opts.pcsc_dev)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100622 from pySim.transport.pcsc import PcscSimLink
623 sl = PcscSimLink(opts.pcsc_dev)
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +0700624 elif opts.osmocon_sock is not None:
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700625 print("Using Calypso-based (OsmocomBB, sock=%s) reader interface"
626 % opts.osmocon_sock)
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +0700627 from pySim.transport.calypso import CalypsoSimLink
628 sl = CalypsoSimLink(sock_path=opts.osmocon_sock)
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700629 else: # Serial reader is default
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700630 print("Using serial reader (port=%s, baudrate=%d) interface"
631 % (opts.device, opts.baudrate))
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700632 from pySim.transport.serial import SerialSimLink
633 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100634
635 # Create command layer
636 scc = SimCardCommands(transport=sl)
637
638 # Batch mode init
639 init_batch(opts)
640
641 # Iterate
642 done = False
643 first = True
644 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100645
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100646 while not done:
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200647
648 if opts.dry_run is False:
649 # Connect transport
650 print "Insert card now (or CTRL-C to cancel)"
651 sl.wait_for_card(newcardonly=not first)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100652
653 # Not the first anymore !
654 first = False
655
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200656 if opts.dry_run is False:
657 # Get card
658 card = card_detect(opts, scc)
659 if card is None:
660 if opts.batch_mode:
661 first = False
662 continue
663 else:
664 sys.exit(-1)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100665
Philipp Maierac9dde62018-07-04 11:05:14 +0200666 # Probe only
667 if opts.probe:
668 break;
669
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200670 # Erase if requested
671 if opts.erase:
672 print "Formatting ..."
673 card.erase()
674 card.reset()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100675
676 # Generate parameters
Harald Welte7f62cec2012-08-13 20:07:41 +0200677 if opts.source == 'cmdline':
678 cp = gen_parameters(opts)
679 elif opts.source == 'csv':
Daniel Willmann164b9632019-09-03 19:13:51 +0200680 imsi = None
681 iccid = None
682 if opts.read_iccid:
683 if opts.dry_run:
684 # Connect transport
685 print "Insert card now (or CTRL-C to cancel)"
686 sl.wait_for_card(newcardonly=not first)
687 (res,_) = scc.read_binary(['3f00', '2fe2'], length=10)
688 iccid = dec_iccid(res)
689 print iccid
690 elif opts.read_imsi:
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200691 if opts.dry_run:
692 # Connect transport
693 print "Insert card now (or CTRL-C to cancel)"
694 sl.wait_for_card(newcardonly=not first)
Alexander Chemeris47c73ab2018-01-10 14:10:17 +0900695 (res,_) = scc.read_binary(EF['IMSI'])
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200696 imsi = swap_nibbles(res)[3:]
697 else:
698 imsi = opts.imsi
Daniel Willmann164b9632019-09-03 19:13:51 +0200699 cp = read_params_csv(opts, imsi=imsi, iccid=iccid)
Harald Welte7f62cec2012-08-13 20:07:41 +0200700 if cp is None:
701 print "Error reading parameters\n"
702 sys.exit(2)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100703 print_parameters(cp)
704
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200705 if opts.dry_run is False:
706 # Program the card
707 print "Programming ..."
708 if opts.dry_run is not True:
709 card.program(cp)
710 else:
711 print "Dry Run: NOT PROGRAMMING!"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100712
713 # Write parameters permanently
714 write_parameters(opts, cp)
715
716 # Batch mode state update and save
Sylvain Munaut8d243e82010-12-23 20:27:48 +0100717 if opts.num is not None:
718 opts.num += 1
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100719 save_batch(opts)
720
721 # Done for this card and maybe for everything ?
722 print "Done !\n"
723
724 if not opts.batch_mode:
725 done = True