blob: 5e5f0639febaddeae7198099ee6d0b8bc2c8fea6 [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 )
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200144 parser.add_option("--dry-run", dest="dry_run",
145 help="Perform a 'dry run', don't actually program the card",
146 default=False, action="store_true")
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100147
Sylvain Munaut76504e02010-12-07 00:24:32 +0100148 (options, args) = parser.parse_args()
149
150 if options.type == 'list':
151 for kls in _cards_classes:
152 print kls.name
153 sys.exit(0)
154
Harald Welte7f62cec2012-08-13 20:07:41 +0200155 if options.source == 'csv':
156 if (options.imsi is None) and (options.batch_mode is False):
157 parser.error("CSV mode needs either an IMSI or batch mode")
158 if options.read_csv is None:
159 parser.error("CSV mode requires a CSV input file")
160 elif options.source == 'cmdline':
161 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
162 parser.error("If either IMSI or ICCID isn't specified, num is required")
163 else:
164 parser.error("Only `cmdline' and `csv' sources supported")
165
166 if (options.read_csv is not None) and (options.source != 'csv'):
167 parser.error("You cannot specify a CSV input file in source != csv")
168
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100169 if (options.batch_mode) and (options.num is None):
170 options.num = 0
171
Sylvain Munaut98d2b852010-12-23 20:27:25 +0100172 if (options.batch_mode):
173 if (options.imsi is not None) or (options.iccid is not None):
174 parser.error("Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more informations")
175
Sylvain Munaut76504e02010-12-07 00:24:32 +0100176 if args:
177 parser.error("Extraneous arguments")
178
179 return options
180
181
182def _digits(secret, usage, len, num):
183 s = hashlib.sha1(secret + usage + '%d' % num)
184 d = ''.join(['%02d'%ord(x) for x in s.digest()])
185 return d[0:len]
186
187def _mcc_mnc_digits(mcc, mnc):
188 return ('%03d%03d' if mnc > 100 else '%03d%02d') % (mcc, mnc)
189
190def _cc_digits(cc):
191 return ('%03d' if cc > 100 else '%02d') % cc
192
193def _isnum(s, l=-1):
194 return s.isdigit() and ((l== -1) or (len(s) == l))
195
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100196def _ishex(s, l=-1):
197 hc = '0123456789abcdef'
198 return all([x in hc for x in s.lower()]) and ((l== -1) or (len(s) == l))
199
Sylvain Munaut76504e02010-12-07 00:24:32 +0100200
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100201def _dbi_binary_quote(s):
202 # Count usage of each char
203 cnt = {}
204 for c in s:
205 cnt[c] = cnt.get(c, 0) + 1
206
207 # Find best offset
208 e = 0
209 m = len(s)
210 for i in range(1, 256):
211 if i == 39:
212 continue
213 sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
214 if sum_ < m:
215 m = sum_
216 e = i
217 if m == 0: # No overhead ? use this !
218 break;
Sylvain Munaut1a914432011-12-08 20:08:26 +0100219
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100220 # Generate output
221 out = []
222 out.append( chr(e) ) # Offset
223 for c in s:
224 x = (256 + ord(c) - e) % 256
225 if x in (0, 1, 39):
226 out.append('\x01')
227 out.append(chr(x+1))
228 else:
229 out.append(chr(x))
230
231 return ''.join(out)
232
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100233def calculate_luhn(cc):
234 num = map(int, str(cc))
235 check_digit = 10 - sum(num[-2::-2] + [sum(divmod(d * 2, 10)) for d in num[::-2]]) % 10
236 return 0 if check_digit == 10 else check_digit
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100237
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100238def derive_milenage_opc(ki_hex, op_hex):
239 """
240 Run the milenage algorithm.
241 """
242 from Crypto.Cipher import AES
243 from Crypto.Util.strxor import strxor
244 from pySim.utils import b2h
245
246 # We pass in hex string and now need to work on bytes
247 aes = AES.new(h2b(ki_hex))
248 opc_bytes = aes.encrypt(h2b(op_hex))
249 return b2h(strxor(opc_bytes, h2b(op_hex)))
250
Sylvain Munaut76504e02010-12-07 00:24:32 +0100251def gen_parameters(opts):
252 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki from the
253 options given by the user"""
254
255 # MCC/MNC
256 mcc = opts.mcc
257 mnc = opts.mnc
258
259 if not ((0 < mcc < 999) and (0 < mnc < 999)):
260 raise ValueError('mcc & mnc must be between 0 and 999')
261
262 # Digitize country code (2 or 3 digits)
263 cc_digits = _cc_digits(opts.country)
264
265 # Digitize MCC/MNC (5 or 6 digits)
266 plmn_digits = _mcc_mnc_digits(mcc, mnc)
267
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100268 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
Sylvain Munaut76504e02010-12-07 00:24:32 +0100269 if opts.iccid is not None:
270 iccid = opts.iccid
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100271 if not _isnum(iccid, 19):
272 raise ValueError('ICCID must be 19 digits !');
Sylvain Munaut76504e02010-12-07 00:24:32 +0100273
274 else:
275 if opts.num is None:
276 raise ValueError('Neither ICCID nor card number specified !')
277
278 iccid = (
279 '89' + # Common prefix (telecom)
280 cc_digits + # Country Code on 2/3 digits
281 plmn_digits # MCC/MNC on 5/6 digits
282 )
283
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100284 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100285
286 if opts.secret is None:
287 # The raw number
288 iccid += ('%%0%dd' % ml) % opts.num
289 else:
290 # Randomized digits
291 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
292
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100293 # Add checksum digit
294 iccid += ('%1d' % calculate_luhn(iccid))
295
Sylvain Munaut76504e02010-12-07 00:24:32 +0100296 # IMSI (15 digits usually)
297 if opts.imsi is not None:
298 imsi = opts.imsi
299 if not _isnum(imsi):
300 raise ValueError('IMSI must be digits only !')
301
302 else:
303 if opts.num is None:
304 raise ValueError('Neither IMSI nor card number specified !')
305
306 ml = 15 - len(plmn_digits)
307
308 if opts.secret is None:
309 # The raw number
310 msin = ('%%0%dd' % ml) % opts.num
311 else:
312 # Randomized digits
313 msin = _digits(opts.secret, 'imsi', ml, opts.num)
314
315 imsi = (
316 plmn_digits + # MCC/MNC on 5/6 digits
317 msin # MSIN
318 )
319
320 # SMSP
321 if opts.smsp is not None:
322 smsp = opts.smsp
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100323 if not _ishex(smsp):
324 raise ValueError('SMSP must be hex digits only !')
325 if len(smsp) < 28*2:
326 raise ValueError('SMSP must be at least 28 bytes')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100327
328 else:
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100329 if opts.smsc is not None:
330 smsc = opts.smsc
331 if not _isnum(smsc):
332 raise ValueError('SMSC must be digits only !')
333 else:
334 smsc = '00%d' % opts.country + '5555' # Hack ...
335
Sylvain Munaut9977c862011-12-10 09:57:16 +0100336 smsc = '%02d' % ((len(smsc) + 3)//2,) + "81" + swap_nibbles(rpad(smsc, 20))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100337
338 smsp = (
339 'e1' + # Parameters indicator
340 'ff' * 12 + # TP-Destination address
341 smsc + # TP-Service Centre Address
342 '00' + # TP-Protocol identifier
343 '00' + # TP-Data coding scheme
344 '00' # TP-Validity period
345 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100346
Alexander Chemeris21885242013-07-02 16:56:55 +0400347 # ACC
348 if opts.acc is not None:
349 acc = opts.acc
350 if not _ishex(acc):
351 raise ValueError('ACC must be hex digits only !')
352 if len(acc) != 2*2:
353 raise ValueError('ACC must be exactly 2 bytes')
354
355 else:
356 acc = None
357
Sylvain Munaut76504e02010-12-07 00:24:32 +0100358 # Ki (random)
359 if opts.ki is not None:
360 ki = opts.ki
361 if not re.match('^[0-9a-fA-F]{32}$', ki):
362 raise ValueError('Ki needs to be 128 bits, in hex format')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100363 else:
364 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
365
Harald Welte93b38cd2012-03-22 14:31:36 +0100366 # Ki (random)
367 if opts.opc is not None:
368 opc = opts.opc
369 if not re.match('^[0-9a-fA-F]{32}$', opc):
370 raise ValueError('OPC needs to be 128 bits, in hex format')
371
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100372 elif opts.op is not None:
373 opc = derive_milenage_opc(ki, opts.op)
Harald Welte93b38cd2012-03-22 14:31:36 +0100374 else:
375 opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
376
377
Sylvain Munaut76504e02010-12-07 00:24:32 +0100378 # Return that
379 return {
380 'name' : opts.name,
381 'iccid' : iccid,
382 'mcc' : mcc,
383 'mnc' : mnc,
384 'imsi' : imsi,
385 'smsp' : smsp,
386 'ki' : ki,
Harald Welte93b38cd2012-03-22 14:31:36 +0100387 'opc' : opc,
Alexander Chemeris21885242013-07-02 16:56:55 +0400388 'acc' : acc,
Sylvain Munaut76504e02010-12-07 00:24:32 +0100389 }
390
391
392def print_parameters(params):
393
394 print """Generated card parameters :
395 > Name : %(name)s
396 > SMSP : %(smsp)s
397 > ICCID : %(iccid)s
398 > MCC/MNC : %(mcc)d/%(mnc)d
399 > IMSI : %(imsi)s
400 > Ki : %(ki)s
Harald Welte93b38cd2012-03-22 14:31:36 +0100401 > OPC : %(opc)s
Alexander Chemeris21885242013-07-02 16:56:55 +0400402 > ACC : %(acc)s
Sylvain Munaut76504e02010-12-07 00:24:32 +0100403""" % params
404
405
Harald Welte130524b2012-08-13 15:53:43 +0200406def write_params_csv(opts, params):
407 # csv
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100408 if opts.write_csv:
409 import csv
Harald Welte93b38cd2012-03-22 14:31:36 +0100410 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100411 f = open(opts.write_csv, 'a')
412 cw = csv.writer(f)
413 cw.writerow([params[x] for x in row])
414 f.close()
415
Harald Weltec26b8292012-08-15 15:25:51 +0200416def _read_params_csv(opts, imsi):
Harald Welte7f62cec2012-08-13 20:07:41 +0200417 import csv
418 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
419 f = open(opts.read_csv, 'r')
420 cr = csv.DictReader(f, row)
421 i = 0
422 for row in cr:
423 if opts.num is not None:
Harald Welte7f62cec2012-08-13 20:07:41 +0200424 if opts.num == i:
Harald Weltec26b8292012-08-15 15:25:51 +0200425 f.close()
426 return row;
427 i += 1
Harald Welte7f62cec2012-08-13 20:07:41 +0200428 if row['imsi'] == imsi:
Harald Weltec26b8292012-08-15 15:25:51 +0200429 f.close()
430 return row;
Harald Welte7f62cec2012-08-13 20:07:41 +0200431
432 f.close()
Harald Weltec26b8292012-08-15 15:25:51 +0200433 return None
434
435def read_params_csv(opts, imsi):
436 row = _read_params_csv(opts, imsi)
437 if row is not None:
438 row['mcc'] = int(row['mcc'])
439 row['mnc'] = int(row['mnc'])
Harald Welte7f62cec2012-08-13 20:07:41 +0200440 return row
441
Harald Weltec26b8292012-08-15 15:25:51 +0200442
Harald Welte130524b2012-08-13 15:53:43 +0200443def write_params_hlr(opts, params):
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100444 # SQLite3 OpenBSC HLR
445 if opts.write_hlr:
446 import sqlite3
447 conn = sqlite3.connect(opts.write_hlr)
448
449 c = conn.execute(
450 'INSERT INTO Subscriber ' +
451 '(imsi, name, extension, authorized, created, updated) ' +
452 'VALUES ' +
453 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
454 [
455 params['imsi'],
456 params['name'],
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200457 '9' + params['iccid'][-5:-1]
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100458 ],
459 )
460 sub_id = c.lastrowid
461 c.close()
462
463 c = conn.execute(
464 'INSERT INTO AuthKeys ' +
465 '(subscriber_id, algorithm_id, a3a8_ki)' +
466 'VALUES ' +
467 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100468 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100469 )
470
471 conn.commit()
472 conn.close()
473
Harald Welte130524b2012-08-13 15:53:43 +0200474def write_parameters(opts, params):
475 write_params_csv(opts, params)
Harald Welte7f62cec2012-08-13 20:07:41 +0200476 write_params_hlr(opts, params)
Harald Welte130524b2012-08-13 15:53:43 +0200477
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100478
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100479BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
480BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100481
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100482def init_batch(opts):
483 # Need to do something ?
484 if not opts.batch_mode:
485 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100486
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100487 for k in BATCH_INCOMPATIBLE:
488 if getattr(opts, k):
489 print "Incompatible option with batch_state: %s" % (k,)
490 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100491
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100492 # Don't load state if there is none ...
493 if not opts.batch_state:
494 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100495
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100496 if not os.path.isfile(opts.batch_state):
497 print "No state file yet"
498 return
499
500 # Get stored data
501 fh = open(opts.batch_state)
502 d = json.loads(fh.read())
503 fh.close()
504
505 for k,v in d.iteritems():
506 setattr(opts, k, v)
507
508
509def save_batch(opts):
510 # Need to do something ?
511 if not opts.batch_mode or not opts.batch_state:
512 return
513
514 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
515 fh = open(opts.batch_state, 'w')
516 fh.write(d)
517 fh.close()
518
519
520def card_detect(opts, scc):
Sylvain Munautbdca2522010-12-09 13:31:58 +0100521
Sylvain Munaut76504e02010-12-07 00:24:32 +0100522 # Detect type if needed
523 card = None
524 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
525
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100526 if opts.type in ("auto", "auto_once"):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100527 for kls in _cards_classes:
528 card = kls.autodetect(scc)
529 if card:
530 print "Autodetected card type %s" % card.name
531 card.reset()
532 break
533
534 if card is None:
535 print "Autodetection failed"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100536 return
537
538 if opts.type == "auto_once":
539 opts.type = card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100540
541 elif opts.type in ctypes:
542 card = ctypes[opts.type](scc)
543
544 else:
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100545 raise ValueError("Unknown card type %s" % opts.type)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100546
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100547 return card
Sylvain Munaut76504e02010-12-07 00:24:32 +0100548
Sylvain Munaut76504e02010-12-07 00:24:32 +0100549
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100550if __name__ == '__main__':
551
552 # Parse options
553 opts = parse_options()
554
555 # Connect to the card
556 if opts.pcsc_dev is None:
557 from pySim.transport.serial import SerialSimLink
558 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
559 else:
560 from pySim.transport.pcsc import PcscSimLink
561 sl = PcscSimLink(opts.pcsc_dev)
562
563 # Create command layer
564 scc = SimCardCommands(transport=sl)
565
566 # Batch mode init
567 init_batch(opts)
568
569 # Iterate
570 done = False
571 first = True
572 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100573
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100574 while not done:
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200575
576 if opts.dry_run is False:
577 # Connect transport
578 print "Insert card now (or CTRL-C to cancel)"
579 sl.wait_for_card(newcardonly=not first)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100580
581 # Not the first anymore !
582 first = False
583
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200584 if opts.dry_run is False:
585 # Get card
586 card = card_detect(opts, scc)
587 if card is None:
588 if opts.batch_mode:
589 first = False
590 continue
591 else:
592 sys.exit(-1)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100593
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200594 # Erase if requested
595 if opts.erase:
596 print "Formatting ..."
597 card.erase()
598 card.reset()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100599
600 # Generate parameters
Harald Welte7f62cec2012-08-13 20:07:41 +0200601 if opts.source == 'cmdline':
602 cp = gen_parameters(opts)
603 elif opts.source == 'csv':
604 cp = read_params_csv(opts, opts.imsi)
605 if cp is None:
606 print "Error reading parameters\n"
607 sys.exit(2)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100608 print_parameters(cp)
609
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200610 if opts.dry_run is False:
611 # Program the card
612 print "Programming ..."
613 if opts.dry_run is not True:
614 card.program(cp)
615 else:
616 print "Dry Run: NOT PROGRAMMING!"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100617
618 # Write parameters permanently
619 write_parameters(opts, cp)
620
621 # Batch mode state update and save
Sylvain Munaut8d243e82010-12-23 20:27:48 +0100622 if opts.num is not None:
623 opts.num += 1
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100624 save_batch(opts)
625
626 # Done for this card and maybe for everything ?
627 print "Done !\n"
628
629 if not opts.batch_mode:
630 done = True
Sylvain Munaut76504e02010-12-07 00:24:32 +0100631