blob: c08f43b1d1a4f6883d92224e5187a6420f5f884a [file] [log] [blame]
Pau Espin Pedrolac23ad52017-12-29 20:30:35 +01001#!/usr/bin/env python2
Sylvain Munaut76504e02010-12-07 00:24:32 +01002
3#
4# Utility to deal with sim cards and program the 'magic' ones easily
5#
6#
7# Part of the sim link code of inspired by pySimReader-Serial-src-v2
8#
9#
10# Copyright (C) 2009 Sylvain Munaut <tnt@246tNt.com>
11# Copyright (C) 2010 Harald Welte <laforge@gnumonks.org>
12#
13# This program is free software: you can redistribute it and/or modify
14# it under the terms of the GNU General Public License as published by
15# the Free Software Foundation, either version 2 of the License, or
16# (at your option) any later version.
17#
18# This program is distributed in the hope that it will be useful,
19# but WITHOUT ANY WARRANTY; without even the implied warranty of
20# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21# GNU General Public License for more details.
22#
23# You should have received a copy of the GNU General Public License
24# along with this program. If not, see <http://www.gnu.org/licenses/>.
25#
26
27import hashlib
28from optparse import OptionParser
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +010029import os
Sylvain Munaut76504e02010-12-07 00:24:32 +010030import random
31import re
32import sys
33
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +010034try:
35 import json
Holger Hans Peter Freyther5dffefb2011-11-22 21:18:06 +010036except ImportError:
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +010037 # Python < 2.5
38 import simplejson as json
39
Sylvain Munaut76504e02010-12-07 00:24:32 +010040from pySim.commands import SimCardCommands
41from pySim.cards import _cards_classes
Alexander Chemeris19fffa12018-01-11 13:06:43 +090042from pySim.utils import h2b, swap_nibbles, rpad, derive_milenage_opc, calculate_luhn
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
Sylvain Munaut76504e02010-12-07 00:24:32 +0100237def gen_parameters(opts):
Jan Balkec3ebd332015-01-26 12:22:55 +0100238 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki, PIN-ADM from the
Sylvain Munaut76504e02010-12-07 00:24:32 +0100239 options given by the user"""
240
241 # MCC/MNC
242 mcc = opts.mcc
243 mnc = opts.mnc
244
245 if not ((0 < mcc < 999) and (0 < mnc < 999)):
246 raise ValueError('mcc & mnc must be between 0 and 999')
247
248 # Digitize country code (2 or 3 digits)
249 cc_digits = _cc_digits(opts.country)
250
251 # Digitize MCC/MNC (5 or 6 digits)
252 plmn_digits = _mcc_mnc_digits(mcc, mnc)
253
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100254 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
Sylvain Munaut76504e02010-12-07 00:24:32 +0100255 if opts.iccid is not None:
256 iccid = opts.iccid
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100257 if not _isnum(iccid, 19):
258 raise ValueError('ICCID must be 19 digits !');
Sylvain Munaut76504e02010-12-07 00:24:32 +0100259
260 else:
261 if opts.num is None:
262 raise ValueError('Neither ICCID nor card number specified !')
263
264 iccid = (
265 '89' + # Common prefix (telecom)
266 cc_digits + # Country Code on 2/3 digits
267 plmn_digits # MCC/MNC on 5/6 digits
268 )
269
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100270 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100271
272 if opts.secret is None:
273 # The raw number
274 iccid += ('%%0%dd' % ml) % opts.num
275 else:
276 # Randomized digits
277 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
278
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100279 # Add checksum digit
280 iccid += ('%1d' % calculate_luhn(iccid))
281
Sylvain Munaut76504e02010-12-07 00:24:32 +0100282 # IMSI (15 digits usually)
283 if opts.imsi is not None:
284 imsi = opts.imsi
285 if not _isnum(imsi):
286 raise ValueError('IMSI must be digits only !')
287
288 else:
289 if opts.num is None:
290 raise ValueError('Neither IMSI nor card number specified !')
291
292 ml = 15 - len(plmn_digits)
293
294 if opts.secret is None:
295 # The raw number
296 msin = ('%%0%dd' % ml) % opts.num
297 else:
298 # Randomized digits
299 msin = _digits(opts.secret, 'imsi', ml, opts.num)
300
301 imsi = (
302 plmn_digits + # MCC/MNC on 5/6 digits
303 msin # MSIN
304 )
305
306 # SMSP
307 if opts.smsp is not None:
308 smsp = opts.smsp
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100309 if not _ishex(smsp):
310 raise ValueError('SMSP must be hex digits only !')
311 if len(smsp) < 28*2:
312 raise ValueError('SMSP must be at least 28 bytes')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100313
314 else:
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100315 if opts.smsc is not None:
316 smsc = opts.smsc
317 if not _isnum(smsc):
318 raise ValueError('SMSC must be digits only !')
319 else:
320 smsc = '00%d' % opts.country + '5555' # Hack ...
321
Sylvain Munaut9977c862011-12-10 09:57:16 +0100322 smsc = '%02d' % ((len(smsc) + 3)//2,) + "81" + swap_nibbles(rpad(smsc, 20))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100323
324 smsp = (
325 'e1' + # Parameters indicator
326 'ff' * 12 + # TP-Destination address
327 smsc + # TP-Service Centre Address
328 '00' + # TP-Protocol identifier
329 '00' + # TP-Data coding scheme
330 '00' # TP-Validity period
331 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100332
Alexander Chemeris21885242013-07-02 16:56:55 +0400333 # ACC
334 if opts.acc is not None:
335 acc = opts.acc
336 if not _ishex(acc):
337 raise ValueError('ACC must be hex digits only !')
338 if len(acc) != 2*2:
339 raise ValueError('ACC must be exactly 2 bytes')
340
341 else:
342 acc = None
343
Sylvain Munaut76504e02010-12-07 00:24:32 +0100344 # Ki (random)
345 if opts.ki is not None:
346 ki = opts.ki
347 if not re.match('^[0-9a-fA-F]{32}$', ki):
348 raise ValueError('Ki needs to be 128 bits, in hex format')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100349 else:
350 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
351
Alexander Chemerisd17ca3d2017-07-18 16:40:58 +0300352 # OPC (random)
Harald Welte93b38cd2012-03-22 14:31:36 +0100353 if opts.opc is not None:
354 opc = opts.opc
355 if not re.match('^[0-9a-fA-F]{32}$', opc):
356 raise ValueError('OPC needs to be 128 bits, in hex format')
357
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100358 elif opts.op is not None:
359 opc = derive_milenage_opc(ki, opts.op)
Harald Welte93b38cd2012-03-22 14:31:36 +0100360 else:
361 opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
362
Jan Balkec3ebd332015-01-26 12:22:55 +0100363 if opts.pin_adm is not None:
Alexander Chemerisa51592e2018-01-10 14:07:30 +0900364 pin_adm = opts.pin_adm
365 if not re.match('^([0-9a-fA-F][0-9a-fA-F])+$', pin_adm):
366 raise ValueError('ADM pin needs to be in hex format (even number of hex digits)')
Jan Balkec3ebd332015-01-26 12:22:55 +0100367 else:
368 pin_adm = None
369
Harald Welte93b38cd2012-03-22 14:31:36 +0100370
Sylvain Munaut76504e02010-12-07 00:24:32 +0100371 # Return that
372 return {
373 'name' : opts.name,
374 'iccid' : iccid,
375 'mcc' : mcc,
376 'mnc' : mnc,
377 'imsi' : imsi,
378 'smsp' : smsp,
379 'ki' : ki,
Harald Welte93b38cd2012-03-22 14:31:36 +0100380 'opc' : opc,
Alexander Chemeris21885242013-07-02 16:56:55 +0400381 'acc' : acc,
Jan Balkec3ebd332015-01-26 12:22:55 +0100382 'pin_adm' : pin_adm,
Sylvain Munaut76504e02010-12-07 00:24:32 +0100383 }
384
385
386def print_parameters(params):
387
388 print """Generated card parameters :
389 > Name : %(name)s
390 > SMSP : %(smsp)s
391 > ICCID : %(iccid)s
392 > MCC/MNC : %(mcc)d/%(mnc)d
393 > IMSI : %(imsi)s
394 > Ki : %(ki)s
Harald Welte93b38cd2012-03-22 14:31:36 +0100395 > OPC : %(opc)s
Alexander Chemeris21885242013-07-02 16:56:55 +0400396 > ACC : %(acc)s
Sylvain Munaut76504e02010-12-07 00:24:32 +0100397""" % params
398
399
Harald Welte130524b2012-08-13 15:53:43 +0200400def write_params_csv(opts, params):
401 # csv
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100402 if opts.write_csv:
403 import csv
Harald Welte93b38cd2012-03-22 14:31:36 +0100404 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100405 f = open(opts.write_csv, 'a')
406 cw = csv.writer(f)
407 cw.writerow([params[x] for x in row])
408 f.close()
409
Harald Weltec26b8292012-08-15 15:25:51 +0200410def _read_params_csv(opts, imsi):
Harald Welte7f62cec2012-08-13 20:07:41 +0200411 import csv
412 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
413 f = open(opts.read_csv, 'r')
414 cr = csv.DictReader(f, row)
415 i = 0
416 for row in cr:
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200417 if opts.num is not None and opts.read_imsi is False:
Harald Welte7f62cec2012-08-13 20:07:41 +0200418 if opts.num == i:
Harald Weltec26b8292012-08-15 15:25:51 +0200419 f.close()
420 return row;
421 i += 1
Harald Welte7f62cec2012-08-13 20:07:41 +0200422 if row['imsi'] == imsi:
Harald Weltec26b8292012-08-15 15:25:51 +0200423 f.close()
424 return row;
Harald Welte7f62cec2012-08-13 20:07:41 +0200425
426 f.close()
Harald Weltec26b8292012-08-15 15:25:51 +0200427 return None
428
429def read_params_csv(opts, imsi):
430 row = _read_params_csv(opts, imsi)
431 if row is not None:
432 row['mcc'] = int(row['mcc'])
433 row['mnc'] = int(row['mnc'])
Harald Welte7f62cec2012-08-13 20:07:41 +0200434 return row
435
Harald Weltec26b8292012-08-15 15:25:51 +0200436
Harald Welte130524b2012-08-13 15:53:43 +0200437def write_params_hlr(opts, params):
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100438 # SQLite3 OpenBSC HLR
439 if opts.write_hlr:
440 import sqlite3
441 conn = sqlite3.connect(opts.write_hlr)
442
443 c = conn.execute(
444 'INSERT INTO Subscriber ' +
445 '(imsi, name, extension, authorized, created, updated) ' +
446 'VALUES ' +
447 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
448 [
449 params['imsi'],
450 params['name'],
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200451 '9' + params['iccid'][-5:-1]
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100452 ],
453 )
454 sub_id = c.lastrowid
455 c.close()
456
457 c = conn.execute(
458 'INSERT INTO AuthKeys ' +
459 '(subscriber_id, algorithm_id, a3a8_ki)' +
460 'VALUES ' +
461 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100462 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100463 )
464
465 conn.commit()
466 conn.close()
467
Harald Welte130524b2012-08-13 15:53:43 +0200468def write_parameters(opts, params):
469 write_params_csv(opts, params)
Harald Welte7f62cec2012-08-13 20:07:41 +0200470 write_params_hlr(opts, params)
Harald Welte130524b2012-08-13 15:53:43 +0200471
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100472
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100473BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
474BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100475
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100476def init_batch(opts):
477 # Need to do something ?
478 if not opts.batch_mode:
479 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100480
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100481 for k in BATCH_INCOMPATIBLE:
482 if getattr(opts, k):
483 print "Incompatible option with batch_state: %s" % (k,)
484 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100485
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100486 # Don't load state if there is none ...
487 if not opts.batch_state:
488 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100489
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100490 if not os.path.isfile(opts.batch_state):
491 print "No state file yet"
492 return
493
494 # Get stored data
495 fh = open(opts.batch_state)
496 d = json.loads(fh.read())
497 fh.close()
498
499 for k,v in d.iteritems():
500 setattr(opts, k, v)
501
502
503def save_batch(opts):
504 # Need to do something ?
505 if not opts.batch_mode or not opts.batch_state:
506 return
507
508 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
509 fh = open(opts.batch_state, 'w')
510 fh.write(d)
511 fh.close()
512
513
514def card_detect(opts, scc):
Sylvain Munautbdca2522010-12-09 13:31:58 +0100515
Sylvain Munaut76504e02010-12-07 00:24:32 +0100516 # Detect type if needed
517 card = None
518 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
519
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100520 if opts.type in ("auto", "auto_once"):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100521 for kls in _cards_classes:
522 card = kls.autodetect(scc)
523 if card:
524 print "Autodetected card type %s" % card.name
525 card.reset()
526 break
527
528 if card is None:
529 print "Autodetection failed"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100530 return
531
532 if opts.type == "auto_once":
533 opts.type = card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100534
535 elif opts.type in ctypes:
536 card = ctypes[opts.type](scc)
537
538 else:
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100539 raise ValueError("Unknown card type %s" % opts.type)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100540
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100541 return card
Sylvain Munaut76504e02010-12-07 00:24:32 +0100542
Sylvain Munaut76504e02010-12-07 00:24:32 +0100543
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100544if __name__ == '__main__':
545
546 # Parse options
547 opts = parse_options()
548
549 # Connect to the card
550 if opts.pcsc_dev is None:
551 from pySim.transport.serial import SerialSimLink
552 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
553 else:
554 from pySim.transport.pcsc import PcscSimLink
555 sl = PcscSimLink(opts.pcsc_dev)
556
557 # Create command layer
558 scc = SimCardCommands(transport=sl)
559
560 # Batch mode init
561 init_batch(opts)
562
563 # Iterate
564 done = False
565 first = True
566 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100567
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100568 while not done:
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200569
570 if opts.dry_run is False:
571 # Connect transport
572 print "Insert card now (or CTRL-C to cancel)"
573 sl.wait_for_card(newcardonly=not first)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100574
575 # Not the first anymore !
576 first = False
577
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200578 if opts.dry_run is False:
579 # Get card
580 card = card_detect(opts, scc)
581 if card is None:
582 if opts.batch_mode:
583 first = False
584 continue
585 else:
586 sys.exit(-1)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100587
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200588 # Erase if requested
589 if opts.erase:
590 print "Formatting ..."
591 card.erase()
592 card.reset()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100593
594 # Generate parameters
Harald Welte7f62cec2012-08-13 20:07:41 +0200595 if opts.source == 'cmdline':
596 cp = gen_parameters(opts)
597 elif opts.source == 'csv':
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200598 if opts.read_imsi:
599 if opts.dry_run:
600 # Connect transport
601 print "Insert card now (or CTRL-C to cancel)"
602 sl.wait_for_card(newcardonly=not first)
Alexander Chemeris47c73ab2018-01-10 14:10:17 +0900603 (res,_) = scc.read_binary(EF['IMSI'])
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200604 imsi = swap_nibbles(res)[3:]
605 else:
606 imsi = opts.imsi
607 cp = read_params_csv(opts, imsi)
Harald Welte7f62cec2012-08-13 20:07:41 +0200608 if cp is None:
609 print "Error reading parameters\n"
610 sys.exit(2)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100611 print_parameters(cp)
612
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200613 if opts.dry_run is False:
614 # Program the card
615 print "Programming ..."
616 if opts.dry_run is not True:
617 card.program(cp)
618 else:
619 print "Dry Run: NOT PROGRAMMING!"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100620
621 # Write parameters permanently
622 write_parameters(opts, cp)
623
624 # Batch mode state update and save
Sylvain Munaut8d243e82010-12-23 20:27:48 +0100625 if opts.num is not None:
626 opts.num += 1
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100627 save_batch(opts)
628
629 # Done for this card and maybe for everything ?
630 print "Done !\n"
631
632 if not opts.batch_mode:
633 done = True