blob: 09a5d70fca1290417ec138dcc191366772512acb [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
Philipp Maierc5b422e2019-08-30 11:41:02 +020033import traceback
Sylvain Munaut76504e02010-12-07 00:24:32 +010034
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +010035try:
36 import json
Holger Hans Peter Freyther5dffefb2011-11-22 21:18:06 +010037except ImportError:
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +010038 # Python < 2.5
39 import simplejson as json
40
Sylvain Munaut76504e02010-12-07 00:24:32 +010041from pySim.commands import SimCardCommands
42from pySim.cards import _cards_classes
Daniel Willmann164b9632019-09-03 19:13:51 +020043from pySim.utils import h2b, swap_nibbles, rpad, derive_milenage_opc, calculate_luhn, dec_iccid
Philipp Maierf7792312018-06-11 17:11:39 +020044from pySim.ts_51_011 import EF
Philipp Maierc5b422e2019-08-30 11:41:02 +020045from pySim.card_handler import *
Philipp Maier7592eee2019-09-12 13:03:23 +020046from pySim.utils import *
Sylvain Munaut76504e02010-12-07 00:24:32 +010047
48def parse_options():
49
50 parser = OptionParser(usage="usage: %prog [options]")
51
52 parser.add_option("-d", "--device", dest="device", metavar="DEV",
53 help="Serial Device for SIM access [default: %default]",
54 default="/dev/ttyUSB0",
55 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010056 parser.add_option("-b", "--baud", dest="baudrate", type="int", metavar="BAUD",
57 help="Baudrate used for SIM access [default: %default]",
58 default=9600,
59 )
Sylvain Munaut9c8729a2010-12-08 23:20:27 +010060 parser.add_option("-p", "--pcsc-device", dest="pcsc_dev", type='int', metavar="PCSC",
Sylvain Munaute9fdecb2010-12-08 22:33:19 +010061 help="Which PC/SC reader number for SIM access",
62 default=None,
63 )
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +070064 parser.add_option("--osmocon", dest="osmocon_sock", metavar="PATH",
65 help="Socket path for Calypso (e.g. Motorola C1XX) based reader (via OsmocomBB)",
66 default=None,
67 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010068 parser.add_option("-t", "--type", dest="type",
69 help="Card type (user -t list to view) [default: %default]",
70 default="auto",
71 )
Philipp Maierac9dde62018-07-04 11:05:14 +020072 parser.add_option("-T", "--probe", dest="probe",
73 help="Determine card type",
74 default=False, action="store_true"
75 )
Jan Balkec3ebd332015-01-26 12:22:55 +010076 parser.add_option("-a", "--pin-adm", dest="pin_adm",
77 help="ADM PIN used for provisioning (overwrites default)",
78 )
Daniel Willmannf432b2b2018-06-15 07:31:50 +020079 parser.add_option("-A", "--pin-adm-hex", dest="pin_adm_hex",
80 help="ADM PIN used for provisioning, as hex string (16 characters long",
81 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010082 parser.add_option("-e", "--erase", dest="erase", action='store_true',
83 help="Erase beforehand [default: %default]",
84 default=False,
85 )
86
Harald Welte7f62cec2012-08-13 20:07:41 +020087 parser.add_option("-S", "--source", dest="source",
88 help="Data Source[default: %default]",
89 default="cmdline",
90 )
91
92 # if mode is "cmdline"
Sylvain Munaut76504e02010-12-07 00:24:32 +010093 parser.add_option("-n", "--name", dest="name",
94 help="Operator name [default: %default]",
95 default="Magic",
96 )
97 parser.add_option("-c", "--country", dest="country", type="int", metavar="CC",
98 help="Country code [default: %default]",
99 default=1,
100 )
101 parser.add_option("-x", "--mcc", dest="mcc", type="int",
102 help="Mobile Country Code [default: %default]",
103 default=901,
104 )
105 parser.add_option("-y", "--mnc", dest="mnc", type="int",
Sylvain Munaut17716032010-12-08 22:33:51 +0100106 help="Mobile Network Code [default: %default]",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100107 default=55,
108 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100109 parser.add_option("-m", "--smsc", dest="smsc",
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200110 help="SMSC number (Start with + for international no.) [default: '00 + country code + 5555']",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100111 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100112 parser.add_option("-M", "--smsp", dest="smsp",
113 help="Raw SMSP content in hex [default: auto from SMSC]",
114 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100115
116 parser.add_option("-s", "--iccid", dest="iccid", metavar="ID",
117 help="Integrated Circuit Card ID",
118 )
119 parser.add_option("-i", "--imsi", dest="imsi",
120 help="International Mobile Subscriber Identity",
121 )
122 parser.add_option("-k", "--ki", dest="ki",
123 help="Ki (default is to randomize)",
124 )
Harald Welte93b38cd2012-03-22 14:31:36 +0100125 parser.add_option("-o", "--opc", dest="opc",
126 help="OPC (default is to randomize)",
127 )
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100128 parser.add_option("--op", dest="op",
129 help="Set OP to derive OPC from OP and KI",
130 )
Alexander Chemeris21885242013-07-02 16:56:55 +0400131 parser.add_option("--acc", dest="acc",
132 help="Set ACC bits (Access Control Code). not all card types are supported",
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200133 )
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200134 parser.add_option("--read-imsi", dest="read_imsi", action="store_true",
135 help="Read the IMSI from the CARD", default=False
Alexander Chemeris21885242013-07-02 16:56:55 +0400136 )
Daniel Willmann164b9632019-09-03 19:13:51 +0200137 parser.add_option("--read-iccid", dest="read_iccid", action="store_true",
138 help="Read the ICCID from the CARD", default=False
139 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100140 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
141 help="Secret used for ICCID/IMSI autogen",
142 )
143 parser.add_option("-j", "--num", dest="num", type=int,
144 help="Card # used for ICCID/IMSI autogen",
145 )
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100146 parser.add_option("--batch", dest="batch_mode",
147 help="Enable batch mode [default: %default]",
148 default=False, action='store_true',
149 )
150 parser.add_option("--batch-state", dest="batch_state", metavar="FILE",
151 help="Optional batch state file",
152 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100153
Harald Welte7f62cec2012-08-13 20:07:41 +0200154 # if mode is "csv"
155 parser.add_option("--read-csv", dest="read_csv", metavar="FILE",
156 help="Read parameters from CSV file rather than command line")
157
158
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100159 parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
160 help="Append generated parameters in CSV file",
161 )
162 parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
163 help="Append generated parameters to OpenBSC HLR sqlite3",
164 )
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200165 parser.add_option("--dry-run", dest="dry_run",
166 help="Perform a 'dry run', don't actually program the card",
167 default=False, action="store_true")
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100168
Philipp Maierc5b422e2019-08-30 11:41:02 +0200169 parser.add_option("--card_handler", dest="card_handler", metavar="FILE",
170 help="Use automatic card handling machine")
171
Sylvain Munaut76504e02010-12-07 00:24:32 +0100172 (options, args) = parser.parse_args()
173
174 if options.type == 'list':
175 for kls in _cards_classes:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700176 print(kls.name)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100177 sys.exit(0)
178
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200179 if options.probe:
180 return options
Philipp Maierac9dde62018-07-04 11:05:14 +0200181
Harald Welte7f62cec2012-08-13 20:07:41 +0200182 if options.source == 'csv':
Daniel Willmann164b9632019-09-03 19:13:51 +0200183 if (options.imsi is None) and (options.batch_mode is False) and (options.read_imsi is False) and (options.read_iccid is False):
184 parser.error("CSV mode needs either an IMSI, --read-imsi, --read-iccid or batch mode")
Harald Welte7f62cec2012-08-13 20:07:41 +0200185 if options.read_csv is None:
186 parser.error("CSV mode requires a CSV input file")
187 elif options.source == 'cmdline':
188 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
189 parser.error("If either IMSI or ICCID isn't specified, num is required")
190 else:
191 parser.error("Only `cmdline' and `csv' sources supported")
192
193 if (options.read_csv is not None) and (options.source != 'csv'):
194 parser.error("You cannot specify a CSV input file in source != csv")
195
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100196 if (options.batch_mode) and (options.num is None):
197 options.num = 0
198
Sylvain Munaut98d2b852010-12-23 20:27:25 +0100199 if (options.batch_mode):
200 if (options.imsi is not None) or (options.iccid is not None):
201 parser.error("Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more informations")
202
Sylvain Munaut76504e02010-12-07 00:24:32 +0100203 if args:
204 parser.error("Extraneous arguments")
205
206 return options
207
208
209def _digits(secret, usage, len, num):
210 s = hashlib.sha1(secret + usage + '%d' % num)
211 d = ''.join(['%02d'%ord(x) for x in s.digest()])
212 return d[0:len]
213
214def _mcc_mnc_digits(mcc, mnc):
215 return ('%03d%03d' if mnc > 100 else '%03d%02d') % (mcc, mnc)
216
217def _cc_digits(cc):
218 return ('%03d' if cc > 100 else '%02d') % cc
219
220def _isnum(s, l=-1):
221 return s.isdigit() and ((l== -1) or (len(s) == l))
222
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100223def _ishex(s, l=-1):
224 hc = '0123456789abcdef'
225 return all([x in hc for x in s.lower()]) and ((l== -1) or (len(s) == l))
226
Sylvain Munaut76504e02010-12-07 00:24:32 +0100227
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100228def _dbi_binary_quote(s):
229 # Count usage of each char
230 cnt = {}
231 for c in s:
232 cnt[c] = cnt.get(c, 0) + 1
233
234 # Find best offset
235 e = 0
236 m = len(s)
237 for i in range(1, 256):
238 if i == 39:
239 continue
240 sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
241 if sum_ < m:
242 m = sum_
243 e = i
244 if m == 0: # No overhead ? use this !
245 break;
Sylvain Munaut1a914432011-12-08 20:08:26 +0100246
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100247 # Generate output
248 out = []
249 out.append( chr(e) ) # Offset
250 for c in s:
251 x = (256 + ord(c) - e) % 256
252 if x in (0, 1, 39):
253 out.append('\x01')
254 out.append(chr(x+1))
255 else:
256 out.append(chr(x))
257
258 return ''.join(out)
259
Sylvain Munaut76504e02010-12-07 00:24:32 +0100260def gen_parameters(opts):
Jan Balkec3ebd332015-01-26 12:22:55 +0100261 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki, PIN-ADM from the
Sylvain Munaut76504e02010-12-07 00:24:32 +0100262 options given by the user"""
263
264 # MCC/MNC
265 mcc = opts.mcc
266 mnc = opts.mnc
267
268 if not ((0 < mcc < 999) and (0 < mnc < 999)):
269 raise ValueError('mcc & mnc must be between 0 and 999')
270
271 # Digitize country code (2 or 3 digits)
272 cc_digits = _cc_digits(opts.country)
273
274 # Digitize MCC/MNC (5 or 6 digits)
275 plmn_digits = _mcc_mnc_digits(mcc, mnc)
276
Supreeth Herle840a9e22020-01-21 13:32:46 +0100277 if opts.name is not None:
278 if len(opts.name) > 16:
279 raise ValueError('Service Provider Name must max 16 characters!');
280
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100281 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
Sylvain Munaut76504e02010-12-07 00:24:32 +0100282 if opts.iccid is not None:
283 iccid = opts.iccid
Todd Neal9eeadfc2018-04-25 15:36:29 -0500284 if not _isnum(iccid, 19) and not _isnum(iccid, 20):
285 raise ValueError('ICCID must be 19 or 20 digits !');
Sylvain Munaut76504e02010-12-07 00:24:32 +0100286
287 else:
288 if opts.num is None:
289 raise ValueError('Neither ICCID nor card number specified !')
290
291 iccid = (
292 '89' + # Common prefix (telecom)
293 cc_digits + # Country Code on 2/3 digits
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200294 plmn_digits # MCC/MNC on 5/6 digits
Sylvain Munaut76504e02010-12-07 00:24:32 +0100295 )
296
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100297 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100298
299 if opts.secret is None:
300 # The raw number
301 iccid += ('%%0%dd' % ml) % opts.num
302 else:
303 # Randomized digits
304 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
305
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100306 # Add checksum digit
307 iccid += ('%1d' % calculate_luhn(iccid))
308
Sylvain Munaut76504e02010-12-07 00:24:32 +0100309 # IMSI (15 digits usually)
310 if opts.imsi is not None:
311 imsi = opts.imsi
312 if not _isnum(imsi):
313 raise ValueError('IMSI must be digits only !')
314
315 else:
316 if opts.num is None:
317 raise ValueError('Neither IMSI nor card number specified !')
318
319 ml = 15 - len(plmn_digits)
320
321 if opts.secret is None:
322 # The raw number
323 msin = ('%%0%dd' % ml) % opts.num
324 else:
325 # Randomized digits
326 msin = _digits(opts.secret, 'imsi', ml, opts.num)
327
328 imsi = (
329 plmn_digits + # MCC/MNC on 5/6 digits
330 msin # MSIN
331 )
332
333 # SMSP
334 if opts.smsp is not None:
335 smsp = opts.smsp
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100336 if not _ishex(smsp):
337 raise ValueError('SMSP must be hex digits only !')
338 if len(smsp) < 28*2:
339 raise ValueError('SMSP must be at least 28 bytes')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100340
341 else:
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200342 ton = "81"
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100343 if opts.smsc is not None:
344 smsc = opts.smsc
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200345 if smsc[0] == '+':
346 ton = "91"
347 smsc = smsc[1:]
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100348 if not _isnum(smsc):
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200349 raise ValueError('SMSC must be digits only!\n \
350 Start with \'+\' for international numbers')
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100351 else:
352 smsc = '00%d' % opts.country + '5555' # Hack ...
353
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200354 smsc = '%02d' % ((len(smsc) + 3)//2,) + ton + swap_nibbles(rpad(smsc, 20))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100355
356 smsp = (
357 'e1' + # Parameters indicator
358 'ff' * 12 + # TP-Destination address
359 smsc + # TP-Service Centre Address
360 '00' + # TP-Protocol identifier
361 '00' + # TP-Data coding scheme
362 '00' # TP-Validity period
363 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100364
Alexander Chemeris21885242013-07-02 16:56:55 +0400365 # ACC
366 if opts.acc is not None:
367 acc = opts.acc
368 if not _ishex(acc):
369 raise ValueError('ACC must be hex digits only !')
370 if len(acc) != 2*2:
371 raise ValueError('ACC must be exactly 2 bytes')
372
373 else:
374 acc = None
375
Sylvain Munaut76504e02010-12-07 00:24:32 +0100376 # Ki (random)
377 if opts.ki is not None:
378 ki = opts.ki
379 if not re.match('^[0-9a-fA-F]{32}$', ki):
380 raise ValueError('Ki needs to be 128 bits, in hex format')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100381 else:
382 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
383
Alexander Chemerisd17ca3d2017-07-18 16:40:58 +0300384 # OPC (random)
Harald Welte93b38cd2012-03-22 14:31:36 +0100385 if opts.opc is not None:
386 opc = opts.opc
387 if not re.match('^[0-9a-fA-F]{32}$', opc):
388 raise ValueError('OPC needs to be 128 bits, in hex format')
389
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100390 elif opts.op is not None:
391 opc = derive_milenage_opc(ki, opts.op)
Harald Welte93b38cd2012-03-22 14:31:36 +0100392 else:
393 opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
394
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200395
396 pin_adm = None
397
Jan Balkec3ebd332015-01-26 12:22:55 +0100398 if opts.pin_adm is not None:
Philipp Maierd9824882018-06-13 09:21:59 +0200399 if len(opts.pin_adm) <= 8:
400 pin_adm = ''.join(['%02x'%(ord(x)) for x in opts.pin_adm])
401 pin_adm = rpad(pin_adm, 16)
Jan Balkec3ebd332015-01-26 12:22:55 +0100402
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200403 else:
404 raise ValueError("PIN-ADM needs to be <=8 digits (ascii)")
405
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200406 if opts.pin_adm_hex is not None:
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200407 if len(opts.pin_adm_hex) == 16:
408 pin_adm = opts.pin_adm_hex
409 # Ensure that it's hex-encoded
410 try:
411 try_encode = h2b(pin_adm)
412 except ValueError:
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200413 raise ValueError("PIN-ADM needs to be hex encoded using this option")
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200414 else:
415 raise ValueError("PIN-ADM needs to be exactly 16 digits (hex encoded)")
Harald Welte93b38cd2012-03-22 14:31:36 +0100416
Sylvain Munaut76504e02010-12-07 00:24:32 +0100417 # Return that
418 return {
419 'name' : opts.name,
420 'iccid' : iccid,
421 'mcc' : mcc,
422 'mnc' : mnc,
423 'imsi' : imsi,
424 'smsp' : smsp,
425 'ki' : ki,
Harald Welte93b38cd2012-03-22 14:31:36 +0100426 'opc' : opc,
Alexander Chemeris21885242013-07-02 16:56:55 +0400427 'acc' : acc,
Jan Balkec3ebd332015-01-26 12:22:55 +0100428 'pin_adm' : pin_adm,
Sylvain Munaut76504e02010-12-07 00:24:32 +0100429 }
430
431
432def print_parameters(params):
433
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200434 s = ["Generated card parameters :"]
435 if 'name' in params:
436 s.append(" > Name : %(name)s")
437 if 'smsp' in params:
438 s.append(" > SMSP : %(smsp)s")
439 s.append(" > ICCID : %(iccid)s")
Philipp Maierbe069e22019-09-12 12:52:43 +0200440 s.append(" > MCC/MNC : %(mcc)s/%(mnc)s")
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200441 s.append(" > IMSI : %(imsi)s")
442 s.append(" > Ki : %(ki)s")
443 s.append(" > OPC : %(opc)s")
444 if 'acc' in params:
445 s.append(" > ACC : %(acc)s")
446 s.append(" > ADM1(hex): %(pin_adm)s")
447 print("\n".join(s) % params)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100448
449
Harald Welte130524b2012-08-13 15:53:43 +0200450def write_params_csv(opts, params):
451 # csv
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100452 if opts.write_csv:
453 import csv
Harald Welte93b38cd2012-03-22 14:31:36 +0100454 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100455 f = open(opts.write_csv, 'a')
456 cw = csv.writer(f)
457 cw.writerow([params[x] for x in row])
458 f.close()
459
Daniel Willmann164b9632019-09-03 19:13:51 +0200460def _read_params_csv(opts, iccid=None, imsi=None):
Harald Welte7f62cec2012-08-13 20:07:41 +0200461 import csv
Harald Welte7f62cec2012-08-13 20:07:41 +0200462 f = open(opts.read_csv, 'r')
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200463 cr = csv.DictReader(f)
Philipp Maier120a0002019-09-12 13:11:45 +0200464
465 # Lower-case fieldnames
466 cr.fieldnames = [ field.lower() for field in cr.fieldnames ]
467
Harald Welte7f62cec2012-08-13 20:07:41 +0200468 i = 0
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200469 if not 'iccid' in cr.fieldnames:
470 raise Exception("CSV file in wrong format!")
Harald Welte7f62cec2012-08-13 20:07:41 +0200471 for row in cr:
Daniel Willmann164b9632019-09-03 19:13:51 +0200472 if opts.num is not None and opts.read_iccid is False and opts.read_imsi is False:
Harald Welte7f62cec2012-08-13 20:07:41 +0200473 if opts.num == i:
Harald Weltec26b8292012-08-15 15:25:51 +0200474 f.close()
475 return row;
476 i += 1
Daniel Willmann164b9632019-09-03 19:13:51 +0200477 if row['iccid'] == iccid:
478 f.close()
479 return row;
480
Harald Welte7f62cec2012-08-13 20:07:41 +0200481 if row['imsi'] == imsi:
Harald Weltec26b8292012-08-15 15:25:51 +0200482 f.close()
483 return row;
Harald Welte7f62cec2012-08-13 20:07:41 +0200484
485 f.close()
Harald Weltec26b8292012-08-15 15:25:51 +0200486 return None
487
Daniel Willmann164b9632019-09-03 19:13:51 +0200488def read_params_csv(opts, imsi=None, iccid=None):
489 row = _read_params_csv(opts, iccid=iccid, imsi=imsi)
Harald Weltec26b8292012-08-15 15:25:51 +0200490 if row is not None:
Philipp Maier7592eee2019-09-12 13:03:23 +0200491 row['mcc'] = row.get('mcc', mcc_from_imsi(row.get('imsi')))
492 row['mnc'] = row.get('mnc', mnc_from_imsi(row.get('imsi')))
493
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200494 pin_adm = None
495 # We need to escape the pin_adm we get from the csv
496 if 'pin_adm' in row:
497 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['pin_adm']])
498 # Stay compatible to the odoo csv format
499 elif 'adm1' in row:
500 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['adm1']])
501 if pin_adm:
502 row['pin_adm'] = rpad(pin_adm, 16)
Philipp Maiere053da52019-09-05 13:08:36 +0200503
504 # If the CSV-File defines a pin_adm_hex field use this field to
505 # generate pin_adm from that.
506 pin_adm_hex = row.get('pin_adm_hex')
507 if pin_adm_hex:
508 if len(pin_adm_hex) == 16:
509 row['pin_adm'] = pin_adm_hex
510 # Ensure that it's hex-encoded
511 try:
512 try_encode = h2b(pin_adm)
513 except ValueError:
514 raise ValueError("pin_adm_hex needs to be hex encoded using this option")
515 else:
516 raise ValueError("pin_adm_hex needs to be exactly 16 digits (hex encoded)")
517
Harald Welte7f62cec2012-08-13 20:07:41 +0200518 return row
519
Harald Weltec26b8292012-08-15 15:25:51 +0200520
Harald Welte130524b2012-08-13 15:53:43 +0200521def write_params_hlr(opts, params):
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100522 # SQLite3 OpenBSC HLR
523 if opts.write_hlr:
524 import sqlite3
525 conn = sqlite3.connect(opts.write_hlr)
526
527 c = conn.execute(
528 'INSERT INTO Subscriber ' +
529 '(imsi, name, extension, authorized, created, updated) ' +
530 'VALUES ' +
531 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
532 [
533 params['imsi'],
534 params['name'],
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200535 '9' + params['iccid'][-5:-1]
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100536 ],
537 )
538 sub_id = c.lastrowid
539 c.close()
540
541 c = conn.execute(
542 'INSERT INTO AuthKeys ' +
543 '(subscriber_id, algorithm_id, a3a8_ki)' +
544 'VALUES ' +
545 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100546 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100547 )
548
549 conn.commit()
550 conn.close()
551
Harald Welte130524b2012-08-13 15:53:43 +0200552def write_parameters(opts, params):
553 write_params_csv(opts, params)
Harald Welte7f62cec2012-08-13 20:07:41 +0200554 write_params_hlr(opts, params)
Harald Welte130524b2012-08-13 15:53:43 +0200555
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100556
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100557BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
558BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100559
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100560def init_batch(opts):
561 # Need to do something ?
562 if not opts.batch_mode:
563 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100564
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100565 for k in BATCH_INCOMPATIBLE:
566 if getattr(opts, k):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700567 print("Incompatible option with batch_state: %s" % (k,))
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100568 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100569
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100570 # Don't load state if there is none ...
571 if not opts.batch_state:
572 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100573
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100574 if not os.path.isfile(opts.batch_state):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700575 print("No state file yet")
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100576 return
577
578 # Get stored data
579 fh = open(opts.batch_state)
580 d = json.loads(fh.read())
581 fh.close()
582
583 for k,v in d.iteritems():
584 setattr(opts, k, v)
585
586
587def save_batch(opts):
588 # Need to do something ?
589 if not opts.batch_mode or not opts.batch_state:
590 return
591
592 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
593 fh = open(opts.batch_state, 'w')
594 fh.write(d)
595 fh.close()
596
597
598def card_detect(opts, scc):
Sylvain Munautbdca2522010-12-09 13:31:58 +0100599
Sylvain Munaut76504e02010-12-07 00:24:32 +0100600 # Detect type if needed
601 card = None
602 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
603
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100604 if opts.type in ("auto", "auto_once"):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100605 for kls in _cards_classes:
606 card = kls.autodetect(scc)
607 if card:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700608 print("Autodetected card type: %s" % card.name)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100609 card.reset()
610 break
611
612 if card is None:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700613 print("Autodetection failed")
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100614 return
615
616 if opts.type == "auto_once":
617 opts.type = card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100618
619 elif opts.type in ctypes:
620 card = ctypes[opts.type](scc)
621
622 else:
Philipp Maierac9dde62018-07-04 11:05:14 +0200623 raise ValueError("Unknown card type: %s" % opts.type)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100624
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100625 return card
Sylvain Munaut76504e02010-12-07 00:24:32 +0100626
Sylvain Munaut76504e02010-12-07 00:24:32 +0100627
Philipp Maierc5b422e2019-08-30 11:41:02 +0200628def process_card(opts, first, card_handler):
629
630 if opts.dry_run is False:
631 # Connect transport
632 card_handler.get(first)
633
634 if opts.dry_run is False:
635 # Get card
636 card = card_detect(opts, scc)
637 if card is None:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700638 print("No card detected!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200639 return -1
640
641 # Probe only
642 if opts.probe:
643 return 0
644
645 # Erase if requested
646 if opts.erase:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700647 print("Formatting ...")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200648 card.erase()
649 card.reset()
650
651 # Generate parameters
652 if opts.source == 'cmdline':
653 cp = gen_parameters(opts)
654 elif opts.source == 'csv':
655 imsi = None
656 iccid = None
657 if opts.read_iccid:
658 if opts.dry_run:
659 # Connect transport
660 card_handler.get(false)
661 (res,_) = scc.read_binary(['3f00', '2fe2'], length=10)
662 iccid = dec_iccid(res)
663 elif opts.read_imsi:
664 if opts.dry_run:
665 # Connect transport
666 card_handler.get(false)
667 (res,_) = scc.read_binary(EF['IMSI'])
668 imsi = swap_nibbles(res)[3:]
669 else:
670 imsi = opts.imsi
671 cp = read_params_csv(opts, imsi=imsi, iccid=iccid)
672 if cp is None:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700673 print("Error reading parameters from CSV file!\n")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200674 return 2
675 print_parameters(cp)
676
677 if opts.dry_run is False:
678 # Program the card
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700679 print("Programming ...")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200680 card.program(cp)
681 else:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700682 print("Dry Run: NOT PROGRAMMING!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200683
684 # Write parameters permanently
685 write_parameters(opts, cp)
686
687 # Batch mode state update and save
688 if opts.num is not None:
689 opts.num += 1
690 save_batch(opts)
691
692 card_handler.done()
693 return 0
694
695
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100696if __name__ == '__main__':
697
698 # Parse options
699 opts = parse_options()
700
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700701 # Init card reader driver
702 if opts.pcsc_dev is not None:
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700703 print("Using PC/SC reader (dev=%d) interface"
704 % opts.pcsc_dev)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100705 from pySim.transport.pcsc import PcscSimLink
706 sl = PcscSimLink(opts.pcsc_dev)
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +0700707 elif opts.osmocon_sock is not None:
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700708 print("Using Calypso-based (OsmocomBB, sock=%s) reader interface"
709 % opts.osmocon_sock)
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +0700710 from pySim.transport.calypso import CalypsoSimLink
711 sl = CalypsoSimLink(sock_path=opts.osmocon_sock)
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700712 else: # Serial reader is default
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700713 print("Using serial reader (port=%s, baudrate=%d) interface"
714 % (opts.device, opts.baudrate))
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700715 from pySim.transport.serial import SerialSimLink
716 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100717
718 # Create command layer
719 scc = SimCardCommands(transport=sl)
720
Philipp Maier196b08c2019-09-12 11:49:44 +0200721 # If we use a CSV file as data input, check if the CSV file exists.
722 if opts.source == 'csv':
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700723 print("Using CSV file as data input: " + str(opts.read_csv))
Philipp Maier196b08c2019-09-12 11:49:44 +0200724 if not os.path.isfile(opts.read_csv):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700725 print("CSV file not found!")
Philipp Maier196b08c2019-09-12 11:49:44 +0200726 sys.exit(1)
727
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100728 # Batch mode init
729 init_batch(opts)
730
Philipp Maierc5b422e2019-08-30 11:41:02 +0200731 if opts.card_handler:
732 card_handler = card_handler_auto(sl, opts.card_handler)
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200733 else:
Philipp Maierc5b422e2019-08-30 11:41:02 +0200734 card_handler = card_handler(sl)
735
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100736 # Iterate
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100737 first = True
738 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100739
Philipp Maierc5b422e2019-08-30 11:41:02 +0200740 while 1:
741 try:
742 rc = process_card(opts, first, card_handler)
743 except (KeyboardInterrupt):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700744 print("")
745 print("Terminated by user!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200746 sys.exit(0)
747 except (SystemExit):
748 raise
749 except:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700750 print("")
751 print("Card programming failed with an execption:")
752 print("---------------------8<---------------------")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200753 traceback.print_exc()
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700754 print("---------------------8<---------------------")
755 print("")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200756 rc = -1
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200757
Philipp Maierc5b422e2019-08-30 11:41:02 +0200758 # Something did not work as well as expected, however, lets
759 # make sure the card is pulled from the reader.
760 if rc != 0:
761 card_handler.error()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100762
Philipp Maierc5b422e2019-08-30 11:41:02 +0200763 # If we are not in batch mode we are done in any case, so lets
764 # exit here.
765 if not opts.batch_mode:
766 sys.exit(rc)
767
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100768 first = False