blob: ab18b1259338d6b8cbb159ff2de1fb982eb738e8 [file] [log] [blame]
Sylvain Munaut76504e02010-12-07 00:24:32 +01001#!/usr/bin/env python
2
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 )
65 parser.add_option("-e", "--erase", dest="erase", action='store_true',
66 help="Erase beforehand [default: %default]",
67 default=False,
68 )
69
Harald Welte7f62cec2012-08-13 20:07:41 +020070 parser.add_option("-S", "--source", dest="source",
71 help="Data Source[default: %default]",
72 default="cmdline",
73 )
74
75 # if mode is "cmdline"
Sylvain Munaut76504e02010-12-07 00:24:32 +010076 parser.add_option("-n", "--name", dest="name",
77 help="Operator name [default: %default]",
78 default="Magic",
79 )
80 parser.add_option("-c", "--country", dest="country", type="int", metavar="CC",
81 help="Country code [default: %default]",
82 default=1,
83 )
84 parser.add_option("-x", "--mcc", dest="mcc", type="int",
85 help="Mobile Country Code [default: %default]",
86 default=901,
87 )
88 parser.add_option("-y", "--mnc", dest="mnc", type="int",
Sylvain Munaut17716032010-12-08 22:33:51 +010089 help="Mobile Network Code [default: %default]",
Sylvain Munaut76504e02010-12-07 00:24:32 +010090 default=55,
91 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +010092 parser.add_option("-m", "--smsc", dest="smsc",
Sylvain Munaut76504e02010-12-07 00:24:32 +010093 help="SMSP [default: '00 + country code + 5555']",
94 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +010095 parser.add_option("-M", "--smsp", dest="smsp",
96 help="Raw SMSP content in hex [default: auto from SMSC]",
97 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010098
99 parser.add_option("-s", "--iccid", dest="iccid", metavar="ID",
100 help="Integrated Circuit Card ID",
101 )
102 parser.add_option("-i", "--imsi", dest="imsi",
103 help="International Mobile Subscriber Identity",
104 )
105 parser.add_option("-k", "--ki", dest="ki",
106 help="Ki (default is to randomize)",
107 )
Harald Welte93b38cd2012-03-22 14:31:36 +0100108 parser.add_option("-o", "--opc", dest="opc",
109 help="OPC (default is to randomize)",
110 )
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100111 parser.add_option("--op", dest="op",
112 help="Set OP to derive OPC from OP and KI",
113 )
Alexander Chemeris21885242013-07-02 16:56:55 +0400114 parser.add_option("--acc", dest="acc",
115 help="Set ACC bits (Access Control Code). not all card types are supported",
116 )
Harald Welte93b38cd2012-03-22 14:31:36 +0100117
Sylvain Munaut76504e02010-12-07 00:24:32 +0100118
119 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
120 help="Secret used for ICCID/IMSI autogen",
121 )
122 parser.add_option("-j", "--num", dest="num", type=int,
123 help="Card # used for ICCID/IMSI autogen",
124 )
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100125 parser.add_option("--batch", dest="batch_mode",
126 help="Enable batch mode [default: %default]",
127 default=False, action='store_true',
128 )
129 parser.add_option("--batch-state", dest="batch_state", metavar="FILE",
130 help="Optional batch state file",
131 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100132
Harald Welte7f62cec2012-08-13 20:07:41 +0200133 # if mode is "csv"
134 parser.add_option("--read-csv", dest="read_csv", metavar="FILE",
135 help="Read parameters from CSV file rather than command line")
136
137
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100138 parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
139 help="Append generated parameters in CSV file",
140 )
141 parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
142 help="Append generated parameters to OpenBSC HLR sqlite3",
143 )
144
Sylvain Munaut76504e02010-12-07 00:24:32 +0100145 (options, args) = parser.parse_args()
146
147 if options.type == 'list':
148 for kls in _cards_classes:
149 print kls.name
150 sys.exit(0)
151
Harald Welte7f62cec2012-08-13 20:07:41 +0200152 if options.source == 'csv':
153 if (options.imsi is None) and (options.batch_mode is False):
154 parser.error("CSV mode needs either an IMSI or batch mode")
155 if options.read_csv is None:
156 parser.error("CSV mode requires a CSV input file")
157 elif options.source == 'cmdline':
158 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
159 parser.error("If either IMSI or ICCID isn't specified, num is required")
160 else:
161 parser.error("Only `cmdline' and `csv' sources supported")
162
163 if (options.read_csv is not None) and (options.source != 'csv'):
164 parser.error("You cannot specify a CSV input file in source != csv")
165
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100166 if (options.batch_mode) and (options.num is None):
167 options.num = 0
168
Sylvain Munaut98d2b852010-12-23 20:27:25 +0100169 if (options.batch_mode):
170 if (options.imsi is not None) or (options.iccid is not None):
171 parser.error("Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more informations")
172
Sylvain Munaut76504e02010-12-07 00:24:32 +0100173 if args:
174 parser.error("Extraneous arguments")
175
176 return options
177
178
179def _digits(secret, usage, len, num):
180 s = hashlib.sha1(secret + usage + '%d' % num)
181 d = ''.join(['%02d'%ord(x) for x in s.digest()])
182 return d[0:len]
183
184def _mcc_mnc_digits(mcc, mnc):
185 return ('%03d%03d' if mnc > 100 else '%03d%02d') % (mcc, mnc)
186
187def _cc_digits(cc):
188 return ('%03d' if cc > 100 else '%02d') % cc
189
190def _isnum(s, l=-1):
191 return s.isdigit() and ((l== -1) or (len(s) == l))
192
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100193def _ishex(s, l=-1):
194 hc = '0123456789abcdef'
195 return all([x in hc for x in s.lower()]) and ((l== -1) or (len(s) == l))
196
Sylvain Munaut76504e02010-12-07 00:24:32 +0100197
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100198def _dbi_binary_quote(s):
199 # Count usage of each char
200 cnt = {}
201 for c in s:
202 cnt[c] = cnt.get(c, 0) + 1
203
204 # Find best offset
205 e = 0
206 m = len(s)
207 for i in range(1, 256):
208 if i == 39:
209 continue
210 sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
211 if sum_ < m:
212 m = sum_
213 e = i
214 if m == 0: # No overhead ? use this !
215 break;
Sylvain Munaut1a914432011-12-08 20:08:26 +0100216
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100217 # Generate output
218 out = []
219 out.append( chr(e) ) # Offset
220 for c in s:
221 x = (256 + ord(c) - e) % 256
222 if x in (0, 1, 39):
223 out.append('\x01')
224 out.append(chr(x+1))
225 else:
226 out.append(chr(x))
227
228 return ''.join(out)
229
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100230def calculate_luhn(cc):
231 num = map(int, str(cc))
232 check_digit = 10 - sum(num[-2::-2] + [sum(divmod(d * 2, 10)) for d in num[::-2]]) % 10
233 return 0 if check_digit == 10 else check_digit
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100234
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100235def derive_milenage_opc(ki_hex, op_hex):
236 """
237 Run the milenage algorithm.
238 """
239 from Crypto.Cipher import AES
240 from Crypto.Util.strxor import strxor
241 from pySim.utils import b2h
242
243 # We pass in hex string and now need to work on bytes
244 aes = AES.new(h2b(ki_hex))
245 opc_bytes = aes.encrypt(h2b(op_hex))
246 return b2h(strxor(opc_bytes, h2b(op_hex)))
247
Sylvain Munaut76504e02010-12-07 00:24:32 +0100248def gen_parameters(opts):
249 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki from the
250 options given by the user"""
251
252 # MCC/MNC
253 mcc = opts.mcc
254 mnc = opts.mnc
255
256 if not ((0 < mcc < 999) and (0 < mnc < 999)):
257 raise ValueError('mcc & mnc must be between 0 and 999')
258
259 # Digitize country code (2 or 3 digits)
260 cc_digits = _cc_digits(opts.country)
261
262 # Digitize MCC/MNC (5 or 6 digits)
263 plmn_digits = _mcc_mnc_digits(mcc, mnc)
264
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100265 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
Sylvain Munaut76504e02010-12-07 00:24:32 +0100266 if opts.iccid is not None:
267 iccid = opts.iccid
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100268 if not _isnum(iccid, 19):
269 raise ValueError('ICCID must be 19 digits !');
Sylvain Munaut76504e02010-12-07 00:24:32 +0100270
271 else:
272 if opts.num is None:
273 raise ValueError('Neither ICCID nor card number specified !')
274
275 iccid = (
276 '89' + # Common prefix (telecom)
277 cc_digits + # Country Code on 2/3 digits
278 plmn_digits # MCC/MNC on 5/6 digits
279 )
280
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100281 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100282
283 if opts.secret is None:
284 # The raw number
285 iccid += ('%%0%dd' % ml) % opts.num
286 else:
287 # Randomized digits
288 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
289
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100290 # Add checksum digit
291 iccid += ('%1d' % calculate_luhn(iccid))
292
Sylvain Munaut76504e02010-12-07 00:24:32 +0100293 # IMSI (15 digits usually)
294 if opts.imsi is not None:
295 imsi = opts.imsi
296 if not _isnum(imsi):
297 raise ValueError('IMSI must be digits only !')
298
299 else:
300 if opts.num is None:
301 raise ValueError('Neither IMSI nor card number specified !')
302
303 ml = 15 - len(plmn_digits)
304
305 if opts.secret is None:
306 # The raw number
307 msin = ('%%0%dd' % ml) % opts.num
308 else:
309 # Randomized digits
310 msin = _digits(opts.secret, 'imsi', ml, opts.num)
311
312 imsi = (
313 plmn_digits + # MCC/MNC on 5/6 digits
314 msin # MSIN
315 )
316
317 # SMSP
318 if opts.smsp is not None:
319 smsp = opts.smsp
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100320 if not _ishex(smsp):
321 raise ValueError('SMSP must be hex digits only !')
322 if len(smsp) < 28*2:
323 raise ValueError('SMSP must be at least 28 bytes')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100324
325 else:
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100326 if opts.smsc is not None:
327 smsc = opts.smsc
328 if not _isnum(smsc):
329 raise ValueError('SMSC must be digits only !')
330 else:
331 smsc = '00%d' % opts.country + '5555' # Hack ...
332
Sylvain Munaut9977c862011-12-10 09:57:16 +0100333 smsc = '%02d' % ((len(smsc) + 3)//2,) + "81" + swap_nibbles(rpad(smsc, 20))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100334
335 smsp = (
336 'e1' + # Parameters indicator
337 'ff' * 12 + # TP-Destination address
338 smsc + # TP-Service Centre Address
339 '00' + # TP-Protocol identifier
340 '00' + # TP-Data coding scheme
341 '00' # TP-Validity period
342 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100343
Alexander Chemeris21885242013-07-02 16:56:55 +0400344 # ACC
345 if opts.acc is not None:
346 acc = opts.acc
347 if not _ishex(acc):
348 raise ValueError('ACC must be hex digits only !')
349 if len(acc) != 2*2:
350 raise ValueError('ACC must be exactly 2 bytes')
351
352 else:
353 acc = None
354
Sylvain Munaut76504e02010-12-07 00:24:32 +0100355 # Ki (random)
356 if opts.ki is not None:
357 ki = opts.ki
358 if not re.match('^[0-9a-fA-F]{32}$', ki):
359 raise ValueError('Ki needs to be 128 bits, in hex format')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100360 else:
361 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
362
Harald Welte93b38cd2012-03-22 14:31:36 +0100363 # Ki (random)
364 if opts.opc is not None:
365 opc = opts.opc
366 if not re.match('^[0-9a-fA-F]{32}$', opc):
367 raise ValueError('OPC needs to be 128 bits, in hex format')
368
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100369 elif opts.op is not None:
370 opc = derive_milenage_opc(ki, opts.op)
Harald Welte93b38cd2012-03-22 14:31:36 +0100371 else:
372 opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
373
374
Sylvain Munaut76504e02010-12-07 00:24:32 +0100375 # Return that
376 return {
377 'name' : opts.name,
378 'iccid' : iccid,
379 'mcc' : mcc,
380 'mnc' : mnc,
381 'imsi' : imsi,
382 'smsp' : smsp,
383 'ki' : ki,
Harald Welte93b38cd2012-03-22 14:31:36 +0100384 'opc' : opc,
Alexander Chemeris21885242013-07-02 16:56:55 +0400385 'acc' : acc,
Sylvain Munaut76504e02010-12-07 00:24:32 +0100386 }
387
388
389def print_parameters(params):
390
391 print """Generated card parameters :
392 > Name : %(name)s
393 > SMSP : %(smsp)s
394 > ICCID : %(iccid)s
395 > MCC/MNC : %(mcc)d/%(mnc)d
396 > IMSI : %(imsi)s
397 > Ki : %(ki)s
Harald Welte93b38cd2012-03-22 14:31:36 +0100398 > OPC : %(opc)s
Alexander Chemeris21885242013-07-02 16:56:55 +0400399 > ACC : %(acc)s
Sylvain Munaut76504e02010-12-07 00:24:32 +0100400""" % params
401
402
Harald Welte130524b2012-08-13 15:53:43 +0200403def write_params_csv(opts, params):
404 # csv
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100405 if opts.write_csv:
406 import csv
Harald Welte93b38cd2012-03-22 14:31:36 +0100407 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100408 f = open(opts.write_csv, 'a')
409 cw = csv.writer(f)
410 cw.writerow([params[x] for x in row])
411 f.close()
412
Harald Welte7f62cec2012-08-13 20:07:41 +0200413def read_params_csv(opts, imsi):
414 import csv
415 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
416 f = open(opts.read_csv, 'r')
417 cr = csv.DictReader(f, row)
418 i = 0
419 for row in cr:
420 if opts.num is not None:
421 i += 1
422 if opts.num == i:
423 break
424 if row['imsi'] == imsi:
425 break
426
427 if row:
428 row['mcc'] = int(row['mcc'])
429 row['mnc'] = int(row['mnc'])
430
431 f.close()
432 return row
433
Harald Welte130524b2012-08-13 15:53:43 +0200434def write_params_hlr(opts, params):
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100435 # SQLite3 OpenBSC HLR
436 if opts.write_hlr:
437 import sqlite3
438 conn = sqlite3.connect(opts.write_hlr)
439
440 c = conn.execute(
441 'INSERT INTO Subscriber ' +
442 '(imsi, name, extension, authorized, created, updated) ' +
443 'VALUES ' +
444 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
445 [
446 params['imsi'],
447 params['name'],
448 '9' + params['iccid'][-5:]
449 ],
450 )
451 sub_id = c.lastrowid
452 c.close()
453
454 c = conn.execute(
455 'INSERT INTO AuthKeys ' +
456 '(subscriber_id, algorithm_id, a3a8_ki)' +
457 'VALUES ' +
458 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100459 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100460 )
461
462 conn.commit()
463 conn.close()
464
Harald Welte130524b2012-08-13 15:53:43 +0200465def write_parameters(opts, params):
466 write_params_csv(opts, params)
Harald Welte7f62cec2012-08-13 20:07:41 +0200467 write_params_hlr(opts, params)
Harald Welte130524b2012-08-13 15:53:43 +0200468
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100469
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100470BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
471BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100472
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100473def init_batch(opts):
474 # Need to do something ?
475 if not opts.batch_mode:
476 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100477
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100478 for k in BATCH_INCOMPATIBLE:
479 if getattr(opts, k):
480 print "Incompatible option with batch_state: %s" % (k,)
481 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100482
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100483 # Don't load state if there is none ...
484 if not opts.batch_state:
485 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100486
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100487 if not os.path.isfile(opts.batch_state):
488 print "No state file yet"
489 return
490
491 # Get stored data
492 fh = open(opts.batch_state)
493 d = json.loads(fh.read())
494 fh.close()
495
496 for k,v in d.iteritems():
497 setattr(opts, k, v)
498
499
500def save_batch(opts):
501 # Need to do something ?
502 if not opts.batch_mode or not opts.batch_state:
503 return
504
505 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
506 fh = open(opts.batch_state, 'w')
507 fh.write(d)
508 fh.close()
509
510
511def card_detect(opts, scc):
Sylvain Munautbdca2522010-12-09 13:31:58 +0100512
Sylvain Munaut76504e02010-12-07 00:24:32 +0100513 # Detect type if needed
514 card = None
515 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
516
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100517 if opts.type in ("auto", "auto_once"):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100518 for kls in _cards_classes:
519 card = kls.autodetect(scc)
520 if card:
521 print "Autodetected card type %s" % card.name
522 card.reset()
523 break
524
525 if card is None:
526 print "Autodetection failed"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100527 return
528
529 if opts.type == "auto_once":
530 opts.type = card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100531
532 elif opts.type in ctypes:
533 card = ctypes[opts.type](scc)
534
535 else:
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100536 raise ValueError("Unknown card type %s" % opts.type)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100537
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100538 return card
Sylvain Munaut76504e02010-12-07 00:24:32 +0100539
Sylvain Munaut76504e02010-12-07 00:24:32 +0100540
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100541if __name__ == '__main__':
542
543 # Parse options
544 opts = parse_options()
545
546 # Connect to the card
547 if opts.pcsc_dev is None:
548 from pySim.transport.serial import SerialSimLink
549 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
550 else:
551 from pySim.transport.pcsc import PcscSimLink
552 sl = PcscSimLink(opts.pcsc_dev)
553
554 # Create command layer
555 scc = SimCardCommands(transport=sl)
556
557 # Batch mode init
558 init_batch(opts)
559
560 # Iterate
561 done = False
562 first = True
563 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100564
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100565 while not done:
566 # Connect transport
567 print "Insert card now (or CTRL-C to cancel)"
568 sl.wait_for_card(newcardonly=not first)
569
570 # Not the first anymore !
571 first = False
572
573 # Get card
574 card = card_detect(opts, scc)
575 if card is None:
576 if opts.batch_mode:
577 first = False
578 continue
579 else:
580 sys.exit(-1)
581
582 # Erase if requested
583 if opts.erase:
584 print "Formatting ..."
585 card.erase()
586 card.reset()
587
588 # Generate parameters
Harald Welte7f62cec2012-08-13 20:07:41 +0200589 if opts.source == 'cmdline':
590 cp = gen_parameters(opts)
591 elif opts.source == 'csv':
592 cp = read_params_csv(opts, opts.imsi)
593 if cp is None:
594 print "Error reading parameters\n"
595 sys.exit(2)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100596 print_parameters(cp)
597
598 # Program the card
599 print "Programming ..."
600 card.program(cp)
601
602 # Write parameters permanently
603 write_parameters(opts, cp)
604
605 # Batch mode state update and save
Sylvain Munaut8d243e82010-12-23 20:27:48 +0100606 if opts.num is not None:
607 opts.num += 1
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100608 save_batch(opts)
609
610 # Done for this card and maybe for everything ?
611 print "Done !\n"
612
613 if not opts.batch_mode:
614 done = True
Sylvain Munaut76504e02010-12-07 00:24:32 +0100615