blob: 2638eefaef20cdfedd52afe0aacc972137a6fc5b [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
Philipp Maierf7792312018-06-11 17:11:39 +020043from pySim.ts_51_011 import EF
Sylvain Munaut76504e02010-12-07 00:24:32 +010044
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 )
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +070061 parser.add_option("--osmocon", dest="osmocon_sock", metavar="PATH",
62 help="Socket path for Calypso (e.g. Motorola C1XX) based reader (via OsmocomBB)",
63 default=None,
64 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010065 parser.add_option("-t", "--type", dest="type",
66 help="Card type (user -t list to view) [default: %default]",
67 default="auto",
68 )
Philipp Maierac9dde62018-07-04 11:05:14 +020069 parser.add_option("-T", "--probe", dest="probe",
70 help="Determine card type",
71 default=False, action="store_true"
72 )
Jan Balkec3ebd332015-01-26 12:22:55 +010073 parser.add_option("-a", "--pin-adm", dest="pin_adm",
74 help="ADM PIN used for provisioning (overwrites default)",
75 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010076 parser.add_option("-e", "--erase", dest="erase", action='store_true',
77 help="Erase beforehand [default: %default]",
78 default=False,
79 )
80
Harald Welte7f62cec2012-08-13 20:07:41 +020081 parser.add_option("-S", "--source", dest="source",
82 help="Data Source[default: %default]",
83 default="cmdline",
84 )
85
86 # if mode is "cmdline"
Sylvain Munaut76504e02010-12-07 00:24:32 +010087 parser.add_option("-n", "--name", dest="name",
88 help="Operator name [default: %default]",
89 default="Magic",
90 )
91 parser.add_option("-c", "--country", dest="country", type="int", metavar="CC",
92 help="Country code [default: %default]",
93 default=1,
94 )
95 parser.add_option("-x", "--mcc", dest="mcc", type="int",
96 help="Mobile Country Code [default: %default]",
97 default=901,
98 )
99 parser.add_option("-y", "--mnc", dest="mnc", type="int",
Sylvain Munaut17716032010-12-08 22:33:51 +0100100 help="Mobile Network Code [default: %default]",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100101 default=55,
102 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100103 parser.add_option("-m", "--smsc", dest="smsc",
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200104 help="SMSC number (Start with + for international no.) [default: '00 + country code + 5555']",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100105 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100106 parser.add_option("-M", "--smsp", dest="smsp",
107 help="Raw SMSP content in hex [default: auto from SMSC]",
108 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100109
110 parser.add_option("-s", "--iccid", dest="iccid", metavar="ID",
111 help="Integrated Circuit Card ID",
112 )
113 parser.add_option("-i", "--imsi", dest="imsi",
114 help="International Mobile Subscriber Identity",
115 )
116 parser.add_option("-k", "--ki", dest="ki",
117 help="Ki (default is to randomize)",
118 )
Harald Welte93b38cd2012-03-22 14:31:36 +0100119 parser.add_option("-o", "--opc", dest="opc",
120 help="OPC (default is to randomize)",
121 )
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100122 parser.add_option("--op", dest="op",
123 help="Set OP to derive OPC from OP and KI",
124 )
Alexander Chemeris21885242013-07-02 16:56:55 +0400125 parser.add_option("--acc", dest="acc",
126 help="Set ACC bits (Access Control Code). not all card types are supported",
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200127 )
128 parser.add_option("--read-imsi", dest="read_imsi", action="store_true",
129 help="Read the IMSI from the CARD", default=False
Alexander Chemeris21885242013-07-02 16:56:55 +0400130 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100131 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
132 help="Secret used for ICCID/IMSI autogen",
133 )
134 parser.add_option("-j", "--num", dest="num", type=int,
135 help="Card # used for ICCID/IMSI autogen",
136 )
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100137 parser.add_option("--batch", dest="batch_mode",
138 help="Enable batch mode [default: %default]",
139 default=False, action='store_true',
140 )
141 parser.add_option("--batch-state", dest="batch_state", metavar="FILE",
142 help="Optional batch state file",
143 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100144
Harald Welte7f62cec2012-08-13 20:07:41 +0200145 # if mode is "csv"
146 parser.add_option("--read-csv", dest="read_csv", metavar="FILE",
147 help="Read parameters from CSV file rather than command line")
148
149
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100150 parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
151 help="Append generated parameters in CSV file",
152 )
153 parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
154 help="Append generated parameters to OpenBSC HLR sqlite3",
155 )
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200156 parser.add_option("--dry-run", dest="dry_run",
157 help="Perform a 'dry run', don't actually program the card",
158 default=False, action="store_true")
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100159
Sylvain Munaut76504e02010-12-07 00:24:32 +0100160 (options, args) = parser.parse_args()
161
162 if options.type == 'list':
163 for kls in _cards_classes:
164 print kls.name
165 sys.exit(0)
166
Philipp Maierac9dde62018-07-04 11:05:14 +0200167 if options.probe:
168 return options
169
Harald Welte7f62cec2012-08-13 20:07:41 +0200170 if options.source == 'csv':
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200171 if (options.imsi is None) and (options.batch_mode is False) and (options.read_imsi is False):
172 parser.error("CSV mode needs either an IMSI, --read-imsi or batch mode")
Harald Welte7f62cec2012-08-13 20:07:41 +0200173 if options.read_csv is None:
174 parser.error("CSV mode requires a CSV input file")
175 elif options.source == 'cmdline':
176 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
177 parser.error("If either IMSI or ICCID isn't specified, num is required")
178 else:
179 parser.error("Only `cmdline' and `csv' sources supported")
180
181 if (options.read_csv is not None) and (options.source != 'csv'):
182 parser.error("You cannot specify a CSV input file in source != csv")
183
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100184 if (options.batch_mode) and (options.num is None):
185 options.num = 0
186
Sylvain Munaut98d2b852010-12-23 20:27:25 +0100187 if (options.batch_mode):
188 if (options.imsi is not None) or (options.iccid is not None):
189 parser.error("Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more informations")
190
Sylvain Munaut76504e02010-12-07 00:24:32 +0100191 if args:
192 parser.error("Extraneous arguments")
193
194 return options
195
196
197def _digits(secret, usage, len, num):
198 s = hashlib.sha1(secret + usage + '%d' % num)
199 d = ''.join(['%02d'%ord(x) for x in s.digest()])
200 return d[0:len]
201
202def _mcc_mnc_digits(mcc, mnc):
203 return ('%03d%03d' if mnc > 100 else '%03d%02d') % (mcc, mnc)
204
205def _cc_digits(cc):
206 return ('%03d' if cc > 100 else '%02d') % cc
207
208def _isnum(s, l=-1):
209 return s.isdigit() and ((l== -1) or (len(s) == l))
210
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100211def _ishex(s, l=-1):
212 hc = '0123456789abcdef'
213 return all([x in hc for x in s.lower()]) and ((l== -1) or (len(s) == l))
214
Sylvain Munaut76504e02010-12-07 00:24:32 +0100215
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100216def _dbi_binary_quote(s):
217 # Count usage of each char
218 cnt = {}
219 for c in s:
220 cnt[c] = cnt.get(c, 0) + 1
221
222 # Find best offset
223 e = 0
224 m = len(s)
225 for i in range(1, 256):
226 if i == 39:
227 continue
228 sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
229 if sum_ < m:
230 m = sum_
231 e = i
232 if m == 0: # No overhead ? use this !
233 break;
Sylvain Munaut1a914432011-12-08 20:08:26 +0100234
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100235 # Generate output
236 out = []
237 out.append( chr(e) ) # Offset
238 for c in s:
239 x = (256 + ord(c) - e) % 256
240 if x in (0, 1, 39):
241 out.append('\x01')
242 out.append(chr(x+1))
243 else:
244 out.append(chr(x))
245
246 return ''.join(out)
247
Sylvain Munaut76504e02010-12-07 00:24:32 +0100248def gen_parameters(opts):
Jan Balkec3ebd332015-01-26 12:22:55 +0100249 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki, PIN-ADM from the
Sylvain Munaut76504e02010-12-07 00:24:32 +0100250 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
Todd Neal9eeadfc2018-04-25 15:36:29 -0500268 if not _isnum(iccid, 19) and not _isnum(iccid, 20):
269 raise ValueError('ICCID must be 19 or 20 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:
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200326 ton = "81"
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100327 if opts.smsc is not None:
328 smsc = opts.smsc
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200329 if smsc[0] == '+':
330 ton = "91"
331 smsc = smsc[1:]
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100332 if not _isnum(smsc):
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200333 raise ValueError('SMSC must be digits only!\n \
334 Start with \'+\' for international numbers')
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100335 else:
336 smsc = '00%d' % opts.country + '5555' # Hack ...
337
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200338 smsc = '%02d' % ((len(smsc) + 3)//2,) + ton + swap_nibbles(rpad(smsc, 20))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100339
340 smsp = (
341 'e1' + # Parameters indicator
342 'ff' * 12 + # TP-Destination address
343 smsc + # TP-Service Centre Address
344 '00' + # TP-Protocol identifier
345 '00' + # TP-Data coding scheme
346 '00' # TP-Validity period
347 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100348
Alexander Chemeris21885242013-07-02 16:56:55 +0400349 # ACC
350 if opts.acc is not None:
351 acc = opts.acc
352 if not _ishex(acc):
353 raise ValueError('ACC must be hex digits only !')
354 if len(acc) != 2*2:
355 raise ValueError('ACC must be exactly 2 bytes')
356
357 else:
358 acc = None
359
Sylvain Munaut76504e02010-12-07 00:24:32 +0100360 # Ki (random)
361 if opts.ki is not None:
362 ki = opts.ki
363 if not re.match('^[0-9a-fA-F]{32}$', ki):
364 raise ValueError('Ki needs to be 128 bits, in hex format')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100365 else:
366 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
367
Alexander Chemerisd17ca3d2017-07-18 16:40:58 +0300368 # OPC (random)
Harald Welte93b38cd2012-03-22 14:31:36 +0100369 if opts.opc is not None:
370 opc = opts.opc
371 if not re.match('^[0-9a-fA-F]{32}$', opc):
372 raise ValueError('OPC needs to be 128 bits, in hex format')
373
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100374 elif opts.op is not None:
375 opc = derive_milenage_opc(ki, opts.op)
Harald Welte93b38cd2012-03-22 14:31:36 +0100376 else:
377 opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
378
Jan Balkec3ebd332015-01-26 12:22:55 +0100379 if opts.pin_adm is not None:
Philipp Maierd9824882018-06-13 09:21:59 +0200380 if len(opts.pin_adm) <= 8:
381 pin_adm = ''.join(['%02x'%(ord(x)) for x in opts.pin_adm])
382 pin_adm = rpad(pin_adm, 16)
383 elif len(opts.pin_adm) == 16:
384 pin_adm = opts.pin_adm
385 else:
386 raise ValueError("PIN-ADM needs to be <=8 digits (ascii) or exactly 16 digits (raw hex)")
Jan Balkec3ebd332015-01-26 12:22:55 +0100387 else:
388 pin_adm = None
389
Harald Welte93b38cd2012-03-22 14:31:36 +0100390
Sylvain Munaut76504e02010-12-07 00:24:32 +0100391 # Return that
392 return {
393 'name' : opts.name,
394 'iccid' : iccid,
395 'mcc' : mcc,
396 'mnc' : mnc,
397 'imsi' : imsi,
398 'smsp' : smsp,
399 'ki' : ki,
Harald Welte93b38cd2012-03-22 14:31:36 +0100400 'opc' : opc,
Alexander Chemeris21885242013-07-02 16:56:55 +0400401 'acc' : acc,
Jan Balkec3ebd332015-01-26 12:22:55 +0100402 'pin_adm' : pin_adm,
Sylvain Munaut76504e02010-12-07 00:24:32 +0100403 }
404
405
406def print_parameters(params):
407
408 print """Generated card parameters :
409 > Name : %(name)s
410 > SMSP : %(smsp)s
411 > ICCID : %(iccid)s
412 > MCC/MNC : %(mcc)d/%(mnc)d
413 > IMSI : %(imsi)s
414 > Ki : %(ki)s
Harald Welte93b38cd2012-03-22 14:31:36 +0100415 > OPC : %(opc)s
Alexander Chemeris21885242013-07-02 16:56:55 +0400416 > ACC : %(acc)s
Sylvain Munaut76504e02010-12-07 00:24:32 +0100417""" % params
418
419
Harald Welte130524b2012-08-13 15:53:43 +0200420def write_params_csv(opts, params):
421 # csv
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100422 if opts.write_csv:
423 import csv
Harald Welte93b38cd2012-03-22 14:31:36 +0100424 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100425 f = open(opts.write_csv, 'a')
426 cw = csv.writer(f)
427 cw.writerow([params[x] for x in row])
428 f.close()
429
Harald Weltec26b8292012-08-15 15:25:51 +0200430def _read_params_csv(opts, imsi):
Harald Welte7f62cec2012-08-13 20:07:41 +0200431 import csv
432 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
433 f = open(opts.read_csv, 'r')
434 cr = csv.DictReader(f, row)
435 i = 0
436 for row in cr:
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200437 if opts.num is not None and opts.read_imsi is False:
Harald Welte7f62cec2012-08-13 20:07:41 +0200438 if opts.num == i:
Harald Weltec26b8292012-08-15 15:25:51 +0200439 f.close()
440 return row;
441 i += 1
Harald Welte7f62cec2012-08-13 20:07:41 +0200442 if row['imsi'] == imsi:
Harald Weltec26b8292012-08-15 15:25:51 +0200443 f.close()
444 return row;
Harald Welte7f62cec2012-08-13 20:07:41 +0200445
446 f.close()
Harald Weltec26b8292012-08-15 15:25:51 +0200447 return None
448
449def read_params_csv(opts, imsi):
450 row = _read_params_csv(opts, imsi)
451 if row is not None:
452 row['mcc'] = int(row['mcc'])
453 row['mnc'] = int(row['mnc'])
Harald Welte7f62cec2012-08-13 20:07:41 +0200454 return row
455
Harald Weltec26b8292012-08-15 15:25:51 +0200456
Harald Welte130524b2012-08-13 15:53:43 +0200457def write_params_hlr(opts, params):
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100458 # SQLite3 OpenBSC HLR
459 if opts.write_hlr:
460 import sqlite3
461 conn = sqlite3.connect(opts.write_hlr)
462
463 c = conn.execute(
464 'INSERT INTO Subscriber ' +
465 '(imsi, name, extension, authorized, created, updated) ' +
466 'VALUES ' +
467 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
468 [
469 params['imsi'],
470 params['name'],
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200471 '9' + params['iccid'][-5:-1]
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100472 ],
473 )
474 sub_id = c.lastrowid
475 c.close()
476
477 c = conn.execute(
478 'INSERT INTO AuthKeys ' +
479 '(subscriber_id, algorithm_id, a3a8_ki)' +
480 'VALUES ' +
481 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100482 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100483 )
484
485 conn.commit()
486 conn.close()
487
Harald Welte130524b2012-08-13 15:53:43 +0200488def write_parameters(opts, params):
489 write_params_csv(opts, params)
Harald Welte7f62cec2012-08-13 20:07:41 +0200490 write_params_hlr(opts, params)
Harald Welte130524b2012-08-13 15:53:43 +0200491
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100492
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100493BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
494BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100495
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100496def init_batch(opts):
497 # Need to do something ?
498 if not opts.batch_mode:
499 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100500
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100501 for k in BATCH_INCOMPATIBLE:
502 if getattr(opts, k):
503 print "Incompatible option with batch_state: %s" % (k,)
504 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100505
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100506 # Don't load state if there is none ...
507 if not opts.batch_state:
508 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100509
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100510 if not os.path.isfile(opts.batch_state):
511 print "No state file yet"
512 return
513
514 # Get stored data
515 fh = open(opts.batch_state)
516 d = json.loads(fh.read())
517 fh.close()
518
519 for k,v in d.iteritems():
520 setattr(opts, k, v)
521
522
523def save_batch(opts):
524 # Need to do something ?
525 if not opts.batch_mode or not opts.batch_state:
526 return
527
528 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
529 fh = open(opts.batch_state, 'w')
530 fh.write(d)
531 fh.close()
532
533
534def card_detect(opts, scc):
Sylvain Munautbdca2522010-12-09 13:31:58 +0100535
Sylvain Munaut76504e02010-12-07 00:24:32 +0100536 # Detect type if needed
537 card = None
538 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
539
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100540 if opts.type in ("auto", "auto_once"):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100541 for kls in _cards_classes:
542 card = kls.autodetect(scc)
543 if card:
Philipp Maierac9dde62018-07-04 11:05:14 +0200544 print "Autodetected card type: %s" % card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100545 card.reset()
546 break
547
548 if card is None:
549 print "Autodetection failed"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100550 return
551
552 if opts.type == "auto_once":
553 opts.type = card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100554
555 elif opts.type in ctypes:
556 card = ctypes[opts.type](scc)
557
558 else:
Philipp Maierac9dde62018-07-04 11:05:14 +0200559 raise ValueError("Unknown card type: %s" % opts.type)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100560
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100561 return card
Sylvain Munaut76504e02010-12-07 00:24:32 +0100562
Sylvain Munaut76504e02010-12-07 00:24:32 +0100563
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100564if __name__ == '__main__':
565
566 # Parse options
567 opts = parse_options()
568
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700569 # Init card reader driver
570 if opts.pcsc_dev is not None:
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700571 print("Using PC/SC reader (dev=%d) interface"
572 % opts.pcsc_dev)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100573 from pySim.transport.pcsc import PcscSimLink
574 sl = PcscSimLink(opts.pcsc_dev)
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +0700575 elif opts.osmocon_sock is not None:
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700576 print("Using Calypso-based (OsmocomBB, sock=%s) reader interface"
577 % opts.osmocon_sock)
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +0700578 from pySim.transport.calypso import CalypsoSimLink
579 sl = CalypsoSimLink(sock_path=opts.osmocon_sock)
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700580 else: # Serial reader is default
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700581 print("Using serial reader (port=%s, baudrate=%d) interface"
582 % (opts.device, opts.baudrate))
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700583 from pySim.transport.serial import SerialSimLink
584 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100585
586 # Create command layer
587 scc = SimCardCommands(transport=sl)
588
589 # Batch mode init
590 init_batch(opts)
591
592 # Iterate
593 done = False
594 first = True
595 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100596
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100597 while not done:
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200598
599 if opts.dry_run is False:
600 # Connect transport
601 print "Insert card now (or CTRL-C to cancel)"
602 sl.wait_for_card(newcardonly=not first)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100603
604 # Not the first anymore !
605 first = False
606
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200607 if opts.dry_run is False:
608 # Get card
609 card = card_detect(opts, scc)
610 if card is None:
611 if opts.batch_mode:
612 first = False
613 continue
614 else:
615 sys.exit(-1)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100616
Philipp Maierac9dde62018-07-04 11:05:14 +0200617 # Probe only
618 if opts.probe:
619 break;
620
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200621 # Erase if requested
622 if opts.erase:
623 print "Formatting ..."
624 card.erase()
625 card.reset()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100626
627 # Generate parameters
Harald Welte7f62cec2012-08-13 20:07:41 +0200628 if opts.source == 'cmdline':
629 cp = gen_parameters(opts)
630 elif opts.source == 'csv':
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200631 if opts.read_imsi:
632 if opts.dry_run:
633 # Connect transport
634 print "Insert card now (or CTRL-C to cancel)"
635 sl.wait_for_card(newcardonly=not first)
Alexander Chemeris47c73ab2018-01-10 14:10:17 +0900636 (res,_) = scc.read_binary(EF['IMSI'])
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200637 imsi = swap_nibbles(res)[3:]
638 else:
639 imsi = opts.imsi
640 cp = read_params_csv(opts, imsi)
Harald Welte7f62cec2012-08-13 20:07:41 +0200641 if cp is None:
642 print "Error reading parameters\n"
643 sys.exit(2)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100644 print_parameters(cp)
645
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200646 if opts.dry_run is False:
647 # Program the card
648 print "Programming ..."
649 if opts.dry_run is not True:
650 card.program(cp)
651 else:
652 print "Dry Run: NOT PROGRAMMING!"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100653
654 # Write parameters permanently
655 write_parameters(opts, cp)
656
657 # Batch mode state update and save
Sylvain Munaut8d243e82010-12-23 20:27:48 +0100658 if opts.num is not None:
659 opts.num += 1
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100660 save_batch(opts)
661
662 # Done for this card and maybe for everything ?
663 print "Done !\n"
664
665 if not opts.batch_mode:
666 done = True