blob: 44ca1fd2a26613440aaa826be136bc6ba859d1f1 [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
Sylvain Munaut607ce2a2011-12-08 20:16:43 +010042from pySim.utils import h2b, swap_nibbles, rpad
Sylvain Munaut76504e02010-12-07 00:24:32 +010043
44
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 )
Jan Balkec3ebd332015-01-26 12:22:55 +010065 parser.add_option("-a", "--pin-adm", dest="pin_adm",
66 help="ADM PIN used for provisioning (overwrites default)",
67 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010068 parser.add_option("-e", "--erase", dest="erase", action='store_true',
69 help="Erase beforehand [default: %default]",
70 default=False,
71 )
72
Harald Welte7f62cec2012-08-13 20:07:41 +020073 parser.add_option("-S", "--source", dest="source",
74 help="Data Source[default: %default]",
75 default="cmdline",
76 )
77
78 # if mode is "cmdline"
Sylvain Munaut76504e02010-12-07 00:24:32 +010079 parser.add_option("-n", "--name", dest="name",
80 help="Operator name [default: %default]",
81 default="Magic",
82 )
83 parser.add_option("-c", "--country", dest="country", type="int", metavar="CC",
84 help="Country code [default: %default]",
85 default=1,
86 )
87 parser.add_option("-x", "--mcc", dest="mcc", type="int",
88 help="Mobile Country Code [default: %default]",
89 default=901,
90 )
91 parser.add_option("-y", "--mnc", dest="mnc", type="int",
Sylvain Munaut17716032010-12-08 22:33:51 +010092 help="Mobile Network Code [default: %default]",
Sylvain Munaut76504e02010-12-07 00:24:32 +010093 default=55,
94 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +010095 parser.add_option("-m", "--smsc", dest="smsc",
Sylvain Munaut76504e02010-12-07 00:24:32 +010096 help="SMSP [default: '00 + country code + 5555']",
97 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +010098 parser.add_option("-M", "--smsp", dest="smsp",
99 help="Raw SMSP content in hex [default: auto from SMSC]",
100 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100101
102 parser.add_option("-s", "--iccid", dest="iccid", metavar="ID",
103 help="Integrated Circuit Card ID",
104 )
105 parser.add_option("-i", "--imsi", dest="imsi",
106 help="International Mobile Subscriber Identity",
107 )
108 parser.add_option("-k", "--ki", dest="ki",
109 help="Ki (default is to randomize)",
110 )
Harald Welte93b38cd2012-03-22 14:31:36 +0100111 parser.add_option("-o", "--opc", dest="opc",
112 help="OPC (default is to randomize)",
113 )
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100114 parser.add_option("--op", dest="op",
115 help="Set OP to derive OPC from OP and KI",
116 )
Alexander Chemeris21885242013-07-02 16:56:55 +0400117 parser.add_option("--acc", dest="acc",
118 help="Set ACC bits (Access Control Code). not all card types are supported",
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200119 )
120 parser.add_option("--read-imsi", dest="read_imsi", action="store_true",
121 help="Read the IMSI from the CARD", default=False
Alexander Chemeris21885242013-07-02 16:56:55 +0400122 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100123 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
124 help="Secret used for ICCID/IMSI autogen",
125 )
126 parser.add_option("-j", "--num", dest="num", type=int,
127 help="Card # used for ICCID/IMSI autogen",
128 )
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100129 parser.add_option("--batch", dest="batch_mode",
130 help="Enable batch mode [default: %default]",
131 default=False, action='store_true',
132 )
133 parser.add_option("--batch-state", dest="batch_state", metavar="FILE",
134 help="Optional batch state file",
135 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100136
Harald Welte7f62cec2012-08-13 20:07:41 +0200137 # if mode is "csv"
138 parser.add_option("--read-csv", dest="read_csv", metavar="FILE",
139 help="Read parameters from CSV file rather than command line")
140
141
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100142 parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
143 help="Append generated parameters in CSV file",
144 )
145 parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
146 help="Append generated parameters to OpenBSC HLR sqlite3",
147 )
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200148 parser.add_option("--dry-run", dest="dry_run",
149 help="Perform a 'dry run', don't actually program the card",
150 default=False, action="store_true")
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100151
Sylvain Munaut76504e02010-12-07 00:24:32 +0100152 (options, args) = parser.parse_args()
153
154 if options.type == 'list':
155 for kls in _cards_classes:
156 print kls.name
157 sys.exit(0)
158
Harald Welte7f62cec2012-08-13 20:07:41 +0200159 if options.source == 'csv':
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200160 if (options.imsi is None) and (options.batch_mode is False) and (options.read_imsi is False):
161 parser.error("CSV mode needs either an IMSI, --read-imsi or batch mode")
Harald Welte7f62cec2012-08-13 20:07:41 +0200162 if options.read_csv is None:
163 parser.error("CSV mode requires a CSV input file")
164 elif options.source == 'cmdline':
165 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
166 parser.error("If either IMSI or ICCID isn't specified, num is required")
167 else:
168 parser.error("Only `cmdline' and `csv' sources supported")
169
170 if (options.read_csv is not None) and (options.source != 'csv'):
171 parser.error("You cannot specify a CSV input file in source != csv")
172
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100173 if (options.batch_mode) and (options.num is None):
174 options.num = 0
175
Sylvain Munaut98d2b852010-12-23 20:27:25 +0100176 if (options.batch_mode):
177 if (options.imsi is not None) or (options.iccid is not None):
178 parser.error("Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more informations")
179
Sylvain Munaut76504e02010-12-07 00:24:32 +0100180 if args:
181 parser.error("Extraneous arguments")
182
183 return options
184
185
186def _digits(secret, usage, len, num):
187 s = hashlib.sha1(secret + usage + '%d' % num)
188 d = ''.join(['%02d'%ord(x) for x in s.digest()])
189 return d[0:len]
190
191def _mcc_mnc_digits(mcc, mnc):
192 return ('%03d%03d' if mnc > 100 else '%03d%02d') % (mcc, mnc)
193
194def _cc_digits(cc):
195 return ('%03d' if cc > 100 else '%02d') % cc
196
197def _isnum(s, l=-1):
198 return s.isdigit() and ((l== -1) or (len(s) == l))
199
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100200def _ishex(s, l=-1):
201 hc = '0123456789abcdef'
202 return all([x in hc for x in s.lower()]) and ((l== -1) or (len(s) == l))
203
Sylvain Munaut76504e02010-12-07 00:24:32 +0100204
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100205def _dbi_binary_quote(s):
206 # Count usage of each char
207 cnt = {}
208 for c in s:
209 cnt[c] = cnt.get(c, 0) + 1
210
211 # Find best offset
212 e = 0
213 m = len(s)
214 for i in range(1, 256):
215 if i == 39:
216 continue
217 sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
218 if sum_ < m:
219 m = sum_
220 e = i
221 if m == 0: # No overhead ? use this !
222 break;
Sylvain Munaut1a914432011-12-08 20:08:26 +0100223
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100224 # Generate output
225 out = []
226 out.append( chr(e) ) # Offset
227 for c in s:
228 x = (256 + ord(c) - e) % 256
229 if x in (0, 1, 39):
230 out.append('\x01')
231 out.append(chr(x+1))
232 else:
233 out.append(chr(x))
234
235 return ''.join(out)
236
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100237def calculate_luhn(cc):
238 num = map(int, str(cc))
239 check_digit = 10 - sum(num[-2::-2] + [sum(divmod(d * 2, 10)) for d in num[::-2]]) % 10
240 return 0 if check_digit == 10 else check_digit
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100241
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100242def derive_milenage_opc(ki_hex, op_hex):
243 """
244 Run the milenage algorithm.
245 """
246 from Crypto.Cipher import AES
247 from Crypto.Util.strxor import strxor
248 from pySim.utils import b2h
249
250 # We pass in hex string and now need to work on bytes
251 aes = AES.new(h2b(ki_hex))
252 opc_bytes = aes.encrypt(h2b(op_hex))
253 return b2h(strxor(opc_bytes, h2b(op_hex)))
254
Sylvain Munaut76504e02010-12-07 00:24:32 +0100255def gen_parameters(opts):
Jan Balkec3ebd332015-01-26 12:22:55 +0100256 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki, PIN-ADM from the
Sylvain Munaut76504e02010-12-07 00:24:32 +0100257 options given by the user"""
258
259 # MCC/MNC
260 mcc = opts.mcc
261 mnc = opts.mnc
262
263 if not ((0 < mcc < 999) and (0 < mnc < 999)):
264 raise ValueError('mcc & mnc must be between 0 and 999')
265
266 # Digitize country code (2 or 3 digits)
267 cc_digits = _cc_digits(opts.country)
268
269 # Digitize MCC/MNC (5 or 6 digits)
270 plmn_digits = _mcc_mnc_digits(mcc, mnc)
271
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100272 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
Sylvain Munaut76504e02010-12-07 00:24:32 +0100273 if opts.iccid is not None:
274 iccid = opts.iccid
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100275 if not _isnum(iccid, 19):
276 raise ValueError('ICCID must be 19 digits !');
Sylvain Munaut76504e02010-12-07 00:24:32 +0100277
278 else:
279 if opts.num is None:
280 raise ValueError('Neither ICCID nor card number specified !')
281
282 iccid = (
283 '89' + # Common prefix (telecom)
284 cc_digits + # Country Code on 2/3 digits
285 plmn_digits # MCC/MNC on 5/6 digits
286 )
287
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100288 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100289
290 if opts.secret is None:
291 # The raw number
292 iccid += ('%%0%dd' % ml) % opts.num
293 else:
294 # Randomized digits
295 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
296
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100297 # Add checksum digit
298 iccid += ('%1d' % calculate_luhn(iccid))
299
Sylvain Munaut76504e02010-12-07 00:24:32 +0100300 # IMSI (15 digits usually)
301 if opts.imsi is not None:
302 imsi = opts.imsi
303 if not _isnum(imsi):
304 raise ValueError('IMSI must be digits only !')
305
306 else:
307 if opts.num is None:
308 raise ValueError('Neither IMSI nor card number specified !')
309
310 ml = 15 - len(plmn_digits)
311
312 if opts.secret is None:
313 # The raw number
314 msin = ('%%0%dd' % ml) % opts.num
315 else:
316 # Randomized digits
317 msin = _digits(opts.secret, 'imsi', ml, opts.num)
318
319 imsi = (
320 plmn_digits + # MCC/MNC on 5/6 digits
321 msin # MSIN
322 )
323
324 # SMSP
325 if opts.smsp is not None:
326 smsp = opts.smsp
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100327 if not _ishex(smsp):
328 raise ValueError('SMSP must be hex digits only !')
329 if len(smsp) < 28*2:
330 raise ValueError('SMSP must be at least 28 bytes')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100331
332 else:
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100333 if opts.smsc is not None:
334 smsc = opts.smsc
335 if not _isnum(smsc):
336 raise ValueError('SMSC must be digits only !')
337 else:
338 smsc = '00%d' % opts.country + '5555' # Hack ...
339
Sylvain Munaut9977c862011-12-10 09:57:16 +0100340 smsc = '%02d' % ((len(smsc) + 3)//2,) + "81" + swap_nibbles(rpad(smsc, 20))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100341
342 smsp = (
343 'e1' + # Parameters indicator
344 'ff' * 12 + # TP-Destination address
345 smsc + # TP-Service Centre Address
346 '00' + # TP-Protocol identifier
347 '00' + # TP-Data coding scheme
348 '00' # TP-Validity period
349 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100350
Alexander Chemeris21885242013-07-02 16:56:55 +0400351 # ACC
352 if opts.acc is not None:
353 acc = opts.acc
354 if not _ishex(acc):
355 raise ValueError('ACC must be hex digits only !')
356 if len(acc) != 2*2:
357 raise ValueError('ACC must be exactly 2 bytes')
358
359 else:
360 acc = None
361
Sylvain Munaut76504e02010-12-07 00:24:32 +0100362 # Ki (random)
363 if opts.ki is not None:
364 ki = opts.ki
365 if not re.match('^[0-9a-fA-F]{32}$', ki):
366 raise ValueError('Ki needs to be 128 bits, in hex format')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100367 else:
368 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
369
Alexander Chemerisd17ca3d2017-07-18 16:40:58 +0300370 # OPC (random)
Harald Welte93b38cd2012-03-22 14:31:36 +0100371 if opts.opc is not None:
372 opc = opts.opc
373 if not re.match('^[0-9a-fA-F]{32}$', opc):
374 raise ValueError('OPC needs to be 128 bits, in hex format')
375
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100376 elif opts.op is not None:
377 opc = derive_milenage_opc(ki, opts.op)
Harald Welte93b38cd2012-03-22 14:31:36 +0100378 else:
379 opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
380
Jan Balkec3ebd332015-01-26 12:22:55 +0100381 if opts.pin_adm is not None:
Alexander Chemerisa51592e2018-01-10 14:07:30 +0900382 pin_adm = opts.pin_adm
383 if not re.match('^([0-9a-fA-F][0-9a-fA-F])+$', pin_adm):
384 raise ValueError('ADM pin needs to be in hex format (even number of hex digits)')
Jan Balkec3ebd332015-01-26 12:22:55 +0100385 else:
386 pin_adm = None
387
Harald Welte93b38cd2012-03-22 14:31:36 +0100388
Sylvain Munaut76504e02010-12-07 00:24:32 +0100389 # Return that
390 return {
391 'name' : opts.name,
392 'iccid' : iccid,
393 'mcc' : mcc,
394 'mnc' : mnc,
395 'imsi' : imsi,
396 'smsp' : smsp,
397 'ki' : ki,
Harald Welte93b38cd2012-03-22 14:31:36 +0100398 'opc' : opc,
Alexander Chemeris21885242013-07-02 16:56:55 +0400399 'acc' : acc,
Jan Balkec3ebd332015-01-26 12:22:55 +0100400 'pin_adm' : pin_adm,
Sylvain Munaut76504e02010-12-07 00:24:32 +0100401 }
402
403
404def print_parameters(params):
405
406 print """Generated card parameters :
407 > Name : %(name)s
408 > SMSP : %(smsp)s
409 > ICCID : %(iccid)s
410 > MCC/MNC : %(mcc)d/%(mnc)d
411 > IMSI : %(imsi)s
412 > Ki : %(ki)s
Harald Welte93b38cd2012-03-22 14:31:36 +0100413 > OPC : %(opc)s
Alexander Chemeris21885242013-07-02 16:56:55 +0400414 > ACC : %(acc)s
Sylvain Munaut76504e02010-12-07 00:24:32 +0100415""" % params
416
417
Harald Welte130524b2012-08-13 15:53:43 +0200418def write_params_csv(opts, params):
419 # csv
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100420 if opts.write_csv:
421 import csv
Harald Welte93b38cd2012-03-22 14:31:36 +0100422 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100423 f = open(opts.write_csv, 'a')
424 cw = csv.writer(f)
425 cw.writerow([params[x] for x in row])
426 f.close()
427
Harald Weltec26b8292012-08-15 15:25:51 +0200428def _read_params_csv(opts, imsi):
Harald Welte7f62cec2012-08-13 20:07:41 +0200429 import csv
430 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
431 f = open(opts.read_csv, 'r')
432 cr = csv.DictReader(f, row)
433 i = 0
434 for row in cr:
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200435 if opts.num is not None and opts.read_imsi is False:
Harald Welte7f62cec2012-08-13 20:07:41 +0200436 if opts.num == i:
Harald Weltec26b8292012-08-15 15:25:51 +0200437 f.close()
438 return row;
439 i += 1
Harald Welte7f62cec2012-08-13 20:07:41 +0200440 if row['imsi'] == imsi:
Harald Weltec26b8292012-08-15 15:25:51 +0200441 f.close()
442 return row;
Harald Welte7f62cec2012-08-13 20:07:41 +0200443
444 f.close()
Harald Weltec26b8292012-08-15 15:25:51 +0200445 return None
446
447def read_params_csv(opts, imsi):
448 row = _read_params_csv(opts, imsi)
449 if row is not None:
450 row['mcc'] = int(row['mcc'])
451 row['mnc'] = int(row['mnc'])
Harald Welte7f62cec2012-08-13 20:07:41 +0200452 return row
453
Harald Weltec26b8292012-08-15 15:25:51 +0200454
Harald Welte130524b2012-08-13 15:53:43 +0200455def write_params_hlr(opts, params):
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100456 # SQLite3 OpenBSC HLR
457 if opts.write_hlr:
458 import sqlite3
459 conn = sqlite3.connect(opts.write_hlr)
460
461 c = conn.execute(
462 'INSERT INTO Subscriber ' +
463 '(imsi, name, extension, authorized, created, updated) ' +
464 'VALUES ' +
465 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
466 [
467 params['imsi'],
468 params['name'],
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200469 '9' + params['iccid'][-5:-1]
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100470 ],
471 )
472 sub_id = c.lastrowid
473 c.close()
474
475 c = conn.execute(
476 'INSERT INTO AuthKeys ' +
477 '(subscriber_id, algorithm_id, a3a8_ki)' +
478 'VALUES ' +
479 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100480 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100481 )
482
483 conn.commit()
484 conn.close()
485
Harald Welte130524b2012-08-13 15:53:43 +0200486def write_parameters(opts, params):
487 write_params_csv(opts, params)
Harald Welte7f62cec2012-08-13 20:07:41 +0200488 write_params_hlr(opts, params)
Harald Welte130524b2012-08-13 15:53:43 +0200489
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100490
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100491BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
492BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100493
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100494def init_batch(opts):
495 # Need to do something ?
496 if not opts.batch_mode:
497 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100498
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100499 for k in BATCH_INCOMPATIBLE:
500 if getattr(opts, k):
501 print "Incompatible option with batch_state: %s" % (k,)
502 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100503
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100504 # Don't load state if there is none ...
505 if not opts.batch_state:
506 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100507
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100508 if not os.path.isfile(opts.batch_state):
509 print "No state file yet"
510 return
511
512 # Get stored data
513 fh = open(opts.batch_state)
514 d = json.loads(fh.read())
515 fh.close()
516
517 for k,v in d.iteritems():
518 setattr(opts, k, v)
519
520
521def save_batch(opts):
522 # Need to do something ?
523 if not opts.batch_mode or not opts.batch_state:
524 return
525
526 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
527 fh = open(opts.batch_state, 'w')
528 fh.write(d)
529 fh.close()
530
531
532def card_detect(opts, scc):
Sylvain Munautbdca2522010-12-09 13:31:58 +0100533
Sylvain Munaut76504e02010-12-07 00:24:32 +0100534 # Detect type if needed
535 card = None
536 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
537
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100538 if opts.type in ("auto", "auto_once"):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100539 for kls in _cards_classes:
540 card = kls.autodetect(scc)
541 if card:
542 print "Autodetected card type %s" % card.name
543 card.reset()
544 break
545
546 if card is None:
547 print "Autodetection failed"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100548 return
549
550 if opts.type == "auto_once":
551 opts.type = card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100552
553 elif opts.type in ctypes:
554 card = ctypes[opts.type](scc)
555
556 else:
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100557 raise ValueError("Unknown card type %s" % opts.type)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100558
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100559 return card
Sylvain Munaut76504e02010-12-07 00:24:32 +0100560
Sylvain Munaut76504e02010-12-07 00:24:32 +0100561
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100562if __name__ == '__main__':
563
564 # Parse options
565 opts = parse_options()
566
567 # Connect to the card
568 if opts.pcsc_dev is None:
569 from pySim.transport.serial import SerialSimLink
570 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
571 else:
572 from pySim.transport.pcsc import PcscSimLink
573 sl = PcscSimLink(opts.pcsc_dev)
574
575 # Create command layer
576 scc = SimCardCommands(transport=sl)
577
578 # Batch mode init
579 init_batch(opts)
580
581 # Iterate
582 done = False
583 first = True
584 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100585
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100586 while not done:
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200587
588 if opts.dry_run is False:
589 # Connect transport
590 print "Insert card now (or CTRL-C to cancel)"
591 sl.wait_for_card(newcardonly=not first)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100592
593 # Not the first anymore !
594 first = False
595
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200596 if opts.dry_run is False:
597 # Get card
598 card = card_detect(opts, scc)
599 if card is None:
600 if opts.batch_mode:
601 first = False
602 continue
603 else:
604 sys.exit(-1)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100605
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200606 # Erase if requested
607 if opts.erase:
608 print "Formatting ..."
609 card.erase()
610 card.reset()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100611
612 # Generate parameters
Harald Welte7f62cec2012-08-13 20:07:41 +0200613 if opts.source == 'cmdline':
614 cp = gen_parameters(opts)
615 elif opts.source == 'csv':
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200616 if opts.read_imsi:
617 if opts.dry_run:
618 # Connect transport
619 print "Insert card now (or CTRL-C to cancel)"
620 sl.wait_for_card(newcardonly=not first)
Alexander Chemeris47c73ab2018-01-10 14:10:17 +0900621 (res,_) = scc.read_binary(EF['IMSI'])
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200622 imsi = swap_nibbles(res)[3:]
623 else:
624 imsi = opts.imsi
625 cp = read_params_csv(opts, imsi)
Harald Welte7f62cec2012-08-13 20:07:41 +0200626 if cp is None:
627 print "Error reading parameters\n"
628 sys.exit(2)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100629 print_parameters(cp)
630
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200631 if opts.dry_run is False:
632 # Program the card
633 print "Programming ..."
634 if opts.dry_run is not True:
635 card.program(cp)
636 else:
637 print "Dry Run: NOT PROGRAMMING!"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100638
639 # Write parameters permanently
640 write_parameters(opts, cp)
641
642 # Batch mode state update and save
Sylvain Munaut8d243e82010-12-23 20:27:48 +0100643 if opts.num is not None:
644 opts.num += 1
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100645 save_batch(opts)
646
647 # Done for this card and maybe for everything ?
648 print "Done !\n"
649
650 if not opts.batch_mode:
651 done = True