blob: eca8b4ecca97de60190d4418b01d31e7b992e03b [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
Alexander Chemeris19fffa12018-01-11 13:06:43 +090042from pySim.utils import h2b, swap_nibbles, rpad, derive_milenage_opc, calculate_luhn
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 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010061 parser.add_option("-t", "--type", dest="type",
62 help="Card type (user -t list to view) [default: %default]",
63 default="auto",
64 )
Philipp Maierac9dde62018-07-04 11:05:14 +020065 parser.add_option("-T", "--probe", dest="probe",
66 help="Determine card type",
67 default=False, action="store_true"
68 )
Jan Balkec3ebd332015-01-26 12:22:55 +010069 parser.add_option("-a", "--pin-adm", dest="pin_adm",
70 help="ADM PIN used for provisioning (overwrites default)",
71 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010072 parser.add_option("-e", "--erase", dest="erase", action='store_true',
73 help="Erase beforehand [default: %default]",
74 default=False,
75 )
76
Harald Welte7f62cec2012-08-13 20:07:41 +020077 parser.add_option("-S", "--source", dest="source",
78 help="Data Source[default: %default]",
79 default="cmdline",
80 )
81
82 # if mode is "cmdline"
Sylvain Munaut76504e02010-12-07 00:24:32 +010083 parser.add_option("-n", "--name", dest="name",
84 help="Operator name [default: %default]",
85 default="Magic",
86 )
87 parser.add_option("-c", "--country", dest="country", type="int", metavar="CC",
88 help="Country code [default: %default]",
89 default=1,
90 )
91 parser.add_option("-x", "--mcc", dest="mcc", type="int",
92 help="Mobile Country Code [default: %default]",
93 default=901,
94 )
95 parser.add_option("-y", "--mnc", dest="mnc", type="int",
Sylvain Munaut17716032010-12-08 22:33:51 +010096 help="Mobile Network Code [default: %default]",
Sylvain Munaut76504e02010-12-07 00:24:32 +010097 default=55,
98 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +010099 parser.add_option("-m", "--smsc", dest="smsc",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100100 help="SMSP [default: '00 + country code + 5555']",
101 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100102 parser.add_option("-M", "--smsp", dest="smsp",
103 help="Raw SMSP content in hex [default: auto from SMSC]",
104 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100105
106 parser.add_option("-s", "--iccid", dest="iccid", metavar="ID",
107 help="Integrated Circuit Card ID",
108 )
109 parser.add_option("-i", "--imsi", dest="imsi",
110 help="International Mobile Subscriber Identity",
111 )
112 parser.add_option("-k", "--ki", dest="ki",
113 help="Ki (default is to randomize)",
114 )
Harald Welte93b38cd2012-03-22 14:31:36 +0100115 parser.add_option("-o", "--opc", dest="opc",
116 help="OPC (default is to randomize)",
117 )
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100118 parser.add_option("--op", dest="op",
119 help="Set OP to derive OPC from OP and KI",
120 )
Alexander Chemeris21885242013-07-02 16:56:55 +0400121 parser.add_option("--acc", dest="acc",
122 help="Set ACC bits (Access Control Code). not all card types are supported",
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200123 )
124 parser.add_option("--read-imsi", dest="read_imsi", action="store_true",
125 help="Read the IMSI from the CARD", default=False
Alexander Chemeris21885242013-07-02 16:56:55 +0400126 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100127 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
128 help="Secret used for ICCID/IMSI autogen",
129 )
130 parser.add_option("-j", "--num", dest="num", type=int,
131 help="Card # used for ICCID/IMSI autogen",
132 )
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100133 parser.add_option("--batch", dest="batch_mode",
134 help="Enable batch mode [default: %default]",
135 default=False, action='store_true',
136 )
137 parser.add_option("--batch-state", dest="batch_state", metavar="FILE",
138 help="Optional batch state file",
139 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100140
Harald Welte7f62cec2012-08-13 20:07:41 +0200141 # if mode is "csv"
142 parser.add_option("--read-csv", dest="read_csv", metavar="FILE",
143 help="Read parameters from CSV file rather than command line")
144
145
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100146 parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
147 help="Append generated parameters in CSV file",
148 )
149 parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
150 help="Append generated parameters to OpenBSC HLR sqlite3",
151 )
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200152 parser.add_option("--dry-run", dest="dry_run",
153 help="Perform a 'dry run', don't actually program the card",
154 default=False, action="store_true")
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100155
Sylvain Munaut76504e02010-12-07 00:24:32 +0100156 (options, args) = parser.parse_args()
157
158 if options.type == 'list':
159 for kls in _cards_classes:
160 print kls.name
161 sys.exit(0)
162
Philipp Maierac9dde62018-07-04 11:05:14 +0200163 if options.probe:
164 return options
165
Harald Welte7f62cec2012-08-13 20:07:41 +0200166 if options.source == 'csv':
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200167 if (options.imsi is None) and (options.batch_mode is False) and (options.read_imsi is False):
168 parser.error("CSV mode needs either an IMSI, --read-imsi or batch mode")
Harald Welte7f62cec2012-08-13 20:07:41 +0200169 if options.read_csv is None:
170 parser.error("CSV mode requires a CSV input file")
171 elif options.source == 'cmdline':
172 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
173 parser.error("If either IMSI or ICCID isn't specified, num is required")
174 else:
175 parser.error("Only `cmdline' and `csv' sources supported")
176
177 if (options.read_csv is not None) and (options.source != 'csv'):
178 parser.error("You cannot specify a CSV input file in source != csv")
179
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100180 if (options.batch_mode) and (options.num is None):
181 options.num = 0
182
Sylvain Munaut98d2b852010-12-23 20:27:25 +0100183 if (options.batch_mode):
184 if (options.imsi is not None) or (options.iccid is not None):
185 parser.error("Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more informations")
186
Sylvain Munaut76504e02010-12-07 00:24:32 +0100187 if args:
188 parser.error("Extraneous arguments")
189
190 return options
191
192
193def _digits(secret, usage, len, num):
194 s = hashlib.sha1(secret + usage + '%d' % num)
195 d = ''.join(['%02d'%ord(x) for x in s.digest()])
196 return d[0:len]
197
198def _mcc_mnc_digits(mcc, mnc):
199 return ('%03d%03d' if mnc > 100 else '%03d%02d') % (mcc, mnc)
200
201def _cc_digits(cc):
202 return ('%03d' if cc > 100 else '%02d') % cc
203
204def _isnum(s, l=-1):
205 return s.isdigit() and ((l== -1) or (len(s) == l))
206
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100207def _ishex(s, l=-1):
208 hc = '0123456789abcdef'
209 return all([x in hc for x in s.lower()]) and ((l== -1) or (len(s) == l))
210
Sylvain Munaut76504e02010-12-07 00:24:32 +0100211
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100212def _dbi_binary_quote(s):
213 # Count usage of each char
214 cnt = {}
215 for c in s:
216 cnt[c] = cnt.get(c, 0) + 1
217
218 # Find best offset
219 e = 0
220 m = len(s)
221 for i in range(1, 256):
222 if i == 39:
223 continue
224 sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
225 if sum_ < m:
226 m = sum_
227 e = i
228 if m == 0: # No overhead ? use this !
229 break;
Sylvain Munaut1a914432011-12-08 20:08:26 +0100230
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100231 # Generate output
232 out = []
233 out.append( chr(e) ) # Offset
234 for c in s:
235 x = (256 + ord(c) - e) % 256
236 if x in (0, 1, 39):
237 out.append('\x01')
238 out.append(chr(x+1))
239 else:
240 out.append(chr(x))
241
242 return ''.join(out)
243
Sylvain Munaut76504e02010-12-07 00:24:32 +0100244def gen_parameters(opts):
Jan Balkec3ebd332015-01-26 12:22:55 +0100245 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki, PIN-ADM from the
Sylvain Munaut76504e02010-12-07 00:24:32 +0100246 options given by the user"""
247
248 # MCC/MNC
249 mcc = opts.mcc
250 mnc = opts.mnc
251
252 if not ((0 < mcc < 999) and (0 < mnc < 999)):
253 raise ValueError('mcc & mnc must be between 0 and 999')
254
255 # Digitize country code (2 or 3 digits)
256 cc_digits = _cc_digits(opts.country)
257
258 # Digitize MCC/MNC (5 or 6 digits)
259 plmn_digits = _mcc_mnc_digits(mcc, mnc)
260
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100261 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
Sylvain Munaut76504e02010-12-07 00:24:32 +0100262 if opts.iccid is not None:
263 iccid = opts.iccid
Todd Neal9eeadfc2018-04-25 15:36:29 -0500264 if not _isnum(iccid, 19) and not _isnum(iccid, 20):
265 raise ValueError('ICCID must be 19 or 20 digits !');
Sylvain Munaut76504e02010-12-07 00:24:32 +0100266
267 else:
268 if opts.num is None:
269 raise ValueError('Neither ICCID nor card number specified !')
270
271 iccid = (
272 '89' + # Common prefix (telecom)
273 cc_digits + # Country Code on 2/3 digits
274 plmn_digits # MCC/MNC on 5/6 digits
275 )
276
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100277 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100278
279 if opts.secret is None:
280 # The raw number
281 iccid += ('%%0%dd' % ml) % opts.num
282 else:
283 # Randomized digits
284 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
285
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100286 # Add checksum digit
287 iccid += ('%1d' % calculate_luhn(iccid))
288
Sylvain Munaut76504e02010-12-07 00:24:32 +0100289 # IMSI (15 digits usually)
290 if opts.imsi is not None:
291 imsi = opts.imsi
292 if not _isnum(imsi):
293 raise ValueError('IMSI must be digits only !')
294
295 else:
296 if opts.num is None:
297 raise ValueError('Neither IMSI nor card number specified !')
298
299 ml = 15 - len(plmn_digits)
300
301 if opts.secret is None:
302 # The raw number
303 msin = ('%%0%dd' % ml) % opts.num
304 else:
305 # Randomized digits
306 msin = _digits(opts.secret, 'imsi', ml, opts.num)
307
308 imsi = (
309 plmn_digits + # MCC/MNC on 5/6 digits
310 msin # MSIN
311 )
312
313 # SMSP
314 if opts.smsp is not None:
315 smsp = opts.smsp
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100316 if not _ishex(smsp):
317 raise ValueError('SMSP must be hex digits only !')
318 if len(smsp) < 28*2:
319 raise ValueError('SMSP must be at least 28 bytes')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100320
321 else:
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100322 if opts.smsc is not None:
323 smsc = opts.smsc
324 if not _isnum(smsc):
325 raise ValueError('SMSC must be digits only !')
326 else:
327 smsc = '00%d' % opts.country + '5555' # Hack ...
328
Sylvain Munaut9977c862011-12-10 09:57:16 +0100329 smsc = '%02d' % ((len(smsc) + 3)//2,) + "81" + swap_nibbles(rpad(smsc, 20))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100330
331 smsp = (
332 'e1' + # Parameters indicator
333 'ff' * 12 + # TP-Destination address
334 smsc + # TP-Service Centre Address
335 '00' + # TP-Protocol identifier
336 '00' + # TP-Data coding scheme
337 '00' # TP-Validity period
338 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100339
Alexander Chemeris21885242013-07-02 16:56:55 +0400340 # ACC
341 if opts.acc is not None:
342 acc = opts.acc
343 if not _ishex(acc):
344 raise ValueError('ACC must be hex digits only !')
345 if len(acc) != 2*2:
346 raise ValueError('ACC must be exactly 2 bytes')
347
348 else:
349 acc = None
350
Sylvain Munaut76504e02010-12-07 00:24:32 +0100351 # Ki (random)
352 if opts.ki is not None:
353 ki = opts.ki
354 if not re.match('^[0-9a-fA-F]{32}$', ki):
355 raise ValueError('Ki needs to be 128 bits, in hex format')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100356 else:
357 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
358
Alexander Chemerisd17ca3d2017-07-18 16:40:58 +0300359 # OPC (random)
Harald Welte93b38cd2012-03-22 14:31:36 +0100360 if opts.opc is not None:
361 opc = opts.opc
362 if not re.match('^[0-9a-fA-F]{32}$', opc):
363 raise ValueError('OPC needs to be 128 bits, in hex format')
364
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100365 elif opts.op is not None:
366 opc = derive_milenage_opc(ki, opts.op)
Harald Welte93b38cd2012-03-22 14:31:36 +0100367 else:
368 opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
369
Jan Balkec3ebd332015-01-26 12:22:55 +0100370 if opts.pin_adm is not None:
Philipp Maierd9824882018-06-13 09:21:59 +0200371 if len(opts.pin_adm) <= 8:
372 pin_adm = ''.join(['%02x'%(ord(x)) for x in opts.pin_adm])
373 pin_adm = rpad(pin_adm, 16)
374 elif len(opts.pin_adm) == 16:
375 pin_adm = opts.pin_adm
376 else:
377 raise ValueError("PIN-ADM needs to be <=8 digits (ascii) or exactly 16 digits (raw hex)")
Jan Balkec3ebd332015-01-26 12:22:55 +0100378 else:
379 pin_adm = None
380
Harald Welte93b38cd2012-03-22 14:31:36 +0100381
Sylvain Munaut76504e02010-12-07 00:24:32 +0100382 # Return that
383 return {
384 'name' : opts.name,
385 'iccid' : iccid,
386 'mcc' : mcc,
387 'mnc' : mnc,
388 'imsi' : imsi,
389 'smsp' : smsp,
390 'ki' : ki,
Harald Welte93b38cd2012-03-22 14:31:36 +0100391 'opc' : opc,
Alexander Chemeris21885242013-07-02 16:56:55 +0400392 'acc' : acc,
Jan Balkec3ebd332015-01-26 12:22:55 +0100393 'pin_adm' : pin_adm,
Sylvain Munaut76504e02010-12-07 00:24:32 +0100394 }
395
396
397def print_parameters(params):
398
399 print """Generated card parameters :
400 > Name : %(name)s
401 > SMSP : %(smsp)s
402 > ICCID : %(iccid)s
403 > MCC/MNC : %(mcc)d/%(mnc)d
404 > IMSI : %(imsi)s
405 > Ki : %(ki)s
Harald Welte93b38cd2012-03-22 14:31:36 +0100406 > OPC : %(opc)s
Alexander Chemeris21885242013-07-02 16:56:55 +0400407 > ACC : %(acc)s
Sylvain Munaut76504e02010-12-07 00:24:32 +0100408""" % params
409
410
Harald Welte130524b2012-08-13 15:53:43 +0200411def write_params_csv(opts, params):
412 # csv
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100413 if opts.write_csv:
414 import csv
Harald Welte93b38cd2012-03-22 14:31:36 +0100415 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100416 f = open(opts.write_csv, 'a')
417 cw = csv.writer(f)
418 cw.writerow([params[x] for x in row])
419 f.close()
420
Harald Weltec26b8292012-08-15 15:25:51 +0200421def _read_params_csv(opts, imsi):
Harald Welte7f62cec2012-08-13 20:07:41 +0200422 import csv
423 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
424 f = open(opts.read_csv, 'r')
425 cr = csv.DictReader(f, row)
426 i = 0
427 for row in cr:
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200428 if opts.num is not None and opts.read_imsi is False:
Harald Welte7f62cec2012-08-13 20:07:41 +0200429 if opts.num == i:
Harald Weltec26b8292012-08-15 15:25:51 +0200430 f.close()
431 return row;
432 i += 1
Harald Welte7f62cec2012-08-13 20:07:41 +0200433 if row['imsi'] == imsi:
Harald Weltec26b8292012-08-15 15:25:51 +0200434 f.close()
435 return row;
Harald Welte7f62cec2012-08-13 20:07:41 +0200436
437 f.close()
Harald Weltec26b8292012-08-15 15:25:51 +0200438 return None
439
440def read_params_csv(opts, imsi):
441 row = _read_params_csv(opts, imsi)
442 if row is not None:
443 row['mcc'] = int(row['mcc'])
444 row['mnc'] = int(row['mnc'])
Harald Welte7f62cec2012-08-13 20:07:41 +0200445 return row
446
Harald Weltec26b8292012-08-15 15:25:51 +0200447
Harald Welte130524b2012-08-13 15:53:43 +0200448def write_params_hlr(opts, params):
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100449 # SQLite3 OpenBSC HLR
450 if opts.write_hlr:
451 import sqlite3
452 conn = sqlite3.connect(opts.write_hlr)
453
454 c = conn.execute(
455 'INSERT INTO Subscriber ' +
456 '(imsi, name, extension, authorized, created, updated) ' +
457 'VALUES ' +
458 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
459 [
460 params['imsi'],
461 params['name'],
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200462 '9' + params['iccid'][-5:-1]
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100463 ],
464 )
465 sub_id = c.lastrowid
466 c.close()
467
468 c = conn.execute(
469 'INSERT INTO AuthKeys ' +
470 '(subscriber_id, algorithm_id, a3a8_ki)' +
471 'VALUES ' +
472 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100473 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100474 )
475
476 conn.commit()
477 conn.close()
478
Harald Welte130524b2012-08-13 15:53:43 +0200479def write_parameters(opts, params):
480 write_params_csv(opts, params)
Harald Welte7f62cec2012-08-13 20:07:41 +0200481 write_params_hlr(opts, params)
Harald Welte130524b2012-08-13 15:53:43 +0200482
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100483
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100484BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
485BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100486
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100487def init_batch(opts):
488 # Need to do something ?
489 if not opts.batch_mode:
490 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100491
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100492 for k in BATCH_INCOMPATIBLE:
493 if getattr(opts, k):
494 print "Incompatible option with batch_state: %s" % (k,)
495 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100496
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100497 # Don't load state if there is none ...
498 if not opts.batch_state:
499 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100500
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100501 if not os.path.isfile(opts.batch_state):
502 print "No state file yet"
503 return
504
505 # Get stored data
506 fh = open(opts.batch_state)
507 d = json.loads(fh.read())
508 fh.close()
509
510 for k,v in d.iteritems():
511 setattr(opts, k, v)
512
513
514def save_batch(opts):
515 # Need to do something ?
516 if not opts.batch_mode or not opts.batch_state:
517 return
518
519 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
520 fh = open(opts.batch_state, 'w')
521 fh.write(d)
522 fh.close()
523
524
525def card_detect(opts, scc):
Sylvain Munautbdca2522010-12-09 13:31:58 +0100526
Sylvain Munaut76504e02010-12-07 00:24:32 +0100527 # Detect type if needed
528 card = None
529 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
530
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100531 if opts.type in ("auto", "auto_once"):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100532 for kls in _cards_classes:
533 card = kls.autodetect(scc)
534 if card:
Philipp Maierac9dde62018-07-04 11:05:14 +0200535 print "Autodetected card type: %s" % card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100536 card.reset()
537 break
538
539 if card is None:
540 print "Autodetection failed"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100541 return
542
543 if opts.type == "auto_once":
544 opts.type = card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100545
546 elif opts.type in ctypes:
547 card = ctypes[opts.type](scc)
548
549 else:
Philipp Maierac9dde62018-07-04 11:05:14 +0200550 raise ValueError("Unknown card type: %s" % opts.type)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100551
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100552 return card
Sylvain Munaut76504e02010-12-07 00:24:32 +0100553
Sylvain Munaut76504e02010-12-07 00:24:32 +0100554
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100555if __name__ == '__main__':
556
557 # Parse options
558 opts = parse_options()
559
560 # Connect to the card
561 if opts.pcsc_dev is None:
562 from pySim.transport.serial import SerialSimLink
563 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
564 else:
565 from pySim.transport.pcsc import PcscSimLink
566 sl = PcscSimLink(opts.pcsc_dev)
567
568 # Create command layer
569 scc = SimCardCommands(transport=sl)
570
571 # Batch mode init
572 init_batch(opts)
573
574 # Iterate
575 done = False
576 first = True
577 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100578
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100579 while not done:
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200580
581 if opts.dry_run is False:
582 # Connect transport
583 print "Insert card now (or CTRL-C to cancel)"
584 sl.wait_for_card(newcardonly=not first)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100585
586 # Not the first anymore !
587 first = False
588
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200589 if opts.dry_run is False:
590 # Get card
591 card = card_detect(opts, scc)
592 if card is None:
593 if opts.batch_mode:
594 first = False
595 continue
596 else:
597 sys.exit(-1)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100598
Philipp Maierac9dde62018-07-04 11:05:14 +0200599 # Probe only
600 if opts.probe:
601 break;
602
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200603 # Erase if requested
604 if opts.erase:
605 print "Formatting ..."
606 card.erase()
607 card.reset()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100608
609 # Generate parameters
Harald Welte7f62cec2012-08-13 20:07:41 +0200610 if opts.source == 'cmdline':
611 cp = gen_parameters(opts)
612 elif opts.source == 'csv':
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200613 if opts.read_imsi:
614 if opts.dry_run:
615 # Connect transport
616 print "Insert card now (or CTRL-C to cancel)"
617 sl.wait_for_card(newcardonly=not first)
Alexander Chemeris47c73ab2018-01-10 14:10:17 +0900618 (res,_) = scc.read_binary(EF['IMSI'])
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200619 imsi = swap_nibbles(res)[3:]
620 else:
621 imsi = opts.imsi
622 cp = read_params_csv(opts, imsi)
Harald Welte7f62cec2012-08-13 20:07:41 +0200623 if cp is None:
624 print "Error reading parameters\n"
625 sys.exit(2)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100626 print_parameters(cp)
627
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200628 if opts.dry_run is False:
629 # Program the card
630 print "Programming ..."
631 if opts.dry_run is not True:
632 card.program(cp)
633 else:
634 print "Dry Run: NOT PROGRAMMING!"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100635
636 # Write parameters permanently
637 write_parameters(opts, cp)
638
639 # Batch mode state update and save
Sylvain Munaut8d243e82010-12-23 20:27:48 +0100640 if opts.num is not None:
641 opts.num += 1
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100642 save_batch(opts)
643
644 # Done for this card and maybe for everything ?
645 print "Done !\n"
646
647 if not opts.batch_mode:
648 done = True