blob: f707c57c68b3323a48f60d54ee5a4798d73203dd [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
Supreeth Herle4c306ab2020-03-18 11:38:00 +010042from pySim.cards import _cards_classes, card_detect
Philipp Maierff84c232020-05-12 17:24:18 +020043from pySim.utils import h2b, swap_nibbles, rpad, derive_milenage_opc, calculate_luhn, dec_iccid, init_reader
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 )
Harald Welte7f1d3c42020-05-12 21:12:44 +0200101 parser.add_option("-x", "--mcc", dest="mcc", type="string",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100102 help="Mobile Country Code [default: %default]",
Harald Welte7f1d3c42020-05-12 21:12:44 +0200103 default="901",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100104 )
Harald Welte7f1d3c42020-05-12 21:12:44 +0200105 parser.add_option("-y", "--mnc", dest="mnc", type="string",
Sylvain Munaut17716032010-12-08 22:33:51 +0100106 help="Mobile Network Code [default: %default]",
Harald Welte7f1d3c42020-05-12 21:12:44 +0200107 default="55",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100108 )
Supreeth Herlefc83e432020-05-06 11:48:46 +0200109 parser.add_option("--mnclen", dest="mnclen", type="choice",
110 help="Length of Mobile Network Code [default: %default]",
111 default=2,
112 choices=[2, 3],
113 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100114 parser.add_option("-m", "--smsc", dest="smsc",
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200115 help="SMSC number (Start with + for international no.) [default: '00 + country code + 5555']",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100116 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100117 parser.add_option("-M", "--smsp", dest="smsp",
118 help="Raw SMSP content in hex [default: auto from SMSC]",
119 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100120
121 parser.add_option("-s", "--iccid", dest="iccid", metavar="ID",
122 help="Integrated Circuit Card ID",
123 )
124 parser.add_option("-i", "--imsi", dest="imsi",
125 help="International Mobile Subscriber Identity",
126 )
Supreeth Herle5a541012019-12-22 08:59:16 +0100127 parser.add_option("--msisdn", dest="msisdn",
128 help="Mobile Subscriber Integrated Services Digital Number",
129 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100130 parser.add_option("-k", "--ki", dest="ki",
131 help="Ki (default is to randomize)",
132 )
Harald Welte93b38cd2012-03-22 14:31:36 +0100133 parser.add_option("-o", "--opc", dest="opc",
134 help="OPC (default is to randomize)",
135 )
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100136 parser.add_option("--op", dest="op",
137 help="Set OP to derive OPC from OP and KI",
138 )
Alexander Chemeris21885242013-07-02 16:56:55 +0400139 parser.add_option("--acc", dest="acc",
140 help="Set ACC bits (Access Control Code). not all card types are supported",
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200141 )
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200142 parser.add_option("--read-imsi", dest="read_imsi", action="store_true",
143 help="Read the IMSI from the CARD", default=False
Alexander Chemeris21885242013-07-02 16:56:55 +0400144 )
Daniel Willmann164b9632019-09-03 19:13:51 +0200145 parser.add_option("--read-iccid", dest="read_iccid", action="store_true",
146 help="Read the ICCID from the CARD", default=False
147 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100148 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
149 help="Secret used for ICCID/IMSI autogen",
150 )
151 parser.add_option("-j", "--num", dest="num", type=int,
152 help="Card # used for ICCID/IMSI autogen",
153 )
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100154 parser.add_option("--batch", dest="batch_mode",
155 help="Enable batch mode [default: %default]",
156 default=False, action='store_true',
157 )
158 parser.add_option("--batch-state", dest="batch_state", metavar="FILE",
159 help="Optional batch state file",
160 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100161
Harald Welte7f62cec2012-08-13 20:07:41 +0200162 # if mode is "csv"
163 parser.add_option("--read-csv", dest="read_csv", metavar="FILE",
164 help="Read parameters from CSV file rather than command line")
165
166
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100167 parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
168 help="Append generated parameters in CSV file",
169 )
170 parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
171 help="Append generated parameters to OpenBSC HLR sqlite3",
172 )
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200173 parser.add_option("--dry-run", dest="dry_run",
174 help="Perform a 'dry run', don't actually program the card",
175 default=False, action="store_true")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200176 parser.add_option("--card_handler", dest="card_handler", metavar="FILE",
177 help="Use automatic card handling machine")
178
Sylvain Munaut76504e02010-12-07 00:24:32 +0100179 (options, args) = parser.parse_args()
180
181 if options.type == 'list':
182 for kls in _cards_classes:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700183 print(kls.name)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100184 sys.exit(0)
185
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200186 if options.probe:
187 return options
Philipp Maierac9dde62018-07-04 11:05:14 +0200188
Harald Welte7f62cec2012-08-13 20:07:41 +0200189 if options.source == 'csv':
Daniel Willmann164b9632019-09-03 19:13:51 +0200190 if (options.imsi is None) and (options.batch_mode is False) and (options.read_imsi is False) and (options.read_iccid is False):
191 parser.error("CSV mode needs either an IMSI, --read-imsi, --read-iccid or batch mode")
Harald Welte7f62cec2012-08-13 20:07:41 +0200192 if options.read_csv is None:
193 parser.error("CSV mode requires a CSV input file")
194 elif options.source == 'cmdline':
195 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
196 parser.error("If either IMSI or ICCID isn't specified, num is required")
197 else:
198 parser.error("Only `cmdline' and `csv' sources supported")
199
200 if (options.read_csv is not None) and (options.source != 'csv'):
201 parser.error("You cannot specify a CSV input file in source != csv")
202
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100203 if (options.batch_mode) and (options.num is None):
204 options.num = 0
205
Sylvain Munaut98d2b852010-12-23 20:27:25 +0100206 if (options.batch_mode):
207 if (options.imsi is not None) or (options.iccid is not None):
208 parser.error("Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more informations")
209
Sylvain Munaut76504e02010-12-07 00:24:32 +0100210 if args:
211 parser.error("Extraneous arguments")
212
213 return options
214
215
216def _digits(secret, usage, len, num):
217 s = hashlib.sha1(secret + usage + '%d' % num)
218 d = ''.join(['%02d'%ord(x) for x in s.digest()])
219 return d[0:len]
220
221def _mcc_mnc_digits(mcc, mnc):
Harald Welte7f1d3c42020-05-12 21:12:44 +0200222 return '%s%s' % (mcc, mnc)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100223
224def _cc_digits(cc):
225 return ('%03d' if cc > 100 else '%02d') % cc
226
227def _isnum(s, l=-1):
228 return s.isdigit() and ((l== -1) or (len(s) == l))
229
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100230def _ishex(s, l=-1):
231 hc = '0123456789abcdef'
232 return all([x in hc for x in s.lower()]) and ((l== -1) or (len(s) == l))
233
Sylvain Munaut76504e02010-12-07 00:24:32 +0100234
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100235def _dbi_binary_quote(s):
236 # Count usage of each char
237 cnt = {}
238 for c in s:
239 cnt[c] = cnt.get(c, 0) + 1
240
241 # Find best offset
242 e = 0
243 m = len(s)
244 for i in range(1, 256):
245 if i == 39:
246 continue
247 sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
248 if sum_ < m:
249 m = sum_
250 e = i
251 if m == 0: # No overhead ? use this !
252 break;
Sylvain Munaut1a914432011-12-08 20:08:26 +0100253
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100254 # Generate output
255 out = []
256 out.append( chr(e) ) # Offset
257 for c in s:
258 x = (256 + ord(c) - e) % 256
259 if x in (0, 1, 39):
260 out.append('\x01')
261 out.append(chr(x+1))
262 else:
263 out.append(chr(x))
264
265 return ''.join(out)
266
Sylvain Munaut76504e02010-12-07 00:24:32 +0100267def gen_parameters(opts):
Jan Balkec3ebd332015-01-26 12:22:55 +0100268 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki, PIN-ADM from the
Sylvain Munaut76504e02010-12-07 00:24:32 +0100269 options given by the user"""
270
271 # MCC/MNC
272 mcc = opts.mcc
273 mnc = opts.mnc
274
Harald Welte7f1d3c42020-05-12 21:12:44 +0200275 if not mcc.isdigit() or not mnc.isdigit():
276 raise ValueError('mcc & mnc must only contain decimal digits')
277 if len(mcc) < 1 or len(mcc) > 3:
278 raise ValueError('mcc must be between 1 .. 3 digits')
279 if len(mnc) < 1 or len(mnc) > 3:
280 raise ValueError('mnc must be between 1 .. 3 digits')
281
282 # MCC always has 3 digits
283 mcc = lpad(mcc, 3, "0")
284 # MNC must be at least 2 digits
285 mnc = lpad(mnc, 2, "0")
Sylvain Munaut76504e02010-12-07 00:24:32 +0100286
287 # Digitize country code (2 or 3 digits)
288 cc_digits = _cc_digits(opts.country)
289
290 # Digitize MCC/MNC (5 or 6 digits)
291 plmn_digits = _mcc_mnc_digits(mcc, mnc)
292
Supreeth Herle840a9e22020-01-21 13:32:46 +0100293 if opts.name is not None:
294 if len(opts.name) > 16:
295 raise ValueError('Service Provider Name must max 16 characters!');
296
Supreeth Herle5a541012019-12-22 08:59:16 +0100297 if opts.msisdn is not None:
298 msisdn = opts.msisdn
299 if msisdn[0] == '+':
300 msisdn = msisdn[1:]
301 if not msisdn.isdigit():
302 raise ValueError('MSISDN must be digits only! '
303 'Start with \'+\' for international numbers.')
304 if len(msisdn) > 10 * 2:
305 # TODO: Support MSISDN of length > 20 (10 Bytes)
306 raise ValueError('MSISDNs longer than 20 digits are not (yet) supported.')
307
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100308 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
Sylvain Munaut76504e02010-12-07 00:24:32 +0100309 if opts.iccid is not None:
310 iccid = opts.iccid
Todd Neal9eeadfc2018-04-25 15:36:29 -0500311 if not _isnum(iccid, 19) and not _isnum(iccid, 20):
312 raise ValueError('ICCID must be 19 or 20 digits !');
Sylvain Munaut76504e02010-12-07 00:24:32 +0100313
314 else:
315 if opts.num is None:
316 raise ValueError('Neither ICCID nor card number specified !')
317
318 iccid = (
319 '89' + # Common prefix (telecom)
320 cc_digits + # Country Code on 2/3 digits
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200321 plmn_digits # MCC/MNC on 5/6 digits
Sylvain Munaut76504e02010-12-07 00:24:32 +0100322 )
323
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100324 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100325
326 if opts.secret is None:
327 # The raw number
328 iccid += ('%%0%dd' % ml) % opts.num
329 else:
330 # Randomized digits
331 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
332
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100333 # Add checksum digit
334 iccid += ('%1d' % calculate_luhn(iccid))
335
Sylvain Munaut76504e02010-12-07 00:24:32 +0100336 # IMSI (15 digits usually)
337 if opts.imsi is not None:
338 imsi = opts.imsi
339 if not _isnum(imsi):
340 raise ValueError('IMSI must be digits only !')
341
342 else:
343 if opts.num is None:
344 raise ValueError('Neither IMSI nor card number specified !')
345
346 ml = 15 - len(plmn_digits)
347
348 if opts.secret is None:
349 # The raw number
350 msin = ('%%0%dd' % ml) % opts.num
351 else:
352 # Randomized digits
353 msin = _digits(opts.secret, 'imsi', ml, opts.num)
354
355 imsi = (
356 plmn_digits + # MCC/MNC on 5/6 digits
357 msin # MSIN
358 )
359
360 # SMSP
361 if opts.smsp is not None:
362 smsp = opts.smsp
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100363 if not _ishex(smsp):
364 raise ValueError('SMSP must be hex digits only !')
365 if len(smsp) < 28*2:
366 raise ValueError('SMSP must be at least 28 bytes')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100367
368 else:
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200369 ton = "81"
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100370 if opts.smsc is not None:
371 smsc = opts.smsc
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200372 if smsc[0] == '+':
373 ton = "91"
374 smsc = smsc[1:]
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100375 if not _isnum(smsc):
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200376 raise ValueError('SMSC must be digits only!\n \
377 Start with \'+\' for international numbers')
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100378 else:
379 smsc = '00%d' % opts.country + '5555' # Hack ...
380
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200381 smsc = '%02d' % ((len(smsc) + 3)//2,) + ton + swap_nibbles(rpad(smsc, 20))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100382
383 smsp = (
384 'e1' + # Parameters indicator
385 'ff' * 12 + # TP-Destination address
386 smsc + # TP-Service Centre Address
387 '00' + # TP-Protocol identifier
388 '00' + # TP-Data coding scheme
389 '00' # TP-Validity period
390 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100391
Alexander Chemeris21885242013-07-02 16:56:55 +0400392 # ACC
393 if opts.acc is not None:
394 acc = opts.acc
395 if not _ishex(acc):
396 raise ValueError('ACC must be hex digits only !')
397 if len(acc) != 2*2:
398 raise ValueError('ACC must be exactly 2 bytes')
399
400 else:
401 acc = None
402
Sylvain Munaut76504e02010-12-07 00:24:32 +0100403 # Ki (random)
404 if opts.ki is not None:
405 ki = opts.ki
406 if not re.match('^[0-9a-fA-F]{32}$', ki):
407 raise ValueError('Ki needs to be 128 bits, in hex format')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100408 else:
409 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
410
Alexander Chemerisd17ca3d2017-07-18 16:40:58 +0300411 # OPC (random)
Harald Welte93b38cd2012-03-22 14:31:36 +0100412 if opts.opc is not None:
413 opc = opts.opc
414 if not re.match('^[0-9a-fA-F]{32}$', opc):
415 raise ValueError('OPC needs to be 128 bits, in hex format')
416
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100417 elif opts.op is not None:
418 opc = derive_milenage_opc(ki, opts.op)
Harald Welte93b38cd2012-03-22 14:31:36 +0100419 else:
420 opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
421
Philipp Maiere8536c02020-05-11 21:35:01 +0200422 pin_adm = sanitize_pin_adm(opts)
Harald Welte93b38cd2012-03-22 14:31:36 +0100423
Sylvain Munaut76504e02010-12-07 00:24:32 +0100424 # Return that
425 return {
426 'name' : opts.name,
427 'iccid' : iccid,
428 'mcc' : mcc,
429 'mnc' : mnc,
430 'imsi' : imsi,
431 'smsp' : smsp,
432 'ki' : ki,
Harald Welte93b38cd2012-03-22 14:31:36 +0100433 'opc' : opc,
Alexander Chemeris21885242013-07-02 16:56:55 +0400434 'acc' : acc,
Jan Balkec3ebd332015-01-26 12:22:55 +0100435 'pin_adm' : pin_adm,
Supreeth Herle5a541012019-12-22 08:59:16 +0100436 'msisdn' : opts.msisdn,
Sylvain Munaut76504e02010-12-07 00:24:32 +0100437 }
438
439
440def print_parameters(params):
441
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200442 s = ["Generated card parameters :"]
443 if 'name' in params:
444 s.append(" > Name : %(name)s")
445 if 'smsp' in params:
446 s.append(" > SMSP : %(smsp)s")
447 s.append(" > ICCID : %(iccid)s")
Philipp Maierbe069e22019-09-12 12:52:43 +0200448 s.append(" > MCC/MNC : %(mcc)s/%(mnc)s")
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200449 s.append(" > IMSI : %(imsi)s")
450 s.append(" > Ki : %(ki)s")
451 s.append(" > OPC : %(opc)s")
452 if 'acc' in params:
453 s.append(" > ACC : %(acc)s")
454 s.append(" > ADM1(hex): %(pin_adm)s")
455 print("\n".join(s) % params)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100456
457
Harald Welte130524b2012-08-13 15:53:43 +0200458def write_params_csv(opts, params):
459 # csv
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100460 if opts.write_csv:
461 import csv
Harald Welte93b38cd2012-03-22 14:31:36 +0100462 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100463 f = open(opts.write_csv, 'a')
464 cw = csv.writer(f)
465 cw.writerow([params[x] for x in row])
466 f.close()
467
Daniel Willmann164b9632019-09-03 19:13:51 +0200468def _read_params_csv(opts, iccid=None, imsi=None):
Harald Welte7f62cec2012-08-13 20:07:41 +0200469 import csv
Harald Welte7f62cec2012-08-13 20:07:41 +0200470 f = open(opts.read_csv, 'r')
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200471 cr = csv.DictReader(f)
Philipp Maier120a0002019-09-12 13:11:45 +0200472
473 # Lower-case fieldnames
474 cr.fieldnames = [ field.lower() for field in cr.fieldnames ]
475
Harald Welte7f62cec2012-08-13 20:07:41 +0200476 i = 0
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200477 if not 'iccid' in cr.fieldnames:
478 raise Exception("CSV file in wrong format!")
Harald Welte7f62cec2012-08-13 20:07:41 +0200479 for row in cr:
Daniel Willmann164b9632019-09-03 19:13:51 +0200480 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 +0200481 if opts.num == i:
Harald Weltec26b8292012-08-15 15:25:51 +0200482 f.close()
483 return row;
484 i += 1
Daniel Willmann164b9632019-09-03 19:13:51 +0200485 if row['iccid'] == iccid:
486 f.close()
487 return row;
488
Harald Welte7f62cec2012-08-13 20:07:41 +0200489 if row['imsi'] == imsi:
Harald Weltec26b8292012-08-15 15:25:51 +0200490 f.close()
491 return row;
Harald Welte7f62cec2012-08-13 20:07:41 +0200492
493 f.close()
Harald Weltec26b8292012-08-15 15:25:51 +0200494 return None
495
Daniel Willmann164b9632019-09-03 19:13:51 +0200496def read_params_csv(opts, imsi=None, iccid=None):
497 row = _read_params_csv(opts, iccid=iccid, imsi=imsi)
Harald Weltec26b8292012-08-15 15:25:51 +0200498 if row is not None:
Philipp Maier7592eee2019-09-12 13:03:23 +0200499 row['mcc'] = row.get('mcc', mcc_from_imsi(row.get('imsi')))
500 row['mnc'] = row.get('mnc', mnc_from_imsi(row.get('imsi')))
501
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200502 pin_adm = None
503 # We need to escape the pin_adm we get from the csv
504 if 'pin_adm' in row:
505 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['pin_adm']])
506 # Stay compatible to the odoo csv format
507 elif 'adm1' in row:
508 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['adm1']])
509 if pin_adm:
510 row['pin_adm'] = rpad(pin_adm, 16)
Philipp Maiere053da52019-09-05 13:08:36 +0200511
512 # If the CSV-File defines a pin_adm_hex field use this field to
513 # generate pin_adm from that.
514 pin_adm_hex = row.get('pin_adm_hex')
515 if pin_adm_hex:
516 if len(pin_adm_hex) == 16:
517 row['pin_adm'] = pin_adm_hex
518 # Ensure that it's hex-encoded
519 try:
520 try_encode = h2b(pin_adm)
521 except ValueError:
522 raise ValueError("pin_adm_hex needs to be hex encoded using this option")
523 else:
524 raise ValueError("pin_adm_hex needs to be exactly 16 digits (hex encoded)")
525
Harald Welte7f62cec2012-08-13 20:07:41 +0200526 return row
527
Harald Weltec26b8292012-08-15 15:25:51 +0200528
Harald Welte130524b2012-08-13 15:53:43 +0200529def write_params_hlr(opts, params):
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100530 # SQLite3 OpenBSC HLR
531 if opts.write_hlr:
532 import sqlite3
533 conn = sqlite3.connect(opts.write_hlr)
534
535 c = conn.execute(
536 'INSERT INTO Subscriber ' +
537 '(imsi, name, extension, authorized, created, updated) ' +
538 'VALUES ' +
539 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
540 [
541 params['imsi'],
542 params['name'],
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200543 '9' + params['iccid'][-5:-1]
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100544 ],
545 )
546 sub_id = c.lastrowid
547 c.close()
548
549 c = conn.execute(
550 'INSERT INTO AuthKeys ' +
551 '(subscriber_id, algorithm_id, a3a8_ki)' +
552 'VALUES ' +
553 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100554 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100555 )
556
557 conn.commit()
558 conn.close()
559
Harald Welte130524b2012-08-13 15:53:43 +0200560def write_parameters(opts, params):
561 write_params_csv(opts, params)
Harald Welte7f62cec2012-08-13 20:07:41 +0200562 write_params_hlr(opts, params)
Harald Welte130524b2012-08-13 15:53:43 +0200563
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100564
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100565BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
566BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100567
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100568def init_batch(opts):
569 # Need to do something ?
570 if not opts.batch_mode:
571 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100572
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100573 for k in BATCH_INCOMPATIBLE:
574 if getattr(opts, k):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700575 print("Incompatible option with batch_state: %s" % (k,))
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100576 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100577
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100578 # Don't load state if there is none ...
579 if not opts.batch_state:
580 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100581
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100582 if not os.path.isfile(opts.batch_state):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700583 print("No state file yet")
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100584 return
585
586 # Get stored data
587 fh = open(opts.batch_state)
588 d = json.loads(fh.read())
589 fh.close()
590
591 for k,v in d.iteritems():
592 setattr(opts, k, v)
593
594
595def save_batch(opts):
596 # Need to do something ?
597 if not opts.batch_mode or not opts.batch_state:
598 return
599
600 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
601 fh = open(opts.batch_state, 'w')
602 fh.write(d)
603 fh.close()
604
605
Philipp Maierc5b422e2019-08-30 11:41:02 +0200606def process_card(opts, first, card_handler):
607
608 if opts.dry_run is False:
609 # Connect transport
610 card_handler.get(first)
611
612 if opts.dry_run is False:
613 # Get card
Supreeth Herle4c306ab2020-03-18 11:38:00 +0100614 card = card_detect(opts.type, scc)
Philipp Maierc5b422e2019-08-30 11:41:02 +0200615 if card is None:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700616 print("No card detected!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200617 return -1
618
619 # Probe only
620 if opts.probe:
621 return 0
622
623 # Erase if requested
624 if opts.erase:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700625 print("Formatting ...")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200626 card.erase()
627 card.reset()
628
629 # Generate parameters
630 if opts.source == 'cmdline':
631 cp = gen_parameters(opts)
632 elif opts.source == 'csv':
633 imsi = None
634 iccid = None
635 if opts.read_iccid:
636 if opts.dry_run:
637 # Connect transport
638 card_handler.get(false)
639 (res,_) = scc.read_binary(['3f00', '2fe2'], length=10)
640 iccid = dec_iccid(res)
641 elif opts.read_imsi:
642 if opts.dry_run:
643 # Connect transport
644 card_handler.get(false)
645 (res,_) = scc.read_binary(EF['IMSI'])
646 imsi = swap_nibbles(res)[3:]
647 else:
648 imsi = opts.imsi
649 cp = read_params_csv(opts, imsi=imsi, iccid=iccid)
650 if cp is None:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700651 print("Error reading parameters from CSV file!\n")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200652 return 2
653 print_parameters(cp)
654
655 if opts.dry_run is False:
656 # Program the card
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700657 print("Programming ...")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200658 card.program(cp)
659 else:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700660 print("Dry Run: NOT PROGRAMMING!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200661
662 # Write parameters permanently
663 write_parameters(opts, cp)
664
665 # Batch mode state update and save
666 if opts.num is not None:
667 opts.num += 1
668 save_batch(opts)
669
670 card_handler.done()
671 return 0
672
673
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100674if __name__ == '__main__':
675
676 # Parse options
677 opts = parse_options()
678
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700679 # Init card reader driver
Philipp Maierff84c232020-05-12 17:24:18 +0200680 sl = init_reader(opts)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100681
682 # Create command layer
683 scc = SimCardCommands(transport=sl)
684
Philipp Maier196b08c2019-09-12 11:49:44 +0200685 # If we use a CSV file as data input, check if the CSV file exists.
686 if opts.source == 'csv':
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700687 print("Using CSV file as data input: " + str(opts.read_csv))
Philipp Maier196b08c2019-09-12 11:49:44 +0200688 if not os.path.isfile(opts.read_csv):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700689 print("CSV file not found!")
Philipp Maier196b08c2019-09-12 11:49:44 +0200690 sys.exit(1)
691
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100692 # Batch mode init
693 init_batch(opts)
694
Philipp Maierc5b422e2019-08-30 11:41:02 +0200695 if opts.card_handler:
696 card_handler = card_handler_auto(sl, opts.card_handler)
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200697 else:
Philipp Maierc5b422e2019-08-30 11:41:02 +0200698 card_handler = card_handler(sl)
699
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100700 # Iterate
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100701 first = True
702 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100703
Philipp Maierc5b422e2019-08-30 11:41:02 +0200704 while 1:
705 try:
706 rc = process_card(opts, first, card_handler)
707 except (KeyboardInterrupt):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700708 print("")
709 print("Terminated by user!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200710 sys.exit(0)
711 except (SystemExit):
712 raise
713 except:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700714 print("")
715 print("Card programming failed with an execption:")
716 print("---------------------8<---------------------")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200717 traceback.print_exc()
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700718 print("---------------------8<---------------------")
719 print("")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200720 rc = -1
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200721
Philipp Maierc5b422e2019-08-30 11:41:02 +0200722 # Something did not work as well as expected, however, lets
723 # make sure the card is pulled from the reader.
724 if rc != 0:
725 card_handler.error()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100726
Philipp Maierc5b422e2019-08-30 11:41:02 +0200727 # If we are not in batch mode we are done in any case, so lets
728 # exit here.
729 if not opts.batch_mode:
730 sys.exit(rc)
731
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100732 first = False