blob: 662824c4a1c7707c87810f754a3c7391746b9701 [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
Supreeth Herle4c306ab2020-03-18 11:38:00 +010037from pySim.cards import _cards_classes, card_detect
Philipp Maierff84c232020-05-12 17:24:18 +020038from pySim.utils import h2b, swap_nibbles, rpad, derive_milenage_opc, calculate_luhn, dec_iccid, init_reader
Philipp Maierf7792312018-06-11 17:11:39 +020039from pySim.ts_51_011 import EF
Philipp Maierc5b422e2019-08-30 11:41:02 +020040from pySim.card_handler import *
Philipp Maier7592eee2019-09-12 13:03:23 +020041from pySim.utils import *
Sylvain Munaut76504e02010-12-07 00:24:32 +010042
43def parse_options():
44
45 parser = OptionParser(usage="usage: %prog [options]")
46
47 parser.add_option("-d", "--device", dest="device", metavar="DEV",
48 help="Serial Device for SIM access [default: %default]",
49 default="/dev/ttyUSB0",
50 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010051 parser.add_option("-b", "--baud", dest="baudrate", type="int", metavar="BAUD",
52 help="Baudrate used for SIM access [default: %default]",
53 default=9600,
54 )
Sylvain Munaut9c8729a2010-12-08 23:20:27 +010055 parser.add_option("-p", "--pcsc-device", dest="pcsc_dev", type='int', metavar="PCSC",
Sylvain Munaute9fdecb2010-12-08 22:33:19 +010056 help="Which PC/SC reader number for SIM access",
57 default=None,
58 )
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070059 parser.add_option("--modem-device", dest="modem_dev", metavar="DEV",
60 help="Serial port of modem for Generic SIM Access (3GPP TS 27.007)",
61 default=None,
62 )
63 parser.add_option("--modem-baud", dest="modem_baud", type="int", metavar="BAUD",
64 help="Baudrate used for modem's port [default: %default]",
65 default=115200,
66 )
Vadim Yanitskiy9f9f5a62018-10-27 02:10:34 +070067 parser.add_option("--osmocon", dest="osmocon_sock", metavar="PATH",
68 help="Socket path for Calypso (e.g. Motorola C1XX) based reader (via OsmocomBB)",
69 default=None,
70 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010071 parser.add_option("-t", "--type", dest="type",
72 help="Card type (user -t list to view) [default: %default]",
73 default="auto",
74 )
Philipp Maierac9dde62018-07-04 11:05:14 +020075 parser.add_option("-T", "--probe", dest="probe",
76 help="Determine card type",
77 default=False, action="store_true"
78 )
Jan Balkec3ebd332015-01-26 12:22:55 +010079 parser.add_option("-a", "--pin-adm", dest="pin_adm",
80 help="ADM PIN used for provisioning (overwrites default)",
81 )
Daniel Willmannf432b2b2018-06-15 07:31:50 +020082 parser.add_option("-A", "--pin-adm-hex", dest="pin_adm_hex",
83 help="ADM PIN used for provisioning, as hex string (16 characters long",
84 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010085 parser.add_option("-e", "--erase", dest="erase", action='store_true',
86 help="Erase beforehand [default: %default]",
87 default=False,
88 )
89
Harald Welte7f62cec2012-08-13 20:07:41 +020090 parser.add_option("-S", "--source", dest="source",
91 help="Data Source[default: %default]",
92 default="cmdline",
93 )
94
95 # if mode is "cmdline"
Sylvain Munaut76504e02010-12-07 00:24:32 +010096 parser.add_option("-n", "--name", dest="name",
97 help="Operator name [default: %default]",
98 default="Magic",
99 )
100 parser.add_option("-c", "--country", dest="country", type="int", metavar="CC",
101 help="Country code [default: %default]",
102 default=1,
103 )
Harald Welte7f1d3c42020-05-12 21:12:44 +0200104 parser.add_option("-x", "--mcc", dest="mcc", type="string",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100105 help="Mobile Country Code [default: %default]",
Harald Welte7f1d3c42020-05-12 21:12:44 +0200106 default="901",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100107 )
Harald Welte7f1d3c42020-05-12 21:12:44 +0200108 parser.add_option("-y", "--mnc", dest="mnc", type="string",
Sylvain Munaut17716032010-12-08 22:33:51 +0100109 help="Mobile Network Code [default: %default]",
Harald Welte7f1d3c42020-05-12 21:12:44 +0200110 default="55",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100111 )
Supreeth Herlefc83e432020-05-06 11:48:46 +0200112 parser.add_option("--mnclen", dest="mnclen", type="choice",
113 help="Length of Mobile Network Code [default: %default]",
114 default=2,
115 choices=[2, 3],
116 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100117 parser.add_option("-m", "--smsc", dest="smsc",
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200118 help="SMSC number (Start with + for international no.) [default: '00 + country code + 5555']",
Sylvain Munaut76504e02010-12-07 00:24:32 +0100119 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100120 parser.add_option("-M", "--smsp", dest="smsp",
121 help="Raw SMSP content in hex [default: auto from SMSC]",
122 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100123
124 parser.add_option("-s", "--iccid", dest="iccid", metavar="ID",
125 help="Integrated Circuit Card ID",
126 )
127 parser.add_option("-i", "--imsi", dest="imsi",
128 help="International Mobile Subscriber Identity",
129 )
Supreeth Herle5a541012019-12-22 08:59:16 +0100130 parser.add_option("--msisdn", dest="msisdn",
131 help="Mobile Subscriber Integrated Services Digital Number",
132 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100133 parser.add_option("-k", "--ki", dest="ki",
134 help="Ki (default is to randomize)",
135 )
Harald Welte93b38cd2012-03-22 14:31:36 +0100136 parser.add_option("-o", "--opc", dest="opc",
137 help="OPC (default is to randomize)",
138 )
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100139 parser.add_option("--op", dest="op",
140 help="Set OP to derive OPC from OP and KI",
141 )
Alexander Chemeris21885242013-07-02 16:56:55 +0400142 parser.add_option("--acc", dest="acc",
143 help="Set ACC bits (Access Control Code). not all card types are supported",
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200144 )
Supreeth Herle8e0fccd2020-03-23 12:10:56 +0100145 parser.add_option("--epdgid", dest="epdgid",
146 help="Set Home Evolved Packet Data Gateway (ePDG) Identifier. (Only FQDN format supported)",
147 )
Supreeth Herlef964df42020-03-24 13:15:37 +0100148 parser.add_option("--epdgSelection", dest="epdgSelection",
149 help="Set PLMN for ePDG Selection Information. (Only Operator Identifier FQDN format supported)",
150 )
Supreeth Herlecf727f22020-03-24 17:32:21 +0100151 parser.add_option("--pcscf", dest="pcscf",
152 help="Set Proxy Call Session Control Function (P-CSCF) Address. (Only FQDN format supported)",
153 )
Supreeth Herle79f43dd2020-03-25 11:43:19 +0100154 parser.add_option("--ims-hdomain", dest="ims_hdomain",
155 help="Set IMS Home Network Domain Name in FQDN format",
156 )
Supreeth Herlea5bd9682020-03-26 09:16:14 +0100157 parser.add_option("--impi", dest="impi",
158 help="Set IMS private user identity",
159 )
Supreeth Herlebe7007e2020-03-26 09:27:45 +0100160 parser.add_option("--impu", dest="impu",
161 help="Set IMS public user identity",
162 )
Holger Hans Peter Freyther4e824682012-08-15 15:56:05 +0200163 parser.add_option("--read-imsi", dest="read_imsi", action="store_true",
164 help="Read the IMSI from the CARD", default=False
Alexander Chemeris21885242013-07-02 16:56:55 +0400165 )
Daniel Willmann164b9632019-09-03 19:13:51 +0200166 parser.add_option("--read-iccid", dest="read_iccid", action="store_true",
167 help="Read the ICCID from the CARD", default=False
168 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100169 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
170 help="Secret used for ICCID/IMSI autogen",
171 )
172 parser.add_option("-j", "--num", dest="num", type=int,
173 help="Card # used for ICCID/IMSI autogen",
174 )
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100175 parser.add_option("--batch", dest="batch_mode",
176 help="Enable batch mode [default: %default]",
177 default=False, action='store_true',
178 )
179 parser.add_option("--batch-state", dest="batch_state", metavar="FILE",
180 help="Optional batch state file",
181 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100182
Harald Welte7f62cec2012-08-13 20:07:41 +0200183 # if mode is "csv"
184 parser.add_option("--read-csv", dest="read_csv", metavar="FILE",
185 help="Read parameters from CSV file rather than command line")
186
187
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100188 parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
189 help="Append generated parameters in CSV file",
190 )
191 parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
192 help="Append generated parameters to OpenBSC HLR sqlite3",
193 )
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200194 parser.add_option("--dry-run", dest="dry_run",
195 help="Perform a 'dry run', don't actually program the card",
196 default=False, action="store_true")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200197 parser.add_option("--card_handler", dest="card_handler", metavar="FILE",
198 help="Use automatic card handling machine")
199
Sylvain Munaut76504e02010-12-07 00:24:32 +0100200 (options, args) = parser.parse_args()
201
202 if options.type == 'list':
203 for kls in _cards_classes:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700204 print(kls.name)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100205 sys.exit(0)
206
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200207 if options.probe:
208 return options
Philipp Maierac9dde62018-07-04 11:05:14 +0200209
Harald Welte7f62cec2012-08-13 20:07:41 +0200210 if options.source == 'csv':
Daniel Willmann164b9632019-09-03 19:13:51 +0200211 if (options.imsi is None) and (options.batch_mode is False) and (options.read_imsi is False) and (options.read_iccid is False):
212 parser.error("CSV mode needs either an IMSI, --read-imsi, --read-iccid or batch mode")
Harald Welte7f62cec2012-08-13 20:07:41 +0200213 if options.read_csv is None:
214 parser.error("CSV mode requires a CSV input file")
215 elif options.source == 'cmdline':
216 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
217 parser.error("If either IMSI or ICCID isn't specified, num is required")
218 else:
219 parser.error("Only `cmdline' and `csv' sources supported")
220
221 if (options.read_csv is not None) and (options.source != 'csv'):
222 parser.error("You cannot specify a CSV input file in source != csv")
223
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100224 if (options.batch_mode) and (options.num is None):
225 options.num = 0
226
Sylvain Munaut98d2b852010-12-23 20:27:25 +0100227 if (options.batch_mode):
228 if (options.imsi is not None) or (options.iccid is not None):
229 parser.error("Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more informations")
230
Sylvain Munaut76504e02010-12-07 00:24:32 +0100231 if args:
232 parser.error("Extraneous arguments")
233
234 return options
235
236
237def _digits(secret, usage, len, num):
Jeremy Herbert3b00dbf2020-10-25 20:56:05 +1000238 seed = secret + usage + '%d' % num
239 s = hashlib.sha1(seed.encode())
240 d = ''.join(['%02d' % x for x in s.digest()])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100241 return d[0:len]
242
243def _mcc_mnc_digits(mcc, mnc):
Harald Welte7f1d3c42020-05-12 21:12:44 +0200244 return '%s%s' % (mcc, mnc)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100245
246def _cc_digits(cc):
247 return ('%03d' if cc > 100 else '%02d') % cc
248
249def _isnum(s, l=-1):
250 return s.isdigit() and ((l== -1) or (len(s) == l))
251
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100252def _ishex(s, l=-1):
253 hc = '0123456789abcdef'
254 return all([x in hc for x in s.lower()]) and ((l== -1) or (len(s) == l))
255
Sylvain Munaut76504e02010-12-07 00:24:32 +0100256
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100257def _dbi_binary_quote(s):
258 # Count usage of each char
259 cnt = {}
260 for c in s:
261 cnt[c] = cnt.get(c, 0) + 1
262
263 # Find best offset
264 e = 0
265 m = len(s)
266 for i in range(1, 256):
267 if i == 39:
268 continue
269 sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
270 if sum_ < m:
271 m = sum_
272 e = i
273 if m == 0: # No overhead ? use this !
Daniel Willmann677d41b2020-10-19 10:34:31 +0200274 break
Sylvain Munaut1a914432011-12-08 20:08:26 +0100275
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100276 # Generate output
277 out = []
278 out.append( chr(e) ) # Offset
279 for c in s:
280 x = (256 + ord(c) - e) % 256
281 if x in (0, 1, 39):
282 out.append('\x01')
283 out.append(chr(x+1))
284 else:
285 out.append(chr(x))
286
287 return ''.join(out)
288
Sylvain Munaut76504e02010-12-07 00:24:32 +0100289def gen_parameters(opts):
Jan Balkec3ebd332015-01-26 12:22:55 +0100290 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki, PIN-ADM from the
Sylvain Munaut76504e02010-12-07 00:24:32 +0100291 options given by the user"""
292
293 # MCC/MNC
294 mcc = opts.mcc
295 mnc = opts.mnc
296
Harald Welte7f1d3c42020-05-12 21:12:44 +0200297 if not mcc.isdigit() or not mnc.isdigit():
298 raise ValueError('mcc & mnc must only contain decimal digits')
299 if len(mcc) < 1 or len(mcc) > 3:
300 raise ValueError('mcc must be between 1 .. 3 digits')
301 if len(mnc) < 1 or len(mnc) > 3:
302 raise ValueError('mnc must be between 1 .. 3 digits')
303
304 # MCC always has 3 digits
305 mcc = lpad(mcc, 3, "0")
306 # MNC must be at least 2 digits
307 mnc = lpad(mnc, 2, "0")
Sylvain Munaut76504e02010-12-07 00:24:32 +0100308
309 # Digitize country code (2 or 3 digits)
310 cc_digits = _cc_digits(opts.country)
311
312 # Digitize MCC/MNC (5 or 6 digits)
313 plmn_digits = _mcc_mnc_digits(mcc, mnc)
314
Supreeth Herle840a9e22020-01-21 13:32:46 +0100315 if opts.name is not None:
316 if len(opts.name) > 16:
Daniel Willmann677d41b2020-10-19 10:34:31 +0200317 raise ValueError('Service Provider Name must max 16 characters!')
Supreeth Herle840a9e22020-01-21 13:32:46 +0100318
Supreeth Herle5a541012019-12-22 08:59:16 +0100319 if opts.msisdn is not None:
320 msisdn = opts.msisdn
321 if msisdn[0] == '+':
322 msisdn = msisdn[1:]
323 if not msisdn.isdigit():
324 raise ValueError('MSISDN must be digits only! '
325 'Start with \'+\' for international numbers.')
326 if len(msisdn) > 10 * 2:
327 # TODO: Support MSISDN of length > 20 (10 Bytes)
328 raise ValueError('MSISDNs longer than 20 digits are not (yet) supported.')
329
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100330 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
Sylvain Munaut76504e02010-12-07 00:24:32 +0100331 if opts.iccid is not None:
332 iccid = opts.iccid
Todd Neal9eeadfc2018-04-25 15:36:29 -0500333 if not _isnum(iccid, 19) and not _isnum(iccid, 20):
Daniel Willmann677d41b2020-10-19 10:34:31 +0200334 raise ValueError('ICCID must be 19 or 20 digits !')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100335
336 else:
337 if opts.num is None:
338 raise ValueError('Neither ICCID nor card number specified !')
339
340 iccid = (
341 '89' + # Common prefix (telecom)
342 cc_digits + # Country Code on 2/3 digits
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200343 plmn_digits # MCC/MNC on 5/6 digits
Sylvain Munaut76504e02010-12-07 00:24:32 +0100344 )
345
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100346 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100347
348 if opts.secret is None:
349 # The raw number
350 iccid += ('%%0%dd' % ml) % opts.num
351 else:
352 # Randomized digits
353 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
354
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100355 # Add checksum digit
356 iccid += ('%1d' % calculate_luhn(iccid))
357
Sylvain Munaut76504e02010-12-07 00:24:32 +0100358 # IMSI (15 digits usually)
359 if opts.imsi is not None:
360 imsi = opts.imsi
361 if not _isnum(imsi):
362 raise ValueError('IMSI must be digits only !')
363
364 else:
365 if opts.num is None:
366 raise ValueError('Neither IMSI nor card number specified !')
367
368 ml = 15 - len(plmn_digits)
369
370 if opts.secret is None:
371 # The raw number
372 msin = ('%%0%dd' % ml) % opts.num
373 else:
374 # Randomized digits
375 msin = _digits(opts.secret, 'imsi', ml, opts.num)
376
377 imsi = (
378 plmn_digits + # MCC/MNC on 5/6 digits
379 msin # MSIN
380 )
381
382 # SMSP
383 if opts.smsp is not None:
384 smsp = opts.smsp
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100385 if not _ishex(smsp):
386 raise ValueError('SMSP must be hex digits only !')
387 if len(smsp) < 28*2:
388 raise ValueError('SMSP must be at least 28 bytes')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100389
390 else:
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200391 ton = "81"
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100392 if opts.smsc is not None:
393 smsc = opts.smsc
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200394 if smsc[0] == '+':
395 ton = "91"
396 smsc = smsc[1:]
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100397 if not _isnum(smsc):
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200398 raise ValueError('SMSC must be digits only!\n \
399 Start with \'+\' for international numbers')
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100400 else:
401 smsc = '00%d' % opts.country + '5555' # Hack ...
402
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200403 smsc = '%02d' % ((len(smsc) + 3)//2,) + ton + swap_nibbles(rpad(smsc, 20))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100404
405 smsp = (
406 'e1' + # Parameters indicator
407 'ff' * 12 + # TP-Destination address
408 smsc + # TP-Service Centre Address
409 '00' + # TP-Protocol identifier
410 '00' + # TP-Data coding scheme
411 '00' # TP-Validity period
412 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100413
Alexander Chemeris21885242013-07-02 16:56:55 +0400414 # ACC
415 if opts.acc is not None:
416 acc = opts.acc
417 if not _ishex(acc):
418 raise ValueError('ACC must be hex digits only !')
419 if len(acc) != 2*2:
420 raise ValueError('ACC must be exactly 2 bytes')
421
422 else:
423 acc = None
424
Sylvain Munaut76504e02010-12-07 00:24:32 +0100425 # Ki (random)
426 if opts.ki is not None:
427 ki = opts.ki
428 if not re.match('^[0-9a-fA-F]{32}$', ki):
429 raise ValueError('Ki needs to be 128 bits, in hex format')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100430 else:
431 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
432
Alexander Chemerisd17ca3d2017-07-18 16:40:58 +0300433 # OPC (random)
Harald Welte93b38cd2012-03-22 14:31:36 +0100434 if opts.opc is not None:
435 opc = opts.opc
436 if not re.match('^[0-9a-fA-F]{32}$', opc):
437 raise ValueError('OPC needs to be 128 bits, in hex format')
438
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100439 elif opts.op is not None:
440 opc = derive_milenage_opc(ki, opts.op)
Harald Welte93b38cd2012-03-22 14:31:36 +0100441 else:
442 opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
443
Harald Welte79b5ba42021-01-08 21:22:38 +0100444 pin_adm = sanitize_pin_adm(opts.pin_adm, opts.pin_adm_hex)
Harald Welte93b38cd2012-03-22 14:31:36 +0100445
Supreeth Herlef964df42020-03-24 13:15:37 +0100446 # ePDG Selection Information
447 if opts.epdgSelection:
448 if len(opts.epdgSelection) < 5 or len(opts.epdgSelection) > 6:
449 raise ValueError('ePDG Selection Information is not valid')
450 epdg_mcc = opts.epdgSelection[:3]
451 epdg_mnc = opts.epdgSelection[3:]
452 if not epdg_mcc.isdigit() or not epdg_mnc.isdigit():
453 raise ValueError('PLMN for ePDG Selection must only contain decimal digits')
454
Sylvain Munaut76504e02010-12-07 00:24:32 +0100455 # Return that
456 return {
457 'name' : opts.name,
458 'iccid' : iccid,
459 'mcc' : mcc,
460 'mnc' : mnc,
461 'imsi' : imsi,
462 'smsp' : smsp,
463 'ki' : ki,
Harald Welte93b38cd2012-03-22 14:31:36 +0100464 'opc' : opc,
Alexander Chemeris21885242013-07-02 16:56:55 +0400465 'acc' : acc,
Jan Balkec3ebd332015-01-26 12:22:55 +0100466 'pin_adm' : pin_adm,
Supreeth Herle5a541012019-12-22 08:59:16 +0100467 'msisdn' : opts.msisdn,
Supreeth Herle8e0fccd2020-03-23 12:10:56 +0100468 'epdgid' : opts.epdgid,
Supreeth Herlef964df42020-03-24 13:15:37 +0100469 'epdgSelection' : opts.epdgSelection,
Supreeth Herlecf727f22020-03-24 17:32:21 +0100470 'pcscf' : opts.pcscf,
Supreeth Herle79f43dd2020-03-25 11:43:19 +0100471 'ims_hdomain': opts.ims_hdomain,
Supreeth Herlebe7007e2020-03-26 09:27:45 +0100472 'impi' : opts.impi,
473 'impu' : opts.impu,
Sylvain Munaut76504e02010-12-07 00:24:32 +0100474 }
475
476
477def print_parameters(params):
478
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200479 s = ["Generated card parameters :"]
480 if 'name' in params:
481 s.append(" > Name : %(name)s")
482 if 'smsp' in params:
483 s.append(" > SMSP : %(smsp)s")
484 s.append(" > ICCID : %(iccid)s")
Philipp Maierbe069e22019-09-12 12:52:43 +0200485 s.append(" > MCC/MNC : %(mcc)s/%(mnc)s")
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200486 s.append(" > IMSI : %(imsi)s")
487 s.append(" > Ki : %(ki)s")
488 s.append(" > OPC : %(opc)s")
489 if 'acc' in params:
490 s.append(" > ACC : %(acc)s")
491 s.append(" > ADM1(hex): %(pin_adm)s")
492 print("\n".join(s) % params)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100493
494
Harald Welte130524b2012-08-13 15:53:43 +0200495def write_params_csv(opts, params):
496 # csv
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100497 if opts.write_csv:
498 import csv
Harald Welte93b38cd2012-03-22 14:31:36 +0100499 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100500 f = open(opts.write_csv, 'a')
501 cw = csv.writer(f)
502 cw.writerow([params[x] for x in row])
503 f.close()
504
Daniel Willmann164b9632019-09-03 19:13:51 +0200505def _read_params_csv(opts, iccid=None, imsi=None):
Harald Welte7f62cec2012-08-13 20:07:41 +0200506 import csv
Harald Welte7f62cec2012-08-13 20:07:41 +0200507 f = open(opts.read_csv, 'r')
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200508 cr = csv.DictReader(f)
Philipp Maier120a0002019-09-12 13:11:45 +0200509
510 # Lower-case fieldnames
511 cr.fieldnames = [ field.lower() for field in cr.fieldnames ]
512
Harald Welte7f62cec2012-08-13 20:07:41 +0200513 i = 0
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200514 if not 'iccid' in cr.fieldnames:
515 raise Exception("CSV file in wrong format!")
Harald Welte7f62cec2012-08-13 20:07:41 +0200516 for row in cr:
Daniel Willmann164b9632019-09-03 19:13:51 +0200517 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 +0200518 if opts.num == i:
Harald Weltec26b8292012-08-15 15:25:51 +0200519 f.close()
Daniel Willmann677d41b2020-10-19 10:34:31 +0200520 return row
Harald Weltec26b8292012-08-15 15:25:51 +0200521 i += 1
Daniel Willmann164b9632019-09-03 19:13:51 +0200522 if row['iccid'] == iccid:
523 f.close()
Daniel Willmann677d41b2020-10-19 10:34:31 +0200524 return row
Daniel Willmann164b9632019-09-03 19:13:51 +0200525
Harald Welte7f62cec2012-08-13 20:07:41 +0200526 if row['imsi'] == imsi:
Harald Weltec26b8292012-08-15 15:25:51 +0200527 f.close()
Daniel Willmann677d41b2020-10-19 10:34:31 +0200528 return row
Harald Welte7f62cec2012-08-13 20:07:41 +0200529
530 f.close()
Harald Weltec26b8292012-08-15 15:25:51 +0200531 return None
532
Daniel Willmann164b9632019-09-03 19:13:51 +0200533def read_params_csv(opts, imsi=None, iccid=None):
534 row = _read_params_csv(opts, iccid=iccid, imsi=imsi)
Harald Weltec26b8292012-08-15 15:25:51 +0200535 if row is not None:
Philipp Maier7592eee2019-09-12 13:03:23 +0200536 row['mcc'] = row.get('mcc', mcc_from_imsi(row.get('imsi')))
537 row['mnc'] = row.get('mnc', mnc_from_imsi(row.get('imsi')))
538
Daniel Willmannc46a4eb2018-06-15 07:31:50 +0200539 pin_adm = None
540 # We need to escape the pin_adm we get from the csv
541 if 'pin_adm' in row:
542 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['pin_adm']])
543 # Stay compatible to the odoo csv format
544 elif 'adm1' in row:
545 pin_adm = ''.join(['%02x'%(ord(x)) for x in row['adm1']])
546 if pin_adm:
547 row['pin_adm'] = rpad(pin_adm, 16)
Philipp Maiere053da52019-09-05 13:08:36 +0200548
549 # If the CSV-File defines a pin_adm_hex field use this field to
550 # generate pin_adm from that.
551 pin_adm_hex = row.get('pin_adm_hex')
552 if pin_adm_hex:
553 if len(pin_adm_hex) == 16:
554 row['pin_adm'] = pin_adm_hex
555 # Ensure that it's hex-encoded
556 try:
557 try_encode = h2b(pin_adm)
558 except ValueError:
559 raise ValueError("pin_adm_hex needs to be hex encoded using this option")
560 else:
561 raise ValueError("pin_adm_hex needs to be exactly 16 digits (hex encoded)")
562
Harald Welte7f62cec2012-08-13 20:07:41 +0200563 return row
564
Harald Weltec26b8292012-08-15 15:25:51 +0200565
Harald Welte130524b2012-08-13 15:53:43 +0200566def write_params_hlr(opts, params):
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100567 # SQLite3 OpenBSC HLR
568 if opts.write_hlr:
569 import sqlite3
570 conn = sqlite3.connect(opts.write_hlr)
571
572 c = conn.execute(
573 'INSERT INTO Subscriber ' +
574 '(imsi, name, extension, authorized, created, updated) ' +
575 'VALUES ' +
576 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
577 [
578 params['imsi'],
579 params['name'],
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200580 '9' + params['iccid'][-5:-1]
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100581 ],
582 )
583 sub_id = c.lastrowid
584 c.close()
585
586 c = conn.execute(
587 'INSERT INTO AuthKeys ' +
588 '(subscriber_id, algorithm_id, a3a8_ki)' +
589 'VALUES ' +
590 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100591 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100592 )
593
594 conn.commit()
595 conn.close()
596
Harald Welte130524b2012-08-13 15:53:43 +0200597def write_parameters(opts, params):
598 write_params_csv(opts, params)
Harald Welte7f62cec2012-08-13 20:07:41 +0200599 write_params_hlr(opts, params)
Harald Welte130524b2012-08-13 15:53:43 +0200600
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100601
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100602BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
603BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100604
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100605def init_batch(opts):
606 # Need to do something ?
607 if not opts.batch_mode:
608 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100609
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100610 for k in BATCH_INCOMPATIBLE:
611 if getattr(opts, k):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700612 print("Incompatible option with batch_state: %s" % (k,))
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100613 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100614
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100615 # Don't load state if there is none ...
616 if not opts.batch_state:
617 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100618
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100619 if not os.path.isfile(opts.batch_state):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700620 print("No state file yet")
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100621 return
622
623 # Get stored data
624 fh = open(opts.batch_state)
625 d = json.loads(fh.read())
626 fh.close()
627
628 for k,v in d.iteritems():
629 setattr(opts, k, v)
630
631
632def save_batch(opts):
633 # Need to do something ?
634 if not opts.batch_mode or not opts.batch_state:
635 return
636
637 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
638 fh = open(opts.batch_state, 'w')
639 fh.write(d)
640 fh.close()
641
642
Philipp Maierc5b422e2019-08-30 11:41:02 +0200643def process_card(opts, first, card_handler):
644
645 if opts.dry_run is False:
646 # Connect transport
647 card_handler.get(first)
648
649 if opts.dry_run is False:
650 # Get card
Supreeth Herle4c306ab2020-03-18 11:38:00 +0100651 card = card_detect(opts.type, scc)
Philipp Maierc5b422e2019-08-30 11:41:02 +0200652 if card is None:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700653 print("No card detected!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200654 return -1
655
656 # Probe only
657 if opts.probe:
658 return 0
659
660 # Erase if requested
661 if opts.erase:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700662 print("Formatting ...")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200663 card.erase()
664 card.reset()
665
666 # Generate parameters
667 if opts.source == 'cmdline':
668 cp = gen_parameters(opts)
669 elif opts.source == 'csv':
670 imsi = None
671 iccid = None
672 if opts.read_iccid:
673 if opts.dry_run:
674 # Connect transport
Daniel Willmanndd014ea2020-10-19 10:35:11 +0200675 card_handler.get(False)
Philipp Maierc5b422e2019-08-30 11:41:02 +0200676 (res,_) = scc.read_binary(['3f00', '2fe2'], length=10)
677 iccid = dec_iccid(res)
678 elif opts.read_imsi:
679 if opts.dry_run:
680 # Connect transport
Daniel Willmanndd014ea2020-10-19 10:35:11 +0200681 card_handler.get(False)
Philipp Maierc5b422e2019-08-30 11:41:02 +0200682 (res,_) = scc.read_binary(EF['IMSI'])
683 imsi = swap_nibbles(res)[3:]
684 else:
685 imsi = opts.imsi
686 cp = read_params_csv(opts, imsi=imsi, iccid=iccid)
687 if cp is None:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700688 print("Error reading parameters from CSV file!\n")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200689 return 2
690 print_parameters(cp)
691
692 if opts.dry_run is False:
693 # Program the card
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700694 print("Programming ...")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200695 card.program(cp)
696 else:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700697 print("Dry Run: NOT PROGRAMMING!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200698
699 # Write parameters permanently
700 write_parameters(opts, cp)
701
702 # Batch mode state update and save
703 if opts.num is not None:
704 opts.num += 1
705 save_batch(opts)
706
707 card_handler.done()
708 return 0
709
710
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100711if __name__ == '__main__':
712
713 # Parse options
714 opts = parse_options()
715
Vadim Yanitskiy588f3ac2018-10-27 06:30:33 +0700716 # Init card reader driver
Philipp Maierff84c232020-05-12 17:24:18 +0200717 sl = init_reader(opts)
Philipp Maierc8caec22021-02-22 16:07:53 +0100718 if sl is None:
719 exit(1)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100720
721 # Create command layer
722 scc = SimCardCommands(transport=sl)
723
Philipp Maier196b08c2019-09-12 11:49:44 +0200724 # If we use a CSV file as data input, check if the CSV file exists.
725 if opts.source == 'csv':
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700726 print("Using CSV file as data input: " + str(opts.read_csv))
Philipp Maier196b08c2019-09-12 11:49:44 +0200727 if not os.path.isfile(opts.read_csv):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700728 print("CSV file not found!")
Philipp Maier196b08c2019-09-12 11:49:44 +0200729 sys.exit(1)
730
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100731 # Batch mode init
732 init_batch(opts)
733
Philipp Maierc5b422e2019-08-30 11:41:02 +0200734 if opts.card_handler:
735 card_handler = card_handler_auto(sl, opts.card_handler)
Denis 'GNUtoo' Carikli84d2cb32019-09-12 01:46:25 +0200736 else:
Philipp Maierc5b422e2019-08-30 11:41:02 +0200737 card_handler = card_handler(sl)
738
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100739 # Iterate
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100740 first = True
741 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100742
Philipp Maierc5b422e2019-08-30 11:41:02 +0200743 while 1:
744 try:
745 rc = process_card(opts, first, card_handler)
746 except (KeyboardInterrupt):
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700747 print("")
748 print("Terminated by user!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200749 sys.exit(0)
750 except (SystemExit):
751 raise
752 except:
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700753 print("")
754 print("Card programming failed with an execption:")
755 print("---------------------8<---------------------")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200756 traceback.print_exc()
Vadim Yanitskiy6727f0c2020-01-22 23:38:24 +0700757 print("---------------------8<---------------------")
758 print("")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200759 rc = -1
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200760
Philipp Maierc5b422e2019-08-30 11:41:02 +0200761 # Something did not work as well as expected, however, lets
762 # make sure the card is pulled from the reader.
763 if rc != 0:
764 card_handler.error()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100765
Philipp Maierc5b422e2019-08-30 11:41:02 +0200766 # If we are not in batch mode we are done in any case, so lets
767 # exit here.
768 if not opts.batch_mode:
769 sys.exit(rc)
770
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100771 first = False