blob: bfb40b2e6131178290f38b37e4b5d6231ec1c90d [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
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100277 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
Sylvain Munaut76504e02010-12-07 00:24:32 +0100278 if opts.iccid is not None:
279 iccid = opts.iccid
Todd Neal9eeadfc2018-04-25 15:36:29 -0500280 if not _isnum(iccid, 19) and not _isnum(iccid, 20):
281 raise ValueError('ICCID must be 19 or 20 digits !');
Sylvain Munaut76504e02010-12-07 00:24:32 +0100282
283 else:
284 if opts.num is None:
285 raise ValueError('Neither ICCID nor card number specified !')
286
287 iccid = (
288 '89' + # Common prefix (telecom)
289 cc_digits + # Country Code on 2/3 digits
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200290 plmn_digits # MCC/MNC on 5/6 digits
Sylvain Munaut76504e02010-12-07 00:24:32 +0100291 )
292
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100293 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100294
295 if opts.secret is None:
296 # The raw number
297 iccid += ('%%0%dd' % ml) % opts.num
298 else:
299 # Randomized digits
300 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
301
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100302 # Add checksum digit
303 iccid += ('%1d' % calculate_luhn(iccid))
304
Sylvain Munaut76504e02010-12-07 00:24:32 +0100305 # IMSI (15 digits usually)
306 if opts.imsi is not None:
307 imsi = opts.imsi
308 if not _isnum(imsi):
309 raise ValueError('IMSI must be digits only !')
310
311 else:
312 if opts.num is None:
313 raise ValueError('Neither IMSI nor card number specified !')
314
315 ml = 15 - len(plmn_digits)
316
317 if opts.secret is None:
318 # The raw number
319 msin = ('%%0%dd' % ml) % opts.num
320 else:
321 # Randomized digits
322 msin = _digits(opts.secret, 'imsi', ml, opts.num)
323
324 imsi = (
325 plmn_digits + # MCC/MNC on 5/6 digits
326 msin # MSIN
327 )
328
329 # SMSP
330 if opts.smsp is not None:
331 smsp = opts.smsp
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100332 if not _ishex(smsp):
333 raise ValueError('SMSP must be hex digits only !')
334 if len(smsp) < 28*2:
335 raise ValueError('SMSP must be at least 28 bytes')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100336
337 else:
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200338 ton = "81"
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100339 if opts.smsc is not None:
340 smsc = opts.smsc
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200341 if smsc[0] == '+':
342 ton = "91"
343 smsc = smsc[1:]
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100344 if not _isnum(smsc):
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200345 raise ValueError('SMSC must be digits only!\n \
346 Start with \'+\' for international numbers')
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100347 else:
348 smsc = '00%d' % opts.country + '5555' # Hack ...
349
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200350 smsc = '%02d' % ((len(smsc) + 3)//2,) + ton + swap_nibbles(rpad(smsc, 20))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100351
352 smsp = (
353 'e1' + # Parameters indicator
354 'ff' * 12 + # TP-Destination address
355 smsc + # TP-Service Centre Address
356 '00' + # TP-Protocol identifier
357 '00' + # TP-Data coding scheme
358 '00' # TP-Validity period
359 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100360
Alexander Chemeris21885242013-07-02 16:56:55 +0400361 # ACC
362 if opts.acc is not None:
363 acc = opts.acc
364 if not _ishex(acc):
365 raise ValueError('ACC must be hex digits only !')
366 if len(acc) != 2*2:
367 raise ValueError('ACC must be exactly 2 bytes')
368
369 else:
370 acc = None
371
Sylvain Munaut76504e02010-12-07 00:24:32 +0100372 # Ki (random)
373 if opts.ki is not None:
374 ki = opts.ki
375 if not re.match('^[0-9a-fA-F]{32}$', ki):
376 raise ValueError('Ki needs to be 128 bits, in hex format')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100377 else:
378 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
379
Alexander Chemerisd17ca3d2017-07-18 16:40:58 +0300380 # OPC (random)
Harald Welte93b38cd2012-03-22 14:31:36 +0100381 if opts.opc is not None:
382 opc = opts.opc
383 if not re.match('^[0-9a-fA-F]{32}$', opc):
384 raise ValueError('OPC needs to be 128 bits, in hex format')
385
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100386 elif opts.op is not None:
387 opc = derive_milenage_opc(ki, opts.op)
Harald Welte93b38cd2012-03-22 14:31:36 +0100388 else:
389 opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
390
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200391
392 pin_adm = None
393
Jan Balkec3ebd332015-01-26 12:22:55 +0100394 if opts.pin_adm is not None:
Philipp Maierd9824882018-06-13 09:21:59 +0200395 if len(opts.pin_adm) <= 8:
396 pin_adm = ''.join(['%02x'%(ord(x)) for x in opts.pin_adm])
397 pin_adm = rpad(pin_adm, 16)
Jan Balkec3ebd332015-01-26 12:22:55 +0100398
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200399 else:
400 raise ValueError("PIN-ADM needs to be <=8 digits (ascii)")
401
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200402 if opts.pin_adm_hex is not None:
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200403 if len(opts.pin_adm_hex) == 16:
404 pin_adm = opts.pin_adm_hex
405 # Ensure that it's hex-encoded
406 try:
407 try_encode = h2b(pin_adm)
408 except ValueError:
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200409 raise ValueError("PIN-ADM needs to be hex encoded using this option")
Daniel Willmannf432b2b2018-06-15 07:31:50 +0200410 else:
411 raise ValueError("PIN-ADM needs to be exactly 16 digits (hex encoded)")
Harald Welte93b38cd2012-03-22 14:31:36 +0100412
Sylvain Munaut76504e02010-12-07 00:24:32 +0100413 # Return that
414 return {
415 'name' : opts.name,
416 'iccid' : iccid,
417 'mcc' : mcc,
418 'mnc' : mnc,
419 'imsi' : imsi,
420 'smsp' : smsp,
421 'ki' : ki,
Harald Welte93b38cd2012-03-22 14:31:36 +0100422 'opc' : opc,
Alexander Chemeris21885242013-07-02 16:56:55 +0400423 'acc' : acc,
Jan Balkec3ebd332015-01-26 12:22:55 +0100424 'pin_adm' : pin_adm,
Sylvain Munaut76504e02010-12-07 00:24:32 +0100425 }
426
427
428def print_parameters(params):
429
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200430 s = ["Generated card parameters :"]
431 if 'name' in params:
432 s.append(" > Name : %(name)s")
433 if 'smsp' in params:
434 s.append(" > SMSP : %(smsp)s")
435 s.append(" > ICCID : %(iccid)s")
Philipp Maierbe069e22019-09-12 12:52:43 +0200436 s.append(" > MCC/MNC : %(mcc)s/%(mnc)s")
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200437 s.append(" > IMSI : %(imsi)s")
438 s.append(" > Ki : %(ki)s")
439 s.append(" > OPC : %(opc)s")
440 if 'acc' in params:
441 s.append(" > ACC : %(acc)s")
442 s.append(" > ADM1(hex): %(pin_adm)s")
443 print("\n".join(s) % params)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100444
445
Harald Welte130524b2012-08-13 15:53:43 +0200446def write_params_csv(opts, params):
447 # csv
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100448 if opts.write_csv:
449 import csv
Harald Welte93b38cd2012-03-22 14:31:36 +0100450 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100451 f = open(opts.write_csv, 'a')
452 cw = csv.writer(f)
453 cw.writerow([params[x] for x in row])
454 f.close()
455
Daniel Willmann164b9632019-09-03 19:13:51 +0200456def _read_params_csv(opts, iccid=None, imsi=None):
Harald Welte7f62cec2012-08-13 20:07:41 +0200457 import csv
Harald Welte7f62cec2012-08-13 20:07:41 +0200458 f = open(opts.read_csv, 'r')
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200459 cr = csv.DictReader(f)
Philipp Maier120a0002019-09-12 13:11:45 +0200460
461 # Lower-case fieldnames
462 cr.fieldnames = [ field.lower() for field in cr.fieldnames ]
463
Harald Welte7f62cec2012-08-13 20:07:41 +0200464 i = 0
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200465 if not 'iccid' in cr.fieldnames:
466 raise Exception("CSV file in wrong format!")
Harald Welte7f62cec2012-08-13 20:07:41 +0200467 for row in cr:
Daniel Willmann164b9632019-09-03 19:13:51 +0200468 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 +0200469 if opts.num == i:
Harald Weltec26b8292012-08-15 15:25:51 +0200470 f.close()
471 return row;
472 i += 1
Daniel Willmann164b9632019-09-03 19:13:51 +0200473 if row['iccid'] == iccid:
474 f.close()
475 return row;
476
Harald Welte7f62cec2012-08-13 20:07:41 +0200477 if row['imsi'] == imsi:
Harald Weltec26b8292012-08-15 15:25:51 +0200478 f.close()
479 return row;
Harald Welte7f62cec2012-08-13 20:07:41 +0200480
481 f.close()
Harald Weltec26b8292012-08-15 15:25:51 +0200482 return None
483
Daniel Willmann164b9632019-09-03 19:13:51 +0200484def read_params_csv(opts, imsi=None, iccid=None):
485 row = _read_params_csv(opts, iccid=iccid, imsi=imsi)
Harald Weltec26b8292012-08-15 15:25:51 +0200486 if row is not None:
Philipp Maier7592eee2019-09-12 13:03:23 +0200487 row['mcc'] = row.get('mcc', mcc_from_imsi(row.get('imsi')))
488 row['mnc'] = row.get('mnc', mnc_from_imsi(row.get('imsi')))
489
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200490 pin_adm = None
491 # We need to escape the pin_adm we get from the csv
492 if 'pin_adm' in row:
493 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['pin_adm']])
494 # Stay compatible to the odoo csv format
495 elif 'adm1' in row:
496 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['adm1']])
497 if pin_adm:
498 row['pin_adm'] = rpad(pin_adm, 16)
Philipp Maiere053da52019-09-05 13:08:36 +0200499
500 # If the CSV-File defines a pin_adm_hex field use this field to
501 # generate pin_adm from that.
502 pin_adm_hex = row.get('pin_adm_hex')
503 if pin_adm_hex:
504 if len(pin_adm_hex) == 16:
505 row['pin_adm'] = pin_adm_hex
506 # Ensure that it's hex-encoded
507 try:
508 try_encode = h2b(pin_adm)
509 except ValueError:
510 raise ValueError("pin_adm_hex needs to be hex encoded using this option")
511 else:
512 raise ValueError("pin_adm_hex needs to be exactly 16 digits (hex encoded)")
513
Harald Welte7f62cec2012-08-13 20:07:41 +0200514 return row
515
Harald Weltec26b8292012-08-15 15:25:51 +0200516
Harald Welte130524b2012-08-13 15:53:43 +0200517def write_params_hlr(opts, params):
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100518 # SQLite3 OpenBSC HLR
519 if opts.write_hlr:
520 import sqlite3
521 conn = sqlite3.connect(opts.write_hlr)
522
523 c = conn.execute(
524 'INSERT INTO Subscriber ' +
525 '(imsi, name, extension, authorized, created, updated) ' +
526 'VALUES ' +
527 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
528 [
529 params['imsi'],
530 params['name'],
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200531 '9' + params['iccid'][-5:-1]
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100532 ],
533 )
534 sub_id = c.lastrowid
535 c.close()
536
537 c = conn.execute(
538 'INSERT INTO AuthKeys ' +
539 '(subscriber_id, algorithm_id, a3a8_ki)' +
540 'VALUES ' +
541 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100542 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100543 )
544
545 conn.commit()
546 conn.close()
547
Harald Welte130524b2012-08-13 15:53:43 +0200548def write_parameters(opts, params):
549 write_params_csv(opts, params)
Harald Welte7f62cec2012-08-13 20:07:41 +0200550 write_params_hlr(opts, params)
Harald Welte130524b2012-08-13 15:53:43 +0200551
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100552
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100553BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
554BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100555
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100556def init_batch(opts):
557 # Need to do something ?
558 if not opts.batch_mode:
559 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100560
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100561 for k in BATCH_INCOMPATIBLE:
562 if getattr(opts, k):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700563 print("Incompatible option with batch_state: %s" % (k,))
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100564 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100565
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100566 # Don't load state if there is none ...
567 if not opts.batch_state:
568 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100569
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100570 if not os.path.isfile(opts.batch_state):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700571 print("No state file yet")
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100572 return
573
574 # Get stored data
575 fh = open(opts.batch_state)
576 d = json.loads(fh.read())
577 fh.close()
578
579 for k,v in d.iteritems():
580 setattr(opts, k, v)
581
582
583def save_batch(opts):
584 # Need to do something ?
585 if not opts.batch_mode or not opts.batch_state:
586 return
587
588 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
589 fh = open(opts.batch_state, 'w')
590 fh.write(d)
591 fh.close()
592
593
594def card_detect(opts, scc):
Sylvain Munautbdca2522010-12-09 13:31:58 +0100595
Sylvain Munaut76504e02010-12-07 00:24:32 +0100596 # Detect type if needed
597 card = None
598 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
599
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100600 if opts.type in ("auto", "auto_once"):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100601 for kls in _cards_classes:
602 card = kls.autodetect(scc)
603 if card:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700604 print("Autodetected card type: %s" % card.name)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100605 card.reset()
606 break
607
608 if card is None:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700609 print("Autodetection failed")
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100610 return
611
612 if opts.type == "auto_once":
613 opts.type = card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100614
615 elif opts.type in ctypes:
616 card = ctypes[opts.type](scc)
617
618 else:
Philipp Maierac9dde62018-07-04 11:05:14 +0200619 raise ValueError("Unknown card type: %s" % opts.type)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100620
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100621 return card
Sylvain Munaut76504e02010-12-07 00:24:32 +0100622
Sylvain Munaut76504e02010-12-07 00:24:32 +0100623
Philipp Maierc5b422e2019-08-30 11:41:02 +0200624def process_card(opts, first, card_handler):
625
626 if opts.dry_run is False:
627 # Connect transport
628 card_handler.get(first)
629
630 if opts.dry_run is False:
631 # Get card
632 card = card_detect(opts, scc)
633 if card is None:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700634 print("No card detected!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200635 return -1
636
637 # Probe only
638 if opts.probe:
639 return 0
640
641 # Erase if requested
642 if opts.erase:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700643 print("Formatting ...")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200644 card.erase()
645 card.reset()
646
647 # Generate parameters
648 if opts.source == 'cmdline':
649 cp = gen_parameters(opts)
650 elif opts.source == 'csv':
651 imsi = None
652 iccid = None
653 if opts.read_iccid:
654 if opts.dry_run:
655 # Connect transport
656 card_handler.get(false)
657 (res,_) = scc.read_binary(['3f00', '2fe2'], length=10)
658 iccid = dec_iccid(res)
659 elif opts.read_imsi:
660 if opts.dry_run:
661 # Connect transport
662 card_handler.get(false)
663 (res,_) = scc.read_binary(EF['IMSI'])
664 imsi = swap_nibbles(res)[3:]
665 else:
666 imsi = opts.imsi
667 cp = read_params_csv(opts, imsi=imsi, iccid=iccid)
668 if cp is None:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700669 print("Error reading parameters from CSV file!\n")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200670 return 2
671 print_parameters(cp)
672
673 if opts.dry_run is False:
674 # Program the card
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700675 print("Programming ...")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200676 card.program(cp)
677 else:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700678 print("Dry Run: NOT PROGRAMMING!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200679
680 # Write parameters permanently
681 write_parameters(opts, cp)
682
683 # Batch mode state update and save
684 if opts.num is not None:
685 opts.num += 1
686 save_batch(opts)
687
688 card_handler.done()
689 return 0
690
691
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100692if __name__ == '__main__':
693
694 # Parse options
695 opts = parse_options()
696
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700697 # Init card reader driver
698 if opts.pcsc_dev is not None:
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700699 print("Using PC/SC reader (dev=%d) interface"
700 % opts.pcsc_dev)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100701 from pySim.transport.pcsc import PcscSimLink
702 sl = PcscSimLink(opts.pcsc_dev)
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +0700703 elif opts.osmocon_sock is not None:
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700704 print("Using Calypso-based (OsmocomBB, sock=%s) reader interface"
705 % opts.osmocon_sock)
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +0700706 from pySim.transport.calypso import CalypsoSimLink
707 sl = CalypsoSimLink(sock_path=opts.osmocon_sock)
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700708 else: # Serial reader is default
Vadim Yanitskiy35a96ed2018-10-29 02:02:14 +0700709 print("Using serial reader (port=%s, baudrate=%d) interface"
710 % (opts.device, opts.baudrate))
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700711 from pySim.transport.serial import SerialSimLink
712 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100713
714 # Create command layer
715 scc = SimCardCommands(transport=sl)
716
Philipp Maier196b08c2019-09-12 11:49:44 +0200717 # If we use a CSV file as data input, check if the CSV file exists.
718 if opts.source == 'csv':
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700719 print("Using CSV file as data input: " + str(opts.read_csv))
Philipp Maier196b08c2019-09-12 11:49:44 +0200720 if not os.path.isfile(opts.read_csv):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700721 print("CSV file not found!")
Philipp Maier196b08c2019-09-12 11:49:44 +0200722 sys.exit(1)
723
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100724 # Batch mode init
725 init_batch(opts)
726
Philipp Maierc5b422e2019-08-30 11:41:02 +0200727 if opts.card_handler:
728 card_handler = card_handler_auto(sl, opts.card_handler)
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200729 else:
Philipp Maierc5b422e2019-08-30 11:41:02 +0200730 card_handler = card_handler(sl)
731
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100732 # Iterate
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100733 first = True
734 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100735
Philipp Maierc5b422e2019-08-30 11:41:02 +0200736 while 1:
737 try:
738 rc = process_card(opts, first, card_handler)
739 except (KeyboardInterrupt):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700740 print("")
741 print("Terminated by user!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200742 sys.exit(0)
743 except (SystemExit):
744 raise
745 except:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700746 print("")
747 print("Card programming failed with an execption:")
748 print("---------------------8<---------------------")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200749 traceback.print_exc()
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700750 print("---------------------8<---------------------")
751 print("")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200752 rc = -1
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200753
Philipp Maierc5b422e2019-08-30 11:41:02 +0200754 # Something did not work as well as expected, however, lets
755 # make sure the card is pulled from the reader.
756 if rc != 0:
757 card_handler.error()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100758
Philipp Maierc5b422e2019-08-30 11:41:02 +0200759 # If we are not in batch mode we are done in any case, so lets
760 # exit here.
761 if not opts.batch_mode:
762 sys.exit(rc)
763
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100764 first = False