blob: 650d8eaa22dbad73a9286b3551288a670ced5acc [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 )
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",
119 )
Harald Welte93b38cd2012-03-22 14:31:36 +0100120
Sylvain Munaut76504e02010-12-07 00:24:32 +0100121
122 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
123 help="Secret used for ICCID/IMSI autogen",
124 )
125 parser.add_option("-j", "--num", dest="num", type=int,
126 help="Card # used for ICCID/IMSI autogen",
127 )
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100128 parser.add_option("--batch", dest="batch_mode",
129 help="Enable batch mode [default: %default]",
130 default=False, action='store_true',
131 )
132 parser.add_option("--batch-state", dest="batch_state", metavar="FILE",
133 help="Optional batch state file",
134 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100135
Harald Welte7f62cec2012-08-13 20:07:41 +0200136 # if mode is "csv"
137 parser.add_option("--read-csv", dest="read_csv", metavar="FILE",
138 help="Read parameters from CSV file rather than command line")
139
140
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100141 parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
142 help="Append generated parameters in CSV file",
143 )
144 parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
145 help="Append generated parameters to OpenBSC HLR sqlite3",
146 )
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200147 parser.add_option("--dry-run", dest="dry_run",
148 help="Perform a 'dry run', don't actually program the card",
149 default=False, action="store_true")
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100150
Sylvain Munaut76504e02010-12-07 00:24:32 +0100151 (options, args) = parser.parse_args()
152
153 if options.type == 'list':
154 for kls in _cards_classes:
155 print kls.name
156 sys.exit(0)
157
Harald Welte7f62cec2012-08-13 20:07:41 +0200158 if options.source == 'csv':
159 if (options.imsi is None) and (options.batch_mode is False):
160 parser.error("CSV mode needs either an IMSI or batch mode")
161 if options.read_csv is None:
162 parser.error("CSV mode requires a CSV input file")
163 elif options.source == 'cmdline':
164 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
165 parser.error("If either IMSI or ICCID isn't specified, num is required")
166 else:
167 parser.error("Only `cmdline' and `csv' sources supported")
168
169 if (options.read_csv is not None) and (options.source != 'csv'):
170 parser.error("You cannot specify a CSV input file in source != csv")
171
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100172 if (options.batch_mode) and (options.num is None):
173 options.num = 0
174
Sylvain Munaut98d2b852010-12-23 20:27:25 +0100175 if (options.batch_mode):
176 if (options.imsi is not None) or (options.iccid is not None):
177 parser.error("Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more informations")
178
Sylvain Munaut76504e02010-12-07 00:24:32 +0100179 if args:
180 parser.error("Extraneous arguments")
181
182 return options
183
184
185def _digits(secret, usage, len, num):
186 s = hashlib.sha1(secret + usage + '%d' % num)
187 d = ''.join(['%02d'%ord(x) for x in s.digest()])
188 return d[0:len]
189
190def _mcc_mnc_digits(mcc, mnc):
191 return ('%03d%03d' if mnc > 100 else '%03d%02d') % (mcc, mnc)
192
193def _cc_digits(cc):
194 return ('%03d' if cc > 100 else '%02d') % cc
195
196def _isnum(s, l=-1):
197 return s.isdigit() and ((l== -1) or (len(s) == l))
198
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100199def _ishex(s, l=-1):
200 hc = '0123456789abcdef'
201 return all([x in hc for x in s.lower()]) and ((l== -1) or (len(s) == l))
202
Sylvain Munaut76504e02010-12-07 00:24:32 +0100203
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100204def _dbi_binary_quote(s):
205 # Count usage of each char
206 cnt = {}
207 for c in s:
208 cnt[c] = cnt.get(c, 0) + 1
209
210 # Find best offset
211 e = 0
212 m = len(s)
213 for i in range(1, 256):
214 if i == 39:
215 continue
216 sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
217 if sum_ < m:
218 m = sum_
219 e = i
220 if m == 0: # No overhead ? use this !
221 break;
Sylvain Munaut1a914432011-12-08 20:08:26 +0100222
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100223 # Generate output
224 out = []
225 out.append( chr(e) ) # Offset
226 for c in s:
227 x = (256 + ord(c) - e) % 256
228 if x in (0, 1, 39):
229 out.append('\x01')
230 out.append(chr(x+1))
231 else:
232 out.append(chr(x))
233
234 return ''.join(out)
235
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100236def calculate_luhn(cc):
237 num = map(int, str(cc))
238 check_digit = 10 - sum(num[-2::-2] + [sum(divmod(d * 2, 10)) for d in num[::-2]]) % 10
239 return 0 if check_digit == 10 else check_digit
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100240
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100241def derive_milenage_opc(ki_hex, op_hex):
242 """
243 Run the milenage algorithm.
244 """
245 from Crypto.Cipher import AES
246 from Crypto.Util.strxor import strxor
247 from pySim.utils import b2h
248
249 # We pass in hex string and now need to work on bytes
250 aes = AES.new(h2b(ki_hex))
251 opc_bytes = aes.encrypt(h2b(op_hex))
252 return b2h(strxor(opc_bytes, h2b(op_hex)))
253
Sylvain Munaut76504e02010-12-07 00:24:32 +0100254def gen_parameters(opts):
Jan Balkec3ebd332015-01-26 12:22:55 +0100255 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki, PIN-ADM from the
Sylvain Munaut76504e02010-12-07 00:24:32 +0100256 options given by the user"""
257
258 # MCC/MNC
259 mcc = opts.mcc
260 mnc = opts.mnc
261
262 if not ((0 < mcc < 999) and (0 < mnc < 999)):
263 raise ValueError('mcc & mnc must be between 0 and 999')
264
265 # Digitize country code (2 or 3 digits)
266 cc_digits = _cc_digits(opts.country)
267
268 # Digitize MCC/MNC (5 or 6 digits)
269 plmn_digits = _mcc_mnc_digits(mcc, mnc)
270
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100271 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
Sylvain Munaut76504e02010-12-07 00:24:32 +0100272 if opts.iccid is not None:
273 iccid = opts.iccid
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100274 if not _isnum(iccid, 19):
275 raise ValueError('ICCID must be 19 digits !');
Sylvain Munaut76504e02010-12-07 00:24:32 +0100276
277 else:
278 if opts.num is None:
279 raise ValueError('Neither ICCID nor card number specified !')
280
281 iccid = (
282 '89' + # Common prefix (telecom)
283 cc_digits + # Country Code on 2/3 digits
284 plmn_digits # MCC/MNC on 5/6 digits
285 )
286
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100287 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100288
289 if opts.secret is None:
290 # The raw number
291 iccid += ('%%0%dd' % ml) % opts.num
292 else:
293 # Randomized digits
294 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
295
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100296 # Add checksum digit
297 iccid += ('%1d' % calculate_luhn(iccid))
298
Sylvain Munaut76504e02010-12-07 00:24:32 +0100299 # IMSI (15 digits usually)
300 if opts.imsi is not None:
301 imsi = opts.imsi
302 if not _isnum(imsi):
303 raise ValueError('IMSI must be digits only !')
304
305 else:
306 if opts.num is None:
307 raise ValueError('Neither IMSI nor card number specified !')
308
309 ml = 15 - len(plmn_digits)
310
311 if opts.secret is None:
312 # The raw number
313 msin = ('%%0%dd' % ml) % opts.num
314 else:
315 # Randomized digits
316 msin = _digits(opts.secret, 'imsi', ml, opts.num)
317
318 imsi = (
319 plmn_digits + # MCC/MNC on 5/6 digits
320 msin # MSIN
321 )
322
323 # SMSP
324 if opts.smsp is not None:
325 smsp = opts.smsp
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100326 if not _ishex(smsp):
327 raise ValueError('SMSP must be hex digits only !')
328 if len(smsp) < 28*2:
329 raise ValueError('SMSP must be at least 28 bytes')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100330
331 else:
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100332 if opts.smsc is not None:
333 smsc = opts.smsc
334 if not _isnum(smsc):
335 raise ValueError('SMSC must be digits only !')
336 else:
337 smsc = '00%d' % opts.country + '5555' # Hack ...
338
Sylvain Munaut9977c862011-12-10 09:57:16 +0100339 smsc = '%02d' % ((len(smsc) + 3)//2,) + "81" + swap_nibbles(rpad(smsc, 20))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100340
341 smsp = (
342 'e1' + # Parameters indicator
343 'ff' * 12 + # TP-Destination address
344 smsc + # TP-Service Centre Address
345 '00' + # TP-Protocol identifier
346 '00' + # TP-Data coding scheme
347 '00' # TP-Validity period
348 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100349
Alexander Chemeris21885242013-07-02 16:56:55 +0400350 # ACC
351 if opts.acc is not None:
352 acc = opts.acc
353 if not _ishex(acc):
354 raise ValueError('ACC must be hex digits only !')
355 if len(acc) != 2*2:
356 raise ValueError('ACC must be exactly 2 bytes')
357
358 else:
359 acc = None
360
Sylvain Munaut76504e02010-12-07 00:24:32 +0100361 # Ki (random)
362 if opts.ki is not None:
363 ki = opts.ki
364 if not re.match('^[0-9a-fA-F]{32}$', ki):
365 raise ValueError('Ki needs to be 128 bits, in hex format')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100366 else:
367 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
368
Harald Welte93b38cd2012-03-22 14:31:36 +0100369 # Ki (random)
370 if opts.opc is not None:
371 opc = opts.opc
372 if not re.match('^[0-9a-fA-F]{32}$', opc):
373 raise ValueError('OPC needs to be 128 bits, in hex format')
374
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100375 elif opts.op is not None:
376 opc = derive_milenage_opc(ki, opts.op)
Harald Welte93b38cd2012-03-22 14:31:36 +0100377 else:
378 opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
379
Jan Balkec3ebd332015-01-26 12:22:55 +0100380 if opts.pin_adm is not None:
381 if len(opts.pin_adm) > 8:
382 raise ValueError("PIN-ADM needs to be <=8 digits")
383 pin_adm = ''.join(['%02x'%(ord(x)) for x in opts.pin_adm])
384 pin_adm = rpad(pin_adm, 16)
385 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:
435 if opts.num is not None:
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':
616 cp = read_params_csv(opts, opts.imsi)
617 if cp is None:
618 print "Error reading parameters\n"
619 sys.exit(2)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100620 print_parameters(cp)
621
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200622 if opts.dry_run is False:
623 # Program the card
624 print "Programming ..."
625 if opts.dry_run is not True:
626 card.program(cp)
627 else:
628 print "Dry Run: NOT PROGRAMMING!"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100629
630 # Write parameters permanently
631 write_parameters(opts, cp)
632
633 # Batch mode state update and save
Sylvain Munaut8d243e82010-12-23 20:27:48 +0100634 if opts.num is not None:
635 opts.num += 1
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100636 save_batch(opts)
637
638 # Done for this card and maybe for everything ?
639 print "Done !\n"
640
641 if not opts.batch_mode:
642 done = True
Sylvain Munaut76504e02010-12-07 00:24:32 +0100643