blob: e92654d0148bc3ac2fa288883739bd4de6ef82f7 [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)
Philipp Maier120a0002019-09-12 13:11:45 +0200459
460 # Lower-case fieldnames
461 cr.fieldnames = [ field.lower() for field in cr.fieldnames ]
462
Harald Welte7f62cec2012-08-13 20:07:41 +0200463 i = 0
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200464 if not 'iccid' in cr.fieldnames:
465 raise Exception("CSV file in wrong format!")
Harald Welte7f62cec2012-08-13 20:07:41 +0200466 for row in cr:
Daniel Willmann164b9632019-09-03 19:13:51 +0200467 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 +0200468 if opts.num == i:
Harald Weltec26b8292012-08-15 15:25:51 +0200469 f.close()
470 return row;
471 i += 1
Daniel Willmann164b9632019-09-03 19:13:51 +0200472 if row['iccid'] == iccid:
473 f.close()
474 return row;
475
Harald Welte7f62cec2012-08-13 20:07:41 +0200476 if row['imsi'] == imsi:
Harald Weltec26b8292012-08-15 15:25:51 +0200477 f.close()
478 return row;
Harald Welte7f62cec2012-08-13 20:07:41 +0200479
480 f.close()
Harald Weltec26b8292012-08-15 15:25:51 +0200481 return None
482
Daniel Willmann164b9632019-09-03 19:13:51 +0200483def read_params_csv(opts, imsi=None, iccid=None):
484 row = _read_params_csv(opts, iccid=iccid, imsi=imsi)
Harald Weltec26b8292012-08-15 15:25:51 +0200485 if row is not None:
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200486 row['mcc'] = int(row.get('mcc', row['imsi'][0:3]))
487 row['mnc'] = int(row.get('mnc', row['imsi'][3:5]))
488 pin_adm = None
489 # We need to escape the pin_adm we get from the csv
490 if 'pin_adm' in row:
491 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['pin_adm']])
492 # Stay compatible to the odoo csv format
493 elif 'adm1' in row:
494 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['adm1']])
495 if pin_adm:
496 row['pin_adm'] = rpad(pin_adm, 16)
Philipp Maiere053da52019-09-05 13:08:36 +0200497
498 # If the CSV-File defines a pin_adm_hex field use this field to
499 # generate pin_adm from that.
500 pin_adm_hex = row.get('pin_adm_hex')
501 if pin_adm_hex:
502 if len(pin_adm_hex) == 16:
503 row['pin_adm'] = pin_adm_hex
504 # Ensure that it's hex-encoded
505 try:
506 try_encode = h2b(pin_adm)
507 except ValueError:
508 raise ValueError("pin_adm_hex needs to be hex encoded using this option")
509 else:
510 raise ValueError("pin_adm_hex needs to be exactly 16 digits (hex encoded)")
511
Harald Welte7f62cec2012-08-13 20:07:41 +0200512 return row
513
Harald Weltec26b8292012-08-15 15:25:51 +0200514
Harald Welte130524b2012-08-13 15:53:43 +0200515def write_params_hlr(opts, params):
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100516 # SQLite3 OpenBSC HLR
517 if opts.write_hlr:
518 import sqlite3
519 conn = sqlite3.connect(opts.write_hlr)
520
521 c = conn.execute(
522 'INSERT INTO Subscriber ' +
523 '(imsi, name, extension, authorized, created, updated) ' +
524 'VALUES ' +
525 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
526 [
527 params['imsi'],
528 params['name'],
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200529 '9' + params['iccid'][-5:-1]
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100530 ],
531 )
532 sub_id = c.lastrowid
533 c.close()
534
535 c = conn.execute(
536 'INSERT INTO AuthKeys ' +
537 '(subscriber_id, algorithm_id, a3a8_ki)' +
538 'VALUES ' +
539 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100540 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100541 )
542
543 conn.commit()
544 conn.close()
545
Harald Welte130524b2012-08-13 15:53:43 +0200546def write_parameters(opts, params):
547 write_params_csv(opts, params)
Harald Welte7f62cec2012-08-13 20:07:41 +0200548 write_params_hlr(opts, params)
Harald Welte130524b2012-08-13 15:53:43 +0200549
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100550
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100551BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
552BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100553
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100554def init_batch(opts):
555 # Need to do something ?
556 if not opts.batch_mode:
557 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100558
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100559 for k in BATCH_INCOMPATIBLE:
560 if getattr(opts, k):
561 print "Incompatible option with batch_state: %s" % (k,)
562 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100563
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100564 # Don't load state if there is none ...
565 if not opts.batch_state:
566 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100567
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100568 if not os.path.isfile(opts.batch_state):
569 print "No state file yet"
570 return
571
572 # Get stored data
573 fh = open(opts.batch_state)
574 d = json.loads(fh.read())
575 fh.close()
576
577 for k,v in d.iteritems():
578 setattr(opts, k, v)
579
580
581def save_batch(opts):
582 # Need to do something ?
583 if not opts.batch_mode or not opts.batch_state:
584 return
585
586 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
587 fh = open(opts.batch_state, 'w')
588 fh.write(d)
589 fh.close()
590
591
592def card_detect(opts, scc):
Sylvain Munautbdca2522010-12-09 13:31:58 +0100593
Sylvain Munaut76504e02010-12-07 00:24:32 +0100594 # Detect type if needed
595 card = None
596 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
597
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100598 if opts.type in ("auto", "auto_once"):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100599 for kls in _cards_classes:
600 card = kls.autodetect(scc)
601 if card:
Philipp Maierac9dde62018-07-04 11:05:14 +0200602 print "Autodetected card type: %s" % card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100603 card.reset()
604 break
605
606 if card is None:
607 print "Autodetection failed"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100608 return
609
610 if opts.type == "auto_once":
611 opts.type = card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100612
613 elif opts.type in ctypes:
614 card = ctypes[opts.type](scc)
615
616 else:
Philipp Maierac9dde62018-07-04 11:05:14 +0200617 raise ValueError("Unknown card type: %s" % opts.type)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100618
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100619 return card
Sylvain Munaut76504e02010-12-07 00:24:32 +0100620
Sylvain Munaut76504e02010-12-07 00:24:32 +0100621
Philipp Maierc5b422e2019-08-30 11:41:02 +0200622def process_card(opts, first, card_handler):
623
624 if opts.dry_run is False:
625 # Connect transport
626 card_handler.get(first)
627
628 if opts.dry_run is False:
629 # Get card
630 card = card_detect(opts, scc)
631 if card is None:
632 print "No card detected!"
633 return -1
634
635 # Probe only
636 if opts.probe:
637 return 0
638
639 # Erase if requested
640 if opts.erase:
641 print "Formatting ..."
642 card.erase()
643 card.reset()
644
645 # Generate parameters
646 if opts.source == 'cmdline':
647 cp = gen_parameters(opts)
648 elif opts.source == 'csv':
649 imsi = None
650 iccid = None
651 if opts.read_iccid:
652 if opts.dry_run:
653 # Connect transport
654 card_handler.get(false)
655 (res,_) = scc.read_binary(['3f00', '2fe2'], length=10)
656 iccid = dec_iccid(res)
657 elif opts.read_imsi:
658 if opts.dry_run:
659 # Connect transport
660 card_handler.get(false)
661 (res,_) = scc.read_binary(EF['IMSI'])
662 imsi = swap_nibbles(res)[3:]
663 else:
664 imsi = opts.imsi
665 cp = read_params_csv(opts, imsi=imsi, iccid=iccid)
666 if cp is None:
Philipp Maier1de89bf2019-09-12 13:40:02 +0200667 print "Error reading parameters from CSV file!\n"
Philipp Maierc5b422e2019-08-30 11:41:02 +0200668 return 2
669 print_parameters(cp)
670
671 if opts.dry_run is False:
672 # Program the card
673 print "Programming ..."
674 card.program(cp)
675 else:
676 print "Dry Run: NOT PROGRAMMING!"
677
678 # Write parameters permanently
679 write_parameters(opts, cp)
680
681 # Batch mode state update and save
682 if opts.num is not None:
683 opts.num += 1
684 save_batch(opts)
685
686 card_handler.done()
687 return 0
688
689
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100690if __name__ == '__main__':
691
692 # Parse options
693 opts = parse_options()
694
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700695 # Init card reader driver
696 if opts.pcsc_dev is not None:
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700697 print("Using PC/SC reader (dev=%d) interface"
698 % opts.pcsc_dev)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100699 from pySim.transport.pcsc import PcscSimLink
700 sl = PcscSimLink(opts.pcsc_dev)
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +0700701 elif opts.osmocon_sock is not None:
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700702 print("Using Calypso-based (OsmocomBB, sock=%s) reader interface"
703 % opts.osmocon_sock)
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +0700704 from pySim.transport.calypso import CalypsoSimLink
705 sl = CalypsoSimLink(sock_path=opts.osmocon_sock)
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700706 else: # Serial reader is default
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700707 print("Using serial reader (port=%s, baudrate=%d) interface"
708 % (opts.device, opts.baudrate))
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700709 from pySim.transport.serial import SerialSimLink
710 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100711
712 # Create command layer
713 scc = SimCardCommands(transport=sl)
714
715 # Batch mode init
716 init_batch(opts)
717
Philipp Maierc5b422e2019-08-30 11:41:02 +0200718 if opts.card_handler:
719 card_handler = card_handler_auto(sl, opts.card_handler)
720 else:
721 card_handler = card_handler(sl)
722
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100723 # Iterate
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100724 first = True
725 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100726
Philipp Maierc5b422e2019-08-30 11:41:02 +0200727 while 1:
728 try:
729 rc = process_card(opts, first, card_handler)
730 except (KeyboardInterrupt):
731 print ""
732 print "Terminated by user!"
733 sys.exit(0)
734 except (SystemExit):
735 raise
736 except:
737 print ""
738 print "Card programming failed with an execption:"
739 print "---------------------8<---------------------"
740 traceback.print_exc()
741 print "---------------------8<---------------------"
742 print ""
743 rc = -1
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200744
Philipp Maierc5b422e2019-08-30 11:41:02 +0200745 # Something did not work as well as expected, however, lets
746 # make sure the card is pulled from the reader.
747 if rc != 0:
748 card_handler.error()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100749
Philipp Maierc5b422e2019-08-30 11:41:02 +0200750 # If we are not in batch mode we are done in any case, so lets
751 # exit here.
752 if not opts.batch_mode:
753 sys.exit(rc)
754
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100755 first = False
756