blob: 238798654d83051b1beebdaf12a684dee6a48c7c [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
42from pySim.cards import _cards_classes
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 *
Sylvain Munaut76504e02010-12-07 00:24:32 +010046
47def parse_options():
48
49 parser = OptionParser(usage="usage: %prog [options]")
50
51 parser.add_option("-d", "--device", dest="device", metavar="DEV",
52 help="Serial Device for SIM access [default: %default]",
53 default="/dev/ttyUSB0",
54 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010055 parser.add_option("-b", "--baud", dest="baudrate", type="int", metavar="BAUD",
56 help="Baudrate used for SIM access [default: %default]",
57 default=9600,
58 )
Sylvain Munaut9c8729a2010-12-08 23:20:27 +010059 parser.add_option("-p", "--pcsc-device", dest="pcsc_dev", type='int', metavar="PCSC",
Sylvain Munaute9fdecb2010-12-08 22:33:19 +010060 help="Which PC/SC reader number for SIM access",
61 default=None,
62 )
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +070063 parser.add_option("--osmocon", dest="osmocon_sock", metavar="PATH",
64 help="Socket path for Calypso (e.g. Motorola C1XX) based reader (via OsmocomBB)",
65 default=None,
66 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010067 parser.add_option("-t", "--type", dest="type",
68 help="Card type (user -t list to view) [default: %default]",
69 default="auto",
70 )
Philipp Maierac9dde62018-07-04 11:05:14 +020071 parser.add_option("-T", "--probe", dest="probe",
72 help="Determine card type",
73 default=False, action="store_true"
74 )
Jan Balkec3ebd332015-01-26 12:22:55 +010075 parser.add_option("-a", "--pin-adm", dest="pin_adm",
76 help="ADM PIN used for provisioning (overwrites default)",
77 )
Daniel Willmannf432b2b2018-06-15 07:31:50 +020078 parser.add_option("-A", "--pin-adm-hex", dest="pin_adm_hex",
79 help="ADM PIN used for provisioning, as hex string (16 characters long",
80 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010081 parser.add_option("-e", "--erase", dest="erase", action='store_true',
82 help="Erase beforehand [default: %default]",
83 default=False,
84 )
85
Harald Welte7f62cec2012-08-13 20:07:41 +020086 parser.add_option("-S", "--source", dest="source",
87 help="Data Source[default: %default]",
88 default="cmdline",
89 )
90
91 # if mode is "cmdline"
Sylvain Munaut76504e02010-12-07 00:24:32 +010092 parser.add_option("-n", "--name", dest="name",
93 help="Operator name [default: %default]",
94 default="Magic",
95 )
96 parser.add_option("-c", "--country", dest="country", type="int", metavar="CC",
97 help="Country code [default: %default]",
98 default=1,
99 )
100 parser.add_option("-x", "--mcc", dest="mcc", type="int",
101 help="Mobile Country Code [default: %default]",
102 default=901,
103 )
104 parser.add_option("-y", "--mnc", dest="mnc", type="int",
Sylvain Munaut17716032010-12-08 22:33:51 +0100105 help="Mobile Network Code [default: %default]",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100106 default=55,
107 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100108 parser.add_option("-m", "--smsc", dest="smsc",
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200109 help="SMSC number (Start with + for international no.) [default: '00 + country code + 5555']",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100110 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100111 parser.add_option("-M", "--smsp", dest="smsp",
112 help="Raw SMSP content in hex [default: auto from SMSC]",
113 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100114
115 parser.add_option("-s", "--iccid", dest="iccid", metavar="ID",
116 help="Integrated Circuit Card ID",
117 )
118 parser.add_option("-i", "--imsi", dest="imsi",
119 help="International Mobile Subscriber Identity",
120 )
121 parser.add_option("-k", "--ki", dest="ki",
122 help="Ki (default is to randomize)",
123 )
Harald Welte93b38cd2012-03-22 14:31:36 +0100124 parser.add_option("-o", "--opc", dest="opc",
125 help="OPC (default is to randomize)",
126 )
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100127 parser.add_option("--op", dest="op",
128 help="Set OP to derive OPC from OP and KI",
129 )
Alexander Chemeris21885242013-07-02 16:56:55 +0400130 parser.add_option("--acc", dest="acc",
131 help="Set ACC bits (Access Control Code). not all card types are supported",
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200132 )
133 parser.add_option("--read-imsi", dest="read_imsi", action="store_true",
134 help="Read the IMSI from the CARD", default=False
Alexander Chemeris21885242013-07-02 16:56:55 +0400135 )
Daniel Willmann164b9632019-09-03 19:13:51 +0200136 parser.add_option("--read-iccid", dest="read_iccid", action="store_true",
137 help="Read the ICCID from the CARD", default=False
138 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100139 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
140 help="Secret used for ICCID/IMSI autogen",
141 )
142 parser.add_option("-j", "--num", dest="num", type=int,
143 help="Card # used for ICCID/IMSI autogen",
144 )
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100145 parser.add_option("--batch", dest="batch_mode",
146 help="Enable batch mode [default: %default]",
147 default=False, action='store_true',
148 )
149 parser.add_option("--batch-state", dest="batch_state", metavar="FILE",
150 help="Optional batch state file",
151 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100152
Harald Welte7f62cec2012-08-13 20:07:41 +0200153 # if mode is "csv"
154 parser.add_option("--read-csv", dest="read_csv", metavar="FILE",
155 help="Read parameters from CSV file rather than command line")
156
157
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100158 parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
159 help="Append generated parameters in CSV file",
160 )
161 parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
162 help="Append generated parameters to OpenBSC HLR sqlite3",
163 )
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200164 parser.add_option("--dry-run", dest="dry_run",
165 help="Perform a 'dry run', don't actually program the card",
166 default=False, action="store_true")
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100167
Philipp Maierc5b422e2019-08-30 11:41:02 +0200168 parser.add_option("--card_handler", dest="card_handler", metavar="FILE",
169 help="Use automatic card handling machine")
170
Sylvain Munaut76504e02010-12-07 00:24:32 +0100171 (options, args) = parser.parse_args()
172
173 if options.type == 'list':
174 for kls in _cards_classes:
175 print kls.name
176 sys.exit(0)
177
Philipp Maierac9dde62018-07-04 11:05:14 +0200178 if options.probe:
179 return options
180
Harald Welte7f62cec2012-08-13 20:07:41 +0200181 if options.source == 'csv':
Daniel Willmann164b9632019-09-03 19:13:51 +0200182 if (options.imsi is None) and (options.batch_mode is False) and (options.read_imsi is False) and (options.read_iccid is False):
183 parser.error("CSV mode needs either an IMSI, --read-imsi, --read-iccid or batch mode")
Harald Welte7f62cec2012-08-13 20:07:41 +0200184 if options.read_csv is None:
185 parser.error("CSV mode requires a CSV input file")
186 elif options.source == 'cmdline':
187 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
188 parser.error("If either IMSI or ICCID isn't specified, num is required")
189 else:
190 parser.error("Only `cmdline' and `csv' sources supported")
191
192 if (options.read_csv is not None) and (options.source != 'csv'):
193 parser.error("You cannot specify a CSV input file in source != csv")
194
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100195 if (options.batch_mode) and (options.num is None):
196 options.num = 0
197
Sylvain Munaut98d2b852010-12-23 20:27:25 +0100198 if (options.batch_mode):
199 if (options.imsi is not None) or (options.iccid is not None):
200 parser.error("Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more informations")
201
Sylvain Munaut76504e02010-12-07 00:24:32 +0100202 if args:
203 parser.error("Extraneous arguments")
204
205 return options
206
207
208def _digits(secret, usage, len, num):
209 s = hashlib.sha1(secret + usage + '%d' % num)
210 d = ''.join(['%02d'%ord(x) for x in s.digest()])
211 return d[0:len]
212
213def _mcc_mnc_digits(mcc, mnc):
214 return ('%03d%03d' if mnc > 100 else '%03d%02d') % (mcc, mnc)
215
216def _cc_digits(cc):
217 return ('%03d' if cc > 100 else '%02d') % cc
218
219def _isnum(s, l=-1):
220 return s.isdigit() and ((l== -1) or (len(s) == l))
221
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100222def _ishex(s, l=-1):
223 hc = '0123456789abcdef'
224 return all([x in hc for x in s.lower()]) and ((l== -1) or (len(s) == l))
225
Sylvain Munaut76504e02010-12-07 00:24:32 +0100226
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100227def _dbi_binary_quote(s):
228 # Count usage of each char
229 cnt = {}
230 for c in s:
231 cnt[c] = cnt.get(c, 0) + 1
232
233 # Find best offset
234 e = 0
235 m = len(s)
236 for i in range(1, 256):
237 if i == 39:
238 continue
239 sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
240 if sum_ < m:
241 m = sum_
242 e = i
243 if m == 0: # No overhead ? use this !
244 break;
Sylvain Munaut1a914432011-12-08 20:08:26 +0100245
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100246 # Generate output
247 out = []
248 out.append( chr(e) ) # Offset
249 for c in s:
250 x = (256 + ord(c) - e) % 256
251 if x in (0, 1, 39):
252 out.append('\x01')
253 out.append(chr(x+1))
254 else:
255 out.append(chr(x))
256
257 return ''.join(out)
258
Sylvain Munaut76504e02010-12-07 00:24:32 +0100259def gen_parameters(opts):
Jan Balkec3ebd332015-01-26 12:22:55 +0100260 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki, PIN-ADM from the
Sylvain Munaut76504e02010-12-07 00:24:32 +0100261 options given by the user"""
262
263 # MCC/MNC
264 mcc = opts.mcc
265 mnc = opts.mnc
266
267 if not ((0 < mcc < 999) and (0 < mnc < 999)):
268 raise ValueError('mcc & mnc must be between 0 and 999')
269
270 # Digitize country code (2 or 3 digits)
271 cc_digits = _cc_digits(opts.country)
272
273 # Digitize MCC/MNC (5 or 6 digits)
274 plmn_digits = _mcc_mnc_digits(mcc, mnc)
275
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100276 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
Sylvain Munaut76504e02010-12-07 00:24:32 +0100277 if opts.iccid is not None:
278 iccid = opts.iccid
Todd Neal9eeadfc2018-04-25 15:36:29 -0500279 if not _isnum(iccid, 19) and not _isnum(iccid, 20):
280 raise ValueError('ICCID must be 19 or 20 digits !');
Sylvain Munaut76504e02010-12-07 00:24:32 +0100281
282 else:
283 if opts.num is None:
284 raise ValueError('Neither ICCID nor card number specified !')
285
286 iccid = (
287 '89' + # Common prefix (telecom)
288 cc_digits + # Country Code on 2/3 digits
289 plmn_digits # MCC/MNC on 5/6 digits
290 )
291
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100292 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100293
294 if opts.secret is None:
295 # The raw number
296 iccid += ('%%0%dd' % ml) % opts.num
297 else:
298 # Randomized digits
299 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
300
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100301 # Add checksum digit
302 iccid += ('%1d' % calculate_luhn(iccid))
303
Sylvain Munaut76504e02010-12-07 00:24:32 +0100304 # IMSI (15 digits usually)
305 if opts.imsi is not None:
306 imsi = opts.imsi
307 if not _isnum(imsi):
308 raise ValueError('IMSI must be digits only !')
309
310 else:
311 if opts.num is None:
312 raise ValueError('Neither IMSI nor card number specified !')
313
314 ml = 15 - len(plmn_digits)
315
316 if opts.secret is None:
317 # The raw number
318 msin = ('%%0%dd' % ml) % opts.num
319 else:
320 # Randomized digits
321 msin = _digits(opts.secret, 'imsi', ml, opts.num)
322
323 imsi = (
324 plmn_digits + # MCC/MNC on 5/6 digits
325 msin # MSIN
326 )
327
328 # SMSP
329 if opts.smsp is not None:
330 smsp = opts.smsp
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100331 if not _ishex(smsp):
332 raise ValueError('SMSP must be hex digits only !')
333 if len(smsp) < 28*2:
334 raise ValueError('SMSP must be at least 28 bytes')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100335
336 else:
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200337 ton = "81"
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100338 if opts.smsc is not None:
339 smsc = opts.smsc
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200340 if smsc[0] == '+':
341 ton = "91"
342 smsc = smsc[1:]
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100343 if not _isnum(smsc):
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200344 raise ValueError('SMSC must be digits only!\n \
345 Start with \'+\' for international numbers')
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100346 else:
347 smsc = '00%d' % opts.country + '5555' # Hack ...
348
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200349 smsc = '%02d' % ((len(smsc) + 3)//2,) + ton + swap_nibbles(rpad(smsc, 20))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100350
351 smsp = (
352 'e1' + # Parameters indicator
353 'ff' * 12 + # TP-Destination address
354 smsc + # TP-Service Centre Address
355 '00' + # TP-Protocol identifier
356 '00' + # TP-Data coding scheme
357 '00' # TP-Validity period
358 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100359
Alexander Chemeris21885242013-07-02 16:56:55 +0400360 # ACC
361 if opts.acc is not None:
362 acc = opts.acc
363 if not _ishex(acc):
364 raise ValueError('ACC must be hex digits only !')
365 if len(acc) != 2*2:
366 raise ValueError('ACC must be exactly 2 bytes')
367
368 else:
369 acc = None
370
Sylvain Munaut76504e02010-12-07 00:24:32 +0100371 # Ki (random)
372 if opts.ki is not None:
373 ki = opts.ki
374 if not re.match('^[0-9a-fA-F]{32}$', ki):
375 raise ValueError('Ki needs to be 128 bits, in hex format')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100376 else:
377 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
378
Alexander Chemerisd17ca3d2017-07-18 16:40:58 +0300379 # OPC (random)
Harald Welte93b38cd2012-03-22 14:31:36 +0100380 if opts.opc is not None:
381 opc = opts.opc
382 if not re.match('^[0-9a-fA-F]{32}$', opc):
383 raise ValueError('OPC needs to be 128 bits, in hex format')
384
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100385 elif opts.op is not None:
386 opc = derive_milenage_opc(ki, opts.op)
Harald Welte93b38cd2012-03-22 14:31:36 +0100387 else:
388 opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
389
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200390
391 pin_adm = None
392
Jan Balkec3ebd332015-01-26 12:22:55 +0100393 if opts.pin_adm is not None:
Philipp Maierd9824882018-06-13 09:21:59 +0200394 if len(opts.pin_adm) <= 8:
395 pin_adm = ''.join(['%02x'%(ord(x)) for x in opts.pin_adm])
396 pin_adm = rpad(pin_adm, 16)
Jan Balkec3ebd332015-01-26 12:22:55 +0100397
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200398 else:
399 raise ValueError("PIN-ADM needs to be <=8 digits (ascii)")
400
401 if opts.pin_adm_hex is not None:
402 if len(opts.pin_adm_hex) == 16:
403 pin_adm = opts.pin_adm_hex
404 # Ensure that it's hex-encoded
405 try:
406 try_encode = h2b(pin_adm)
407 except ValueError:
408 raise ValueError("PIN-ADM needs to be hex encoded using this option")
409 else:
410 raise ValueError("PIN-ADM needs to be exactly 16 digits (hex encoded)")
Harald Welte93b38cd2012-03-22 14:31:36 +0100411
Sylvain Munaut76504e02010-12-07 00:24:32 +0100412 # Return that
413 return {
414 'name' : opts.name,
415 'iccid' : iccid,
416 'mcc' : mcc,
417 'mnc' : mnc,
418 'imsi' : imsi,
419 'smsp' : smsp,
420 'ki' : ki,
Harald Welte93b38cd2012-03-22 14:31:36 +0100421 'opc' : opc,
Alexander Chemeris21885242013-07-02 16:56:55 +0400422 'acc' : acc,
Jan Balkec3ebd332015-01-26 12:22:55 +0100423 'pin_adm' : pin_adm,
Sylvain Munaut76504e02010-12-07 00:24:32 +0100424 }
425
426
427def print_parameters(params):
428
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200429 s = ["Generated card parameters :"]
430 if 'name' in params:
431 s.append(" > Name : %(name)s")
432 if 'smsp' in params:
433 s.append(" > SMSP : %(smsp)s")
434 s.append(" > ICCID : %(iccid)s")
435 s.append(" > MCC/MNC : %(mcc)d/%(mnc)d")
436 s.append(" > IMSI : %(imsi)s")
437 s.append(" > Ki : %(ki)s")
438 s.append(" > OPC : %(opc)s")
439 if 'acc' in params:
440 s.append(" > ACC : %(acc)s")
441 s.append(" > ADM1(hex): %(pin_adm)s")
442 print("\n".join(s) % params)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100443
444
Harald Welte130524b2012-08-13 15:53:43 +0200445def write_params_csv(opts, params):
446 # csv
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100447 if opts.write_csv:
448 import csv
Harald Welte93b38cd2012-03-22 14:31:36 +0100449 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100450 f = open(opts.write_csv, 'a')
451 cw = csv.writer(f)
452 cw.writerow([params[x] for x in row])
453 f.close()
454
Daniel Willmann164b9632019-09-03 19:13:51 +0200455def _read_params_csv(opts, iccid=None, imsi=None):
Harald Welte7f62cec2012-08-13 20:07:41 +0200456 import csv
Harald Welte7f62cec2012-08-13 20:07:41 +0200457 f = open(opts.read_csv, 'r')
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200458 cr = csv.DictReader(f)
Harald Welte7f62cec2012-08-13 20:07:41 +0200459 i = 0
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200460 if not 'iccid' in cr.fieldnames:
461 raise Exception("CSV file in wrong format!")
Harald Welte7f62cec2012-08-13 20:07:41 +0200462 for row in cr:
Daniel Willmann164b9632019-09-03 19:13:51 +0200463 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 +0200464 if opts.num == i:
Harald Weltec26b8292012-08-15 15:25:51 +0200465 f.close()
466 return row;
467 i += 1
Daniel Willmann164b9632019-09-03 19:13:51 +0200468 if row['iccid'] == iccid:
469 f.close()
470 return row;
471
Harald Welte7f62cec2012-08-13 20:07:41 +0200472 if row['imsi'] == imsi:
Harald Weltec26b8292012-08-15 15:25:51 +0200473 f.close()
474 return row;
Harald Welte7f62cec2012-08-13 20:07:41 +0200475
476 f.close()
Harald Weltec26b8292012-08-15 15:25:51 +0200477 return None
478
Daniel Willmann164b9632019-09-03 19:13:51 +0200479def read_params_csv(opts, imsi=None, iccid=None):
480 row = _read_params_csv(opts, iccid=iccid, imsi=imsi)
Harald Weltec26b8292012-08-15 15:25:51 +0200481 if row is not None:
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200482 row['mcc'] = int(row.get('mcc', row['imsi'][0:3]))
483 row['mnc'] = int(row.get('mnc', row['imsi'][3:5]))
484 pin_adm = None
485 # We need to escape the pin_adm we get from the csv
486 if 'pin_adm' in row:
487 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['pin_adm']])
488 # Stay compatible to the odoo csv format
489 elif 'adm1' in row:
490 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['adm1']])
491 if pin_adm:
492 row['pin_adm'] = rpad(pin_adm, 16)
Philipp Maiere053da52019-09-05 13:08:36 +0200493
494 # If the CSV-File defines a pin_adm_hex field use this field to
495 # generate pin_adm from that.
496 pin_adm_hex = row.get('pin_adm_hex')
497 if pin_adm_hex:
498 if len(pin_adm_hex) == 16:
499 row['pin_adm'] = pin_adm_hex
500 # Ensure that it's hex-encoded
501 try:
502 try_encode = h2b(pin_adm)
503 except ValueError:
504 raise ValueError("pin_adm_hex needs to be hex encoded using this option")
505 else:
506 raise ValueError("pin_adm_hex needs to be exactly 16 digits (hex encoded)")
507
Harald Welte7f62cec2012-08-13 20:07:41 +0200508 return row
509
Harald Weltec26b8292012-08-15 15:25:51 +0200510
Harald Welte130524b2012-08-13 15:53:43 +0200511def write_params_hlr(opts, params):
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100512 # SQLite3 OpenBSC HLR
513 if opts.write_hlr:
514 import sqlite3
515 conn = sqlite3.connect(opts.write_hlr)
516
517 c = conn.execute(
518 'INSERT INTO Subscriber ' +
519 '(imsi, name, extension, authorized, created, updated) ' +
520 'VALUES ' +
521 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
522 [
523 params['imsi'],
524 params['name'],
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200525 '9' + params['iccid'][-5:-1]
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100526 ],
527 )
528 sub_id = c.lastrowid
529 c.close()
530
531 c = conn.execute(
532 'INSERT INTO AuthKeys ' +
533 '(subscriber_id, algorithm_id, a3a8_ki)' +
534 'VALUES ' +
535 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100536 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100537 )
538
539 conn.commit()
540 conn.close()
541
Harald Welte130524b2012-08-13 15:53:43 +0200542def write_parameters(opts, params):
543 write_params_csv(opts, params)
Harald Welte7f62cec2012-08-13 20:07:41 +0200544 write_params_hlr(opts, params)
Harald Welte130524b2012-08-13 15:53:43 +0200545
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100546
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100547BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
548BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100549
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100550def init_batch(opts):
551 # Need to do something ?
552 if not opts.batch_mode:
553 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100554
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100555 for k in BATCH_INCOMPATIBLE:
556 if getattr(opts, k):
557 print "Incompatible option with batch_state: %s" % (k,)
558 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100559
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100560 # Don't load state if there is none ...
561 if not opts.batch_state:
562 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100563
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100564 if not os.path.isfile(opts.batch_state):
565 print "No state file yet"
566 return
567
568 # Get stored data
569 fh = open(opts.batch_state)
570 d = json.loads(fh.read())
571 fh.close()
572
573 for k,v in d.iteritems():
574 setattr(opts, k, v)
575
576
577def save_batch(opts):
578 # Need to do something ?
579 if not opts.batch_mode or not opts.batch_state:
580 return
581
582 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
583 fh = open(opts.batch_state, 'w')
584 fh.write(d)
585 fh.close()
586
587
588def card_detect(opts, scc):
Sylvain Munautbdca2522010-12-09 13:31:58 +0100589
Sylvain Munaut76504e02010-12-07 00:24:32 +0100590 # Detect type if needed
591 card = None
592 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
593
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100594 if opts.type in ("auto", "auto_once"):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100595 for kls in _cards_classes:
596 card = kls.autodetect(scc)
597 if card:
Philipp Maierac9dde62018-07-04 11:05:14 +0200598 print "Autodetected card type: %s" % card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100599 card.reset()
600 break
601
602 if card is None:
603 print "Autodetection failed"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100604 return
605
606 if opts.type == "auto_once":
607 opts.type = card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100608
609 elif opts.type in ctypes:
610 card = ctypes[opts.type](scc)
611
612 else:
Philipp Maierac9dde62018-07-04 11:05:14 +0200613 raise ValueError("Unknown card type: %s" % opts.type)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100614
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100615 return card
Sylvain Munaut76504e02010-12-07 00:24:32 +0100616
Sylvain Munaut76504e02010-12-07 00:24:32 +0100617
Philipp Maierc5b422e2019-08-30 11:41:02 +0200618def process_card(opts, first, card_handler):
619
620 if opts.dry_run is False:
621 # Connect transport
622 card_handler.get(first)
623
624 if opts.dry_run is False:
625 # Get card
626 card = card_detect(opts, scc)
627 if card is None:
628 print "No card detected!"
629 return -1
630
631 # Probe only
632 if opts.probe:
633 return 0
634
635 # Erase if requested
636 if opts.erase:
637 print "Formatting ..."
638 card.erase()
639 card.reset()
640
641 # Generate parameters
642 if opts.source == 'cmdline':
643 cp = gen_parameters(opts)
644 elif opts.source == 'csv':
645 imsi = None
646 iccid = None
647 if opts.read_iccid:
648 if opts.dry_run:
649 # Connect transport
650 card_handler.get(false)
651 (res,_) = scc.read_binary(['3f00', '2fe2'], length=10)
652 iccid = dec_iccid(res)
653 elif opts.read_imsi:
654 if opts.dry_run:
655 # Connect transport
656 card_handler.get(false)
657 (res,_) = scc.read_binary(EF['IMSI'])
658 imsi = swap_nibbles(res)[3:]
659 else:
660 imsi = opts.imsi
661 cp = read_params_csv(opts, imsi=imsi, iccid=iccid)
662 if cp is None:
Philipp Maier1de89bf2019-09-12 13:40:02 +0200663 print "Error reading parameters from CSV file!\n"
Philipp Maierc5b422e2019-08-30 11:41:02 +0200664 return 2
665 print_parameters(cp)
666
667 if opts.dry_run is False:
668 # Program the card
669 print "Programming ..."
670 card.program(cp)
671 else:
672 print "Dry Run: NOT PROGRAMMING!"
673
674 # Write parameters permanently
675 write_parameters(opts, cp)
676
677 # Batch mode state update and save
678 if opts.num is not None:
679 opts.num += 1
680 save_batch(opts)
681
682 card_handler.done()
683 return 0
684
685
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100686if __name__ == '__main__':
687
688 # Parse options
689 opts = parse_options()
690
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700691 # Init card reader driver
692 if opts.pcsc_dev is not None:
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700693 print("Using PC/SC reader (dev=%d) interface"
694 % opts.pcsc_dev)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100695 from pySim.transport.pcsc import PcscSimLink
696 sl = PcscSimLink(opts.pcsc_dev)
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +0700697 elif opts.osmocon_sock is not None:
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700698 print("Using Calypso-based (OsmocomBB, sock=%s) reader interface"
699 % opts.osmocon_sock)
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +0700700 from pySim.transport.calypso import CalypsoSimLink
701 sl = CalypsoSimLink(sock_path=opts.osmocon_sock)
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700702 else: # Serial reader is default
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700703 print("Using serial reader (port=%s, baudrate=%d) interface"
704 % (opts.device, opts.baudrate))
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700705 from pySim.transport.serial import SerialSimLink
706 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100707
708 # Create command layer
709 scc = SimCardCommands(transport=sl)
710
711 # Batch mode init
712 init_batch(opts)
713
Philipp Maierc5b422e2019-08-30 11:41:02 +0200714 if opts.card_handler:
715 card_handler = card_handler_auto(sl, opts.card_handler)
716 else:
717 card_handler = card_handler(sl)
718
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100719 # Iterate
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100720 first = True
721 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100722
Philipp Maierc5b422e2019-08-30 11:41:02 +0200723 while 1:
724 try:
725 rc = process_card(opts, first, card_handler)
726 except (KeyboardInterrupt):
727 print ""
728 print "Terminated by user!"
729 sys.exit(0)
730 except (SystemExit):
731 raise
732 except:
733 print ""
734 print "Card programming failed with an execption:"
735 print "---------------------8<---------------------"
736 traceback.print_exc()
737 print "---------------------8<---------------------"
738 print ""
739 rc = -1
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200740
Philipp Maierc5b422e2019-08-30 11:41:02 +0200741 # Something did not work as well as expected, however, lets
742 # make sure the card is pulled from the reader.
743 if rc != 0:
744 card_handler.error()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100745
Philipp Maierc5b422e2019-08-30 11:41:02 +0200746 # If we are not in batch mode we are done in any case, so lets
747 # exit here.
748 if not opts.batch_mode:
749 sys.exit(rc)
750
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100751 first = False
752