blob: 7b1283b883febb21bd874e9a3284ecab57085123 [file] [log] [blame]
Daniel Willmannde07b952020-10-19 10:32:34 +02001#!/usr/bin/env python3
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
Denis 'GNUtoo' Carikli79f5b602020-02-15 04:02:57 +070034import json
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +010035
Sylvain Munaut76504e02010-12-07 00:24:32 +010036from pySim.commands import SimCardCommands
Harald Welte6e0458d2021-04-03 11:52:37 +020037from pySim.transport import init_reader
Supreeth Herle4c306ab2020-03-18 11:38:00 +010038from pySim.cards import _cards_classes, card_detect
Harald Welte6e0458d2021-04-03 11:52:37 +020039from pySim.utils import h2b, swap_nibbles, rpad, derive_milenage_opc, calculate_luhn, dec_iccid
Philipp Maierf7792312018-06-11 17:11:39 +020040from pySim.ts_51_011 import EF
Philipp Maierc5b422e2019-08-30 11:41:02 +020041from pySim.card_handler import *
Philipp Maier7592eee2019-09-12 13:03:23 +020042from pySim.utils import *
Sylvain Munaut76504e02010-12-07 00:24:32 +010043
44def parse_options():
45
46 parser = OptionParser(usage="usage: %prog [options]")
47
48 parser.add_option("-d", "--device", dest="device", metavar="DEV",
49 help="Serial Device for SIM access [default: %default]",
50 default="/dev/ttyUSB0",
51 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010052 parser.add_option("-b", "--baud", dest="baudrate", type="int", metavar="BAUD",
53 help="Baudrate used for SIM access [default: %default]",
54 default=9600,
55 )
Sylvain Munaut9c8729a2010-12-08 23:20:27 +010056 parser.add_option("-p", "--pcsc-device", dest="pcsc_dev", type='int', metavar="PCSC",
Sylvain Munaute9fdecb2010-12-08 22:33:19 +010057 help="Which PC/SC reader number for SIM access",
58 default=None,
59 )
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070060 parser.add_option("--modem-device", dest="modem_dev", metavar="DEV",
61 help="Serial port of modem for Generic SIM Access (3GPP TS 27.007)",
62 default=None,
63 )
64 parser.add_option("--modem-baud", dest="modem_baud", type="int", metavar="BAUD",
65 help="Baudrate used for modem's port [default: %default]",
66 default=115200,
67 )
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +070068 parser.add_option("--osmocon", dest="osmocon_sock", metavar="PATH",
69 help="Socket path for Calypso (e.g. Motorola C1XX) based reader (via OsmocomBB)",
70 default=None,
71 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010072 parser.add_option("-t", "--type", dest="type",
73 help="Card type (user -t list to view) [default: %default]",
74 default="auto",
75 )
Philipp Maierac9dde62018-07-04 11:05:14 +020076 parser.add_option("-T", "--probe", dest="probe",
77 help="Determine card type",
78 default=False, action="store_true"
79 )
Jan Balkec3ebd332015-01-26 12:22:55 +010080 parser.add_option("-a", "--pin-adm", dest="pin_adm",
81 help="ADM PIN used for provisioning (overwrites default)",
82 )
Daniel Willmannf432b2b2018-06-15 07:31:50 +020083 parser.add_option("-A", "--pin-adm-hex", dest="pin_adm_hex",
84 help="ADM PIN used for provisioning, as hex string (16 characters long",
85 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010086 parser.add_option("-e", "--erase", dest="erase", action='store_true',
87 help="Erase beforehand [default: %default]",
88 default=False,
89 )
90
Harald Welte7f62cec2012-08-13 20:07:41 +020091 parser.add_option("-S", "--source", dest="source",
92 help="Data Source[default: %default]",
93 default="cmdline",
94 )
95
96 # if mode is "cmdline"
Sylvain Munaut76504e02010-12-07 00:24:32 +010097 parser.add_option("-n", "--name", dest="name",
98 help="Operator name [default: %default]",
99 default="Magic",
100 )
101 parser.add_option("-c", "--country", dest="country", type="int", metavar="CC",
102 help="Country code [default: %default]",
103 default=1,
104 )
Harald Welte7f1d3c42020-05-12 21:12:44 +0200105 parser.add_option("-x", "--mcc", dest="mcc", type="string",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100106 help="Mobile Country Code [default: %default]",
Harald Welte7f1d3c42020-05-12 21:12:44 +0200107 default="901",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100108 )
Harald Welte7f1d3c42020-05-12 21:12:44 +0200109 parser.add_option("-y", "--mnc", dest="mnc", type="string",
Sylvain Munaut17716032010-12-08 22:33:51 +0100110 help="Mobile Network Code [default: %default]",
Harald Welte7f1d3c42020-05-12 21:12:44 +0200111 default="55",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100112 )
Supreeth Herlefc83e432020-05-06 11:48:46 +0200113 parser.add_option("--mnclen", dest="mnclen", type="choice",
114 help="Length of Mobile Network Code [default: %default]",
115 default=2,
116 choices=[2, 3],
117 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100118 parser.add_option("-m", "--smsc", dest="smsc",
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200119 help="SMSC number (Start with + for international no.) [default: '00 + country code + 5555']",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100120 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100121 parser.add_option("-M", "--smsp", dest="smsp",
122 help="Raw SMSP content in hex [default: auto from SMSC]",
123 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100124
125 parser.add_option("-s", "--iccid", dest="iccid", metavar="ID",
126 help="Integrated Circuit Card ID",
127 )
128 parser.add_option("-i", "--imsi", dest="imsi",
129 help="International Mobile Subscriber Identity",
130 )
Supreeth Herle5a541012019-12-22 08:59:16 +0100131 parser.add_option("--msisdn", dest="msisdn",
132 help="Mobile Subscriber Integrated Services Digital Number",
133 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100134 parser.add_option("-k", "--ki", dest="ki",
135 help="Ki (default is to randomize)",
136 )
Harald Welte93b38cd2012-03-22 14:31:36 +0100137 parser.add_option("-o", "--opc", dest="opc",
138 help="OPC (default is to randomize)",
139 )
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100140 parser.add_option("--op", dest="op",
141 help="Set OP to derive OPC from OP and KI",
142 )
Alexander Chemeris21885242013-07-02 16:56:55 +0400143 parser.add_option("--acc", dest="acc",
144 help="Set ACC bits (Access Control Code). not all card types are supported",
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200145 )
Supreeth Herle8e0fccd2020-03-23 12:10:56 +0100146 parser.add_option("--epdgid", dest="epdgid",
147 help="Set Home Evolved Packet Data Gateway (ePDG) Identifier. (Only FQDN format supported)",
148 )
Supreeth Herlef964df42020-03-24 13:15:37 +0100149 parser.add_option("--epdgSelection", dest="epdgSelection",
150 help="Set PLMN for ePDG Selection Information. (Only Operator Identifier FQDN format supported)",
151 )
Supreeth Herlecf727f22020-03-24 17:32:21 +0100152 parser.add_option("--pcscf", dest="pcscf",
153 help="Set Proxy Call Session Control Function (P-CSCF) Address. (Only FQDN format supported)",
154 )
Supreeth Herle79f43dd2020-03-25 11:43:19 +0100155 parser.add_option("--ims-hdomain", dest="ims_hdomain",
156 help="Set IMS Home Network Domain Name in FQDN format",
157 )
Supreeth Herlea5bd9682020-03-26 09:16:14 +0100158 parser.add_option("--impi", dest="impi",
159 help="Set IMS private user identity",
160 )
Supreeth Herlebe7007e2020-03-26 09:27:45 +0100161 parser.add_option("--impu", dest="impu",
162 help="Set IMS public user identity",
163 )
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200164 parser.add_option("--read-imsi", dest="read_imsi", action="store_true",
165 help="Read the IMSI from the CARD", default=False
Alexander Chemeris21885242013-07-02 16:56:55 +0400166 )
Daniel Willmann164b9632019-09-03 19:13:51 +0200167 parser.add_option("--read-iccid", dest="read_iccid", action="store_true",
168 help="Read the ICCID from the CARD", default=False
169 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100170 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
171 help="Secret used for ICCID/IMSI autogen",
172 )
173 parser.add_option("-j", "--num", dest="num", type=int,
174 help="Card # used for ICCID/IMSI autogen",
175 )
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100176 parser.add_option("--batch", dest="batch_mode",
177 help="Enable batch mode [default: %default]",
178 default=False, action='store_true',
179 )
180 parser.add_option("--batch-state", dest="batch_state", metavar="FILE",
181 help="Optional batch state file",
182 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100183
Harald Welte7f62cec2012-08-13 20:07:41 +0200184 # if mode is "csv"
185 parser.add_option("--read-csv", dest="read_csv", metavar="FILE",
186 help="Read parameters from CSV file rather than command line")
187
188
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100189 parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
190 help="Append generated parameters in CSV file",
191 )
192 parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
193 help="Append generated parameters to OpenBSC HLR sqlite3",
194 )
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200195 parser.add_option("--dry-run", dest="dry_run",
196 help="Perform a 'dry run', don't actually program the card",
197 default=False, action="store_true")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200198 parser.add_option("--card_handler", dest="card_handler", metavar="FILE",
199 help="Use automatic card handling machine")
200
Sylvain Munaut76504e02010-12-07 00:24:32 +0100201 (options, args) = parser.parse_args()
202
203 if options.type == 'list':
204 for kls in _cards_classes:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700205 print(kls.name)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100206 sys.exit(0)
207
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200208 if options.probe:
209 return options
Philipp Maierac9dde62018-07-04 11:05:14 +0200210
Harald Welte7f62cec2012-08-13 20:07:41 +0200211 if options.source == 'csv':
Daniel Willmann164b9632019-09-03 19:13:51 +0200212 if (options.imsi is None) and (options.batch_mode is False) and (options.read_imsi is False) and (options.read_iccid is False):
213 parser.error("CSV mode needs either an IMSI, --read-imsi, --read-iccid or batch mode")
Harald Welte7f62cec2012-08-13 20:07:41 +0200214 if options.read_csv is None:
215 parser.error("CSV mode requires a CSV input file")
216 elif options.source == 'cmdline':
217 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
218 parser.error("If either IMSI or ICCID isn't specified, num is required")
219 else:
220 parser.error("Only `cmdline' and `csv' sources supported")
221
222 if (options.read_csv is not None) and (options.source != 'csv'):
223 parser.error("You cannot specify a CSV input file in source != csv")
224
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100225 if (options.batch_mode) and (options.num is None):
226 options.num = 0
227
Sylvain Munaut98d2b852010-12-23 20:27:25 +0100228 if (options.batch_mode):
229 if (options.imsi is not None) or (options.iccid is not None):
230 parser.error("Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more informations")
231
Sylvain Munaut76504e02010-12-07 00:24:32 +0100232 if args:
233 parser.error("Extraneous arguments")
234
235 return options
236
237
238def _digits(secret, usage, len, num):
Jeremy Herbert3b00dbf2020-10-25 20:56:05 +1000239 seed = secret + usage + '%d' % num
240 s = hashlib.sha1(seed.encode())
241 d = ''.join(['%02d' % x for x in s.digest()])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100242 return d[0:len]
243
244def _mcc_mnc_digits(mcc, mnc):
Harald Welte7f1d3c42020-05-12 21:12:44 +0200245 return '%s%s' % (mcc, mnc)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100246
247def _cc_digits(cc):
248 return ('%03d' if cc > 100 else '%02d') % cc
249
250def _isnum(s, l=-1):
251 return s.isdigit() and ((l== -1) or (len(s) == l))
252
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100253def _ishex(s, l=-1):
254 hc = '0123456789abcdef'
255 return all([x in hc for x in s.lower()]) and ((l== -1) or (len(s) == l))
256
Sylvain Munaut76504e02010-12-07 00:24:32 +0100257
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100258def _dbi_binary_quote(s):
259 # Count usage of each char
260 cnt = {}
261 for c in s:
262 cnt[c] = cnt.get(c, 0) + 1
263
264 # Find best offset
265 e = 0
266 m = len(s)
267 for i in range(1, 256):
268 if i == 39:
269 continue
270 sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
271 if sum_ < m:
272 m = sum_
273 e = i
274 if m == 0: # No overhead ? use this !
Daniel Willmann677d41b2020-10-19 10:34:31 +0200275 break
Sylvain Munaut1a914432011-12-08 20:08:26 +0100276
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100277 # Generate output
278 out = []
279 out.append( chr(e) ) # Offset
280 for c in s:
281 x = (256 + ord(c) - e) % 256
282 if x in (0, 1, 39):
283 out.append('\x01')
284 out.append(chr(x+1))
285 else:
286 out.append(chr(x))
287
288 return ''.join(out)
289
Sylvain Munaut76504e02010-12-07 00:24:32 +0100290def gen_parameters(opts):
Jan Balkec3ebd332015-01-26 12:22:55 +0100291 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki, PIN-ADM from the
Sylvain Munaut76504e02010-12-07 00:24:32 +0100292 options given by the user"""
293
294 # MCC/MNC
295 mcc = opts.mcc
296 mnc = opts.mnc
297
Harald Welte7f1d3c42020-05-12 21:12:44 +0200298 if not mcc.isdigit() or not mnc.isdigit():
299 raise ValueError('mcc & mnc must only contain decimal digits')
300 if len(mcc) < 1 or len(mcc) > 3:
301 raise ValueError('mcc must be between 1 .. 3 digits')
302 if len(mnc) < 1 or len(mnc) > 3:
303 raise ValueError('mnc must be between 1 .. 3 digits')
304
305 # MCC always has 3 digits
306 mcc = lpad(mcc, 3, "0")
307 # MNC must be at least 2 digits
308 mnc = lpad(mnc, 2, "0")
Sylvain Munaut76504e02010-12-07 00:24:32 +0100309
310 # Digitize country code (2 or 3 digits)
311 cc_digits = _cc_digits(opts.country)
312
313 # Digitize MCC/MNC (5 or 6 digits)
314 plmn_digits = _mcc_mnc_digits(mcc, mnc)
315
Supreeth Herle840a9e22020-01-21 13:32:46 +0100316 if opts.name is not None:
317 if len(opts.name) > 16:
Daniel Willmann677d41b2020-10-19 10:34:31 +0200318 raise ValueError('Service Provider Name must max 16 characters!')
Supreeth Herle840a9e22020-01-21 13:32:46 +0100319
Supreeth Herle5a541012019-12-22 08:59:16 +0100320 if opts.msisdn is not None:
321 msisdn = opts.msisdn
322 if msisdn[0] == '+':
323 msisdn = msisdn[1:]
324 if not msisdn.isdigit():
325 raise ValueError('MSISDN must be digits only! '
326 'Start with \'+\' for international numbers.')
327 if len(msisdn) > 10 * 2:
328 # TODO: Support MSISDN of length > 20 (10 Bytes)
329 raise ValueError('MSISDNs longer than 20 digits are not (yet) supported.')
330
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100331 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
Sylvain Munaut76504e02010-12-07 00:24:32 +0100332 if opts.iccid is not None:
333 iccid = opts.iccid
Todd Neal9eeadfc2018-04-25 15:36:29 -0500334 if not _isnum(iccid, 19) and not _isnum(iccid, 20):
Daniel Willmann677d41b2020-10-19 10:34:31 +0200335 raise ValueError('ICCID must be 19 or 20 digits !')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100336
337 else:
338 if opts.num is None:
339 raise ValueError('Neither ICCID nor card number specified !')
340
341 iccid = (
342 '89' + # Common prefix (telecom)
343 cc_digits + # Country Code on 2/3 digits
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200344 plmn_digits # MCC/MNC on 5/6 digits
Sylvain Munaut76504e02010-12-07 00:24:32 +0100345 )
346
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100347 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100348
349 if opts.secret is None:
350 # The raw number
351 iccid += ('%%0%dd' % ml) % opts.num
352 else:
353 # Randomized digits
354 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
355
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100356 # Add checksum digit
357 iccid += ('%1d' % calculate_luhn(iccid))
358
Sylvain Munaut76504e02010-12-07 00:24:32 +0100359 # IMSI (15 digits usually)
360 if opts.imsi is not None:
361 imsi = opts.imsi
362 if not _isnum(imsi):
363 raise ValueError('IMSI must be digits only !')
364
365 else:
366 if opts.num is None:
367 raise ValueError('Neither IMSI nor card number specified !')
368
369 ml = 15 - len(plmn_digits)
370
371 if opts.secret is None:
372 # The raw number
373 msin = ('%%0%dd' % ml) % opts.num
374 else:
375 # Randomized digits
376 msin = _digits(opts.secret, 'imsi', ml, opts.num)
377
378 imsi = (
379 plmn_digits + # MCC/MNC on 5/6 digits
380 msin # MSIN
381 )
382
383 # SMSP
384 if opts.smsp is not None:
385 smsp = opts.smsp
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100386 if not _ishex(smsp):
387 raise ValueError('SMSP must be hex digits only !')
388 if len(smsp) < 28*2:
389 raise ValueError('SMSP must be at least 28 bytes')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100390
391 else:
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200392 ton = "81"
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100393 if opts.smsc is not None:
394 smsc = opts.smsc
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200395 if smsc[0] == '+':
396 ton = "91"
397 smsc = smsc[1:]
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100398 if not _isnum(smsc):
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200399 raise ValueError('SMSC must be digits only!\n \
400 Start with \'+\' for international numbers')
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100401 else:
402 smsc = '00%d' % opts.country + '5555' # Hack ...
403
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200404 smsc = '%02d' % ((len(smsc) + 3)//2,) + ton + swap_nibbles(rpad(smsc, 20))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100405
406 smsp = (
407 'e1' + # Parameters indicator
408 'ff' * 12 + # TP-Destination address
409 smsc + # TP-Service Centre Address
410 '00' + # TP-Protocol identifier
411 '00' + # TP-Data coding scheme
412 '00' # TP-Validity period
413 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100414
Alexander Chemeris21885242013-07-02 16:56:55 +0400415 # ACC
416 if opts.acc is not None:
417 acc = opts.acc
418 if not _ishex(acc):
419 raise ValueError('ACC must be hex digits only !')
420 if len(acc) != 2*2:
421 raise ValueError('ACC must be exactly 2 bytes')
422
423 else:
424 acc = None
425
Sylvain Munaut76504e02010-12-07 00:24:32 +0100426 # Ki (random)
427 if opts.ki is not None:
428 ki = opts.ki
429 if not re.match('^[0-9a-fA-F]{32}$', ki):
430 raise ValueError('Ki needs to be 128 bits, in hex format')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100431 else:
432 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
433
Alexander Chemerisd17ca3d2017-07-18 16:40:58 +0300434 # OPC (random)
Harald Welte93b38cd2012-03-22 14:31:36 +0100435 if opts.opc is not None:
436 opc = opts.opc
437 if not re.match('^[0-9a-fA-F]{32}$', opc):
438 raise ValueError('OPC needs to be 128 bits, in hex format')
439
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100440 elif opts.op is not None:
441 opc = derive_milenage_opc(ki, opts.op)
Harald Welte93b38cd2012-03-22 14:31:36 +0100442 else:
443 opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
444
Harald Welte79b5ba42021-01-08 21:22:38 +0100445 pin_adm = sanitize_pin_adm(opts.pin_adm, opts.pin_adm_hex)
Harald Welte93b38cd2012-03-22 14:31:36 +0100446
Supreeth Herlef964df42020-03-24 13:15:37 +0100447 # ePDG Selection Information
448 if opts.epdgSelection:
449 if len(opts.epdgSelection) < 5 or len(opts.epdgSelection) > 6:
450 raise ValueError('ePDG Selection Information is not valid')
451 epdg_mcc = opts.epdgSelection[:3]
452 epdg_mnc = opts.epdgSelection[3:]
453 if not epdg_mcc.isdigit() or not epdg_mnc.isdigit():
454 raise ValueError('PLMN for ePDG Selection must only contain decimal digits')
455
Sylvain Munaut76504e02010-12-07 00:24:32 +0100456 # Return that
457 return {
458 'name' : opts.name,
459 'iccid' : iccid,
460 'mcc' : mcc,
461 'mnc' : mnc,
462 'imsi' : imsi,
463 'smsp' : smsp,
464 'ki' : ki,
Harald Welte93b38cd2012-03-22 14:31:36 +0100465 'opc' : opc,
Alexander Chemeris21885242013-07-02 16:56:55 +0400466 'acc' : acc,
Jan Balkec3ebd332015-01-26 12:22:55 +0100467 'pin_adm' : pin_adm,
Supreeth Herle5a541012019-12-22 08:59:16 +0100468 'msisdn' : opts.msisdn,
Supreeth Herle8e0fccd2020-03-23 12:10:56 +0100469 'epdgid' : opts.epdgid,
Supreeth Herlef964df42020-03-24 13:15:37 +0100470 'epdgSelection' : opts.epdgSelection,
Supreeth Herlecf727f22020-03-24 17:32:21 +0100471 'pcscf' : opts.pcscf,
Supreeth Herle79f43dd2020-03-25 11:43:19 +0100472 'ims_hdomain': opts.ims_hdomain,
Supreeth Herlebe7007e2020-03-26 09:27:45 +0100473 'impi' : opts.impi,
474 'impu' : opts.impu,
Sylvain Munaut76504e02010-12-07 00:24:32 +0100475 }
476
477
478def print_parameters(params):
479
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200480 s = ["Generated card parameters :"]
481 if 'name' in params:
482 s.append(" > Name : %(name)s")
483 if 'smsp' in params:
484 s.append(" > SMSP : %(smsp)s")
485 s.append(" > ICCID : %(iccid)s")
Philipp Maierbe069e22019-09-12 12:52:43 +0200486 s.append(" > MCC/MNC : %(mcc)s/%(mnc)s")
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200487 s.append(" > IMSI : %(imsi)s")
488 s.append(" > Ki : %(ki)s")
489 s.append(" > OPC : %(opc)s")
490 if 'acc' in params:
491 s.append(" > ACC : %(acc)s")
492 s.append(" > ADM1(hex): %(pin_adm)s")
493 print("\n".join(s) % params)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100494
495
Harald Welte130524b2012-08-13 15:53:43 +0200496def write_params_csv(opts, params):
497 # csv
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100498 if opts.write_csv:
499 import csv
Harald Welte93b38cd2012-03-22 14:31:36 +0100500 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100501 f = open(opts.write_csv, 'a')
502 cw = csv.writer(f)
503 cw.writerow([params[x] for x in row])
504 f.close()
505
Daniel Willmann164b9632019-09-03 19:13:51 +0200506def _read_params_csv(opts, iccid=None, imsi=None):
Harald Welte7f62cec2012-08-13 20:07:41 +0200507 import csv
Harald Welte7f62cec2012-08-13 20:07:41 +0200508 f = open(opts.read_csv, 'r')
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200509 cr = csv.DictReader(f)
Philipp Maier120a0002019-09-12 13:11:45 +0200510
511 # Lower-case fieldnames
512 cr.fieldnames = [ field.lower() for field in cr.fieldnames ]
513
Harald Welte7f62cec2012-08-13 20:07:41 +0200514 i = 0
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200515 if not 'iccid' in cr.fieldnames:
516 raise Exception("CSV file in wrong format!")
Harald Welte7f62cec2012-08-13 20:07:41 +0200517 for row in cr:
Daniel Willmann164b9632019-09-03 19:13:51 +0200518 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 +0200519 if opts.num == i:
Harald Weltec26b8292012-08-15 15:25:51 +0200520 f.close()
Daniel Willmann677d41b2020-10-19 10:34:31 +0200521 return row
Harald Weltec26b8292012-08-15 15:25:51 +0200522 i += 1
Daniel Willmann164b9632019-09-03 19:13:51 +0200523 if row['iccid'] == iccid:
524 f.close()
Daniel Willmann677d41b2020-10-19 10:34:31 +0200525 return row
Daniel Willmann164b9632019-09-03 19:13:51 +0200526
Harald Welte7f62cec2012-08-13 20:07:41 +0200527 if row['imsi'] == imsi:
Harald Weltec26b8292012-08-15 15:25:51 +0200528 f.close()
Daniel Willmann677d41b2020-10-19 10:34:31 +0200529 return row
Harald Welte7f62cec2012-08-13 20:07:41 +0200530
531 f.close()
Harald Weltec26b8292012-08-15 15:25:51 +0200532 return None
533
Daniel Willmann164b9632019-09-03 19:13:51 +0200534def read_params_csv(opts, imsi=None, iccid=None):
535 row = _read_params_csv(opts, iccid=iccid, imsi=imsi)
Harald Weltec26b8292012-08-15 15:25:51 +0200536 if row is not None:
Philipp Maier7592eee2019-09-12 13:03:23 +0200537 row['mcc'] = row.get('mcc', mcc_from_imsi(row.get('imsi')))
538 row['mnc'] = row.get('mnc', mnc_from_imsi(row.get('imsi')))
539
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200540 pin_adm = None
541 # We need to escape the pin_adm we get from the csv
542 if 'pin_adm' in row:
543 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['pin_adm']])
544 # Stay compatible to the odoo csv format
545 elif 'adm1' in row:
546 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['adm1']])
547 if pin_adm:
548 row['pin_adm'] = rpad(pin_adm, 16)
Philipp Maiere053da52019-09-05 13:08:36 +0200549
550 # If the CSV-File defines a pin_adm_hex field use this field to
551 # generate pin_adm from that.
552 pin_adm_hex = row.get('pin_adm_hex')
553 if pin_adm_hex:
554 if len(pin_adm_hex) == 16:
555 row['pin_adm'] = pin_adm_hex
556 # Ensure that it's hex-encoded
557 try:
558 try_encode = h2b(pin_adm)
559 except ValueError:
560 raise ValueError("pin_adm_hex needs to be hex encoded using this option")
561 else:
562 raise ValueError("pin_adm_hex needs to be exactly 16 digits (hex encoded)")
563
Harald Welte7f62cec2012-08-13 20:07:41 +0200564 return row
565
Harald Weltec26b8292012-08-15 15:25:51 +0200566
Harald Welte130524b2012-08-13 15:53:43 +0200567def write_params_hlr(opts, params):
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100568 # SQLite3 OpenBSC HLR
569 if opts.write_hlr:
570 import sqlite3
571 conn = sqlite3.connect(opts.write_hlr)
572
573 c = conn.execute(
574 'INSERT INTO Subscriber ' +
575 '(imsi, name, extension, authorized, created, updated) ' +
576 'VALUES ' +
577 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
578 [
579 params['imsi'],
580 params['name'],
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200581 '9' + params['iccid'][-5:-1]
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100582 ],
583 )
584 sub_id = c.lastrowid
585 c.close()
586
587 c = conn.execute(
588 'INSERT INTO AuthKeys ' +
589 '(subscriber_id, algorithm_id, a3a8_ki)' +
590 'VALUES ' +
591 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100592 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100593 )
594
595 conn.commit()
596 conn.close()
597
Harald Welte130524b2012-08-13 15:53:43 +0200598def write_parameters(opts, params):
599 write_params_csv(opts, params)
Harald Welte7f62cec2012-08-13 20:07:41 +0200600 write_params_hlr(opts, params)
Harald Welte130524b2012-08-13 15:53:43 +0200601
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100602
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100603BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
604BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100605
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100606def init_batch(opts):
607 # Need to do something ?
608 if not opts.batch_mode:
609 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100610
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100611 for k in BATCH_INCOMPATIBLE:
612 if getattr(opts, k):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700613 print("Incompatible option with batch_state: %s" % (k,))
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100614 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100615
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100616 # Don't load state if there is none ...
617 if not opts.batch_state:
618 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100619
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100620 if not os.path.isfile(opts.batch_state):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700621 print("No state file yet")
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100622 return
623
624 # Get stored data
625 fh = open(opts.batch_state)
626 d = json.loads(fh.read())
627 fh.close()
628
629 for k,v in d.iteritems():
630 setattr(opts, k, v)
631
632
633def save_batch(opts):
634 # Need to do something ?
635 if not opts.batch_mode or not opts.batch_state:
636 return
637
638 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
639 fh = open(opts.batch_state, 'w')
640 fh.write(d)
641 fh.close()
642
643
Philipp Maierc5b422e2019-08-30 11:41:02 +0200644def process_card(opts, first, card_handler):
645
646 if opts.dry_run is False:
647 # Connect transport
648 card_handler.get(first)
649
650 if opts.dry_run is False:
651 # Get card
Supreeth Herle4c306ab2020-03-18 11:38:00 +0100652 card = card_detect(opts.type, scc)
Philipp Maierc5b422e2019-08-30 11:41:02 +0200653 if card is None:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700654 print("No card detected!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200655 return -1
656
657 # Probe only
658 if opts.probe:
659 return 0
660
661 # Erase if requested
662 if opts.erase:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700663 print("Formatting ...")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200664 card.erase()
665 card.reset()
666
667 # Generate parameters
668 if opts.source == 'cmdline':
669 cp = gen_parameters(opts)
670 elif opts.source == 'csv':
671 imsi = None
672 iccid = None
673 if opts.read_iccid:
674 if opts.dry_run:
675 # Connect transport
Daniel Willmanndd014ea2020-10-19 10:35:11 +0200676 card_handler.get(False)
Philipp Maierc5b422e2019-08-30 11:41:02 +0200677 (res,_) = scc.read_binary(['3f00', '2fe2'], length=10)
678 iccid = dec_iccid(res)
679 elif opts.read_imsi:
680 if opts.dry_run:
681 # Connect transport
Daniel Willmanndd014ea2020-10-19 10:35:11 +0200682 card_handler.get(False)
Philipp Maierc5b422e2019-08-30 11:41:02 +0200683 (res,_) = scc.read_binary(EF['IMSI'])
684 imsi = swap_nibbles(res)[3:]
685 else:
686 imsi = opts.imsi
687 cp = read_params_csv(opts, imsi=imsi, iccid=iccid)
688 if cp is None:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700689 print("Error reading parameters from CSV file!\n")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200690 return 2
691 print_parameters(cp)
692
693 if opts.dry_run is False:
694 # Program the card
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700695 print("Programming ...")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200696 card.program(cp)
697 else:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700698 print("Dry Run: NOT PROGRAMMING!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200699
700 # Write parameters permanently
701 write_parameters(opts, cp)
702
703 # Batch mode state update and save
704 if opts.num is not None:
705 opts.num += 1
706 save_batch(opts)
707
708 card_handler.done()
709 return 0
710
711
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100712if __name__ == '__main__':
713
714 # Parse options
715 opts = parse_options()
716
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700717 # Init card reader driver
Philipp Maierff84c232020-05-12 17:24:18 +0200718 sl = init_reader(opts)
Philipp Maierc8caec22021-02-22 16:07:53 +0100719 if sl is None:
720 exit(1)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100721
722 # Create command layer
723 scc = SimCardCommands(transport=sl)
724
Philipp Maier196b08c2019-09-12 11:49:44 +0200725 # If we use a CSV file as data input, check if the CSV file exists.
726 if opts.source == 'csv':
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700727 print("Using CSV file as data input: " + str(opts.read_csv))
Philipp Maier196b08c2019-09-12 11:49:44 +0200728 if not os.path.isfile(opts.read_csv):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700729 print("CSV file not found!")
Philipp Maier196b08c2019-09-12 11:49:44 +0200730 sys.exit(1)
731
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100732 # Batch mode init
733 init_batch(opts)
734
Philipp Maierc5b422e2019-08-30 11:41:02 +0200735 if opts.card_handler:
736 card_handler = card_handler_auto(sl, opts.card_handler)
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200737 else:
Philipp Maierc5b422e2019-08-30 11:41:02 +0200738 card_handler = card_handler(sl)
739
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100740 # Iterate
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100741 first = True
742 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100743
Philipp Maierc5b422e2019-08-30 11:41:02 +0200744 while 1:
745 try:
746 rc = process_card(opts, first, card_handler)
747 except (KeyboardInterrupt):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700748 print("")
749 print("Terminated by user!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200750 sys.exit(0)
751 except (SystemExit):
752 raise
753 except:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700754 print("")
755 print("Card programming failed with an execption:")
756 print("---------------------8<---------------------")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200757 traceback.print_exc()
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700758 print("---------------------8<---------------------")
759 print("")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200760 rc = -1
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200761
Philipp Maierc5b422e2019-08-30 11:41:02 +0200762 # Something did not work as well as expected, however, lets
763 # make sure the card is pulled from the reader.
764 if rc != 0:
765 card_handler.error()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100766
Philipp Maierc5b422e2019-08-30 11:41:02 +0200767 # If we are not in batch mode we are done in any case, so lets
768 # exit here.
769 if not opts.batch_mode:
770 sys.exit(rc)
771
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100772 first = False