blob: ade213b6e7a23b0185f65723f8e77c909d0f7a88 [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
Robert Falkenbergd0505bd2021-02-24 14:06:18 +010040from pySim.ts_51_011 import EF, EF_AD
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
Harald Weltec91085e2022-02-10 18:05:45 +010044
Sylvain Munaut76504e02010-12-07 00:24:32 +010045def parse_options():
46
Harald Weltec91085e2022-02-10 18:05:45 +010047 parser = OptionParser(usage="usage: %prog [options]")
Sylvain Munaut76504e02010-12-07 00:24:32 +010048
Harald Weltec91085e2022-02-10 18:05:45 +010049 parser.add_option("-d", "--device", dest="device", metavar="DEV",
50 help="Serial Device for SIM access [default: %default]",
51 default="/dev/ttyUSB0",
52 )
53 parser.add_option("-b", "--baud", dest="baudrate", type="int", metavar="BAUD",
54 help="Baudrate used for SIM access [default: %default]",
55 default=9600,
56 )
57 parser.add_option("-p", "--pcsc-device", dest="pcsc_dev", type='int', metavar="PCSC",
58 help="Which PC/SC reader number for SIM access",
59 default=None,
60 )
61 parser.add_option("--modem-device", dest="modem_dev", metavar="DEV",
62 help="Serial port of modem for Generic SIM Access (3GPP TS 27.007)",
63 default=None,
64 )
65 parser.add_option("--modem-baud", dest="modem_baud", type="int", metavar="BAUD",
66 help="Baudrate used for modem's port [default: %default]",
67 default=115200,
68 )
69 parser.add_option("--osmocon", dest="osmocon_sock", metavar="PATH",
70 help="Socket path for Calypso (e.g. Motorola C1XX) based reader (via OsmocomBB)",
71 default=None,
72 )
73 parser.add_option("-t", "--type", dest="type",
74 help="Card type (user -t list to view) [default: %default]",
75 default="auto",
76 )
77 parser.add_option("-T", "--probe", dest="probe",
78 help="Determine card type",
79 default=False, action="store_true"
80 )
81 parser.add_option("-a", "--pin-adm", dest="pin_adm",
82 help="ADM PIN used for provisioning (overwrites default)",
83 )
84 parser.add_option("-A", "--pin-adm-hex", dest="pin_adm_hex",
85 help="ADM PIN used for provisioning, as hex string (16 characters long",
86 )
87 parser.add_option("-e", "--erase", dest="erase", action='store_true',
88 help="Erase beforehand [default: %default]",
89 default=False,
90 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010091
Harald Weltec91085e2022-02-10 18:05:45 +010092 parser.add_option("-S", "--source", dest="source",
93 help="Data Source[default: %default]",
94 default="cmdline",
95 )
Harald Welte7f62cec2012-08-13 20:07:41 +020096
Harald Weltec91085e2022-02-10 18:05:45 +010097 # if mode is "cmdline"
98 parser.add_option("-n", "--name", dest="name",
99 help="Operator name [default: %default]",
100 default="Magic",
101 )
102 parser.add_option("-c", "--country", dest="country", type="int", metavar="CC",
103 help="Country code [default: %default]",
104 default=1,
105 )
106 parser.add_option("-x", "--mcc", dest="mcc", type="string",
107 help="Mobile Country Code [default: %default]",
108 default="901",
109 )
110 parser.add_option("-y", "--mnc", dest="mnc", type="string",
111 help="Mobile Network Code [default: %default]",
112 default="55",
113 )
114 parser.add_option("--mnclen", dest="mnclen", type="choice",
115 help="Length of Mobile Network Code [default: %default]",
116 default=2,
117 choices=[2, 3],
118 )
119 parser.add_option("-m", "--smsc", dest="smsc",
120 help="SMSC number (Start with + for international no.) [default: '00 + country code + 5555']",
121 )
122 parser.add_option("-M", "--smsp", dest="smsp",
123 help="Raw SMSP content in hex [default: auto from SMSC]",
124 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100125
Harald Weltec91085e2022-02-10 18:05:45 +0100126 parser.add_option("-s", "--iccid", dest="iccid", metavar="ID",
127 help="Integrated Circuit Card ID",
128 )
129 parser.add_option("-i", "--imsi", dest="imsi",
130 help="International Mobile Subscriber Identity",
131 )
132 parser.add_option("--msisdn", dest="msisdn",
133 help="Mobile Subscriber Integrated Services Digital Number",
134 )
135 parser.add_option("-k", "--ki", dest="ki",
136 help="Ki (default is to randomize)",
137 )
138 parser.add_option("-o", "--opc", dest="opc",
139 help="OPC (default is to randomize)",
140 )
141 parser.add_option("--op", dest="op",
142 help="Set OP to derive OPC from OP and KI",
143 )
144 parser.add_option("--acc", dest="acc",
145 help="Set ACC bits (Access Control Code). not all card types are supported",
146 )
147 parser.add_option("--opmode", dest="opmode", type="choice",
148 help="Set UE Operation Mode in EF.AD (Administrative Data)",
149 default=None,
150 choices=['{:02X}'.format(int(m)) for m in EF_AD.OP_MODE],
151 )
152 parser.add_option("--epdgid", dest="epdgid",
153 help="Set Home Evolved Packet Data Gateway (ePDG) Identifier. (Only FQDN format supported)",
154 )
155 parser.add_option("--epdgSelection", dest="epdgSelection",
156 help="Set PLMN for ePDG Selection Information. (Only Operator Identifier FQDN format supported)",
157 )
158 parser.add_option("--pcscf", dest="pcscf",
159 help="Set Proxy Call Session Control Function (P-CSCF) Address. (Only FQDN format supported)",
160 )
161 parser.add_option("--ims-hdomain", dest="ims_hdomain",
162 help="Set IMS Home Network Domain Name in FQDN format",
163 )
164 parser.add_option("--impi", dest="impi",
165 help="Set IMS private user identity",
166 )
167 parser.add_option("--impu", dest="impu",
168 help="Set IMS public user identity",
169 )
170 parser.add_option("--read-imsi", dest="read_imsi", action="store_true",
171 help="Read the IMSI from the CARD", default=False
172 )
173 parser.add_option("--read-iccid", dest="read_iccid", action="store_true",
174 help="Read the ICCID from the CARD", default=False
175 )
176 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
177 help="Secret used for ICCID/IMSI autogen",
178 )
179 parser.add_option("-j", "--num", dest="num", type=int,
180 help="Card # used for ICCID/IMSI autogen",
181 )
182 parser.add_option("--batch", dest="batch_mode",
183 help="Enable batch mode [default: %default]",
184 default=False, action='store_true',
185 )
186 parser.add_option("--batch-state", dest="batch_state", metavar="FILE",
187 help="Optional batch state file",
188 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100189
Harald Weltec91085e2022-02-10 18:05:45 +0100190 # if mode is "csv"
191 parser.add_option("--read-csv", dest="read_csv", metavar="FILE",
192 help="Read parameters from CSV file rather than command line")
Harald Welte7f62cec2012-08-13 20:07:41 +0200193
Harald Weltec91085e2022-02-10 18:05:45 +0100194 parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
195 help="Append generated parameters in CSV file",
196 )
197 parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
198 help="Append generated parameters to OpenBSC HLR sqlite3",
199 )
200 parser.add_option("--dry-run", dest="dry_run",
201 help="Perform a 'dry run', don't actually program the card",
202 default=False, action="store_true")
203 parser.add_option("--card_handler", dest="card_handler_config", metavar="FILE",
204 help="Use automatic card handling machine")
Harald Welte7f62cec2012-08-13 20:07:41 +0200205
Harald Weltec91085e2022-02-10 18:05:45 +0100206 (options, args) = parser.parse_args()
Philipp Maierc5b422e2019-08-30 11:41:02 +0200207
Harald Weltec91085e2022-02-10 18:05:45 +0100208 if options.type == 'list':
209 for kls in _cards_classes:
210 print(kls.name)
211 sys.exit(0)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100212
Harald Weltec91085e2022-02-10 18:05:45 +0100213 if options.probe:
214 return options
Sylvain Munaut76504e02010-12-07 00:24:32 +0100215
Harald Weltec91085e2022-02-10 18:05:45 +0100216 if options.source == 'csv':
217 if (options.imsi is None) and (options.batch_mode is False) and (options.read_imsi is False) and (options.read_iccid is False):
218 parser.error(
219 "CSV mode needs either an IMSI, --read-imsi, --read-iccid or batch mode")
220 if options.read_csv is None:
221 parser.error("CSV mode requires a CSV input file")
222 elif options.source == 'cmdline':
223 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
224 parser.error(
225 "If either IMSI or ICCID isn't specified, num is required")
226 else:
227 parser.error("Only `cmdline' and `csv' sources supported")
Philipp Maierac9dde62018-07-04 11:05:14 +0200228
Harald Weltec91085e2022-02-10 18:05:45 +0100229 if (options.read_csv is not None) and (options.source != 'csv'):
230 parser.error("You cannot specify a CSV input file in source != csv")
Harald Welte7f62cec2012-08-13 20:07:41 +0200231
Harald Weltec91085e2022-02-10 18:05:45 +0100232 if (options.batch_mode) and (options.num is None):
233 options.num = 0
Harald Welte7f62cec2012-08-13 20:07:41 +0200234
Harald Weltec91085e2022-02-10 18:05:45 +0100235 if (options.batch_mode):
236 if (options.imsi is not None) or (options.iccid is not None):
237 parser.error(
238 "Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more information")
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100239
Harald Weltec91085e2022-02-10 18:05:45 +0100240 if args:
241 parser.error("Extraneous arguments")
Sylvain Munaut98d2b852010-12-23 20:27:25 +0100242
Harald Weltec91085e2022-02-10 18:05:45 +0100243 return options
Sylvain Munaut76504e02010-12-07 00:24:32 +0100244
245
246def _digits(secret, usage, len, num):
Harald Weltec91085e2022-02-10 18:05:45 +0100247 seed = secret + usage + '%d' % num
248 s = hashlib.sha1(seed.encode())
249 d = ''.join(['%02d' % x for x in s.digest()])
250 return d[0:len]
251
Sylvain Munaut76504e02010-12-07 00:24:32 +0100252
253def _mcc_mnc_digits(mcc, mnc):
Harald Weltec91085e2022-02-10 18:05:45 +0100254 return '%s%s' % (mcc, mnc)
255
Sylvain Munaut76504e02010-12-07 00:24:32 +0100256
257def _cc_digits(cc):
Harald Weltec91085e2022-02-10 18:05:45 +0100258 return ('%03d' if cc > 100 else '%02d') % cc
259
Sylvain Munaut76504e02010-12-07 00:24:32 +0100260
261def _isnum(s, l=-1):
Harald Weltec91085e2022-02-10 18:05:45 +0100262 return s.isdigit() and ((l == -1) or (len(s) == l))
263
Sylvain Munaut76504e02010-12-07 00:24:32 +0100264
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100265def _ishex(s, l=-1):
Harald Weltec91085e2022-02-10 18:05:45 +0100266 hc = '0123456789abcdef'
267 return all([x in hc for x in s.lower()]) and ((l == -1) or (len(s) == l))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100268
Sylvain Munaut76504e02010-12-07 00:24:32 +0100269
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100270def _dbi_binary_quote(s):
Harald Weltec91085e2022-02-10 18:05:45 +0100271 # Count usage of each char
272 cnt = {}
273 for c in s:
274 cnt[c] = cnt.get(c, 0) + 1
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100275
Harald Weltec91085e2022-02-10 18:05:45 +0100276 # Find best offset
277 e = 0
278 m = len(s)
279 for i in range(1, 256):
280 if i == 39:
281 continue
282 sum_ = cnt.get(i, 0) + cnt.get((i+1) & 0xff, 0) + \
283 cnt.get((i+39) & 0xff, 0)
284 if sum_ < m:
285 m = sum_
286 e = i
287 if m == 0: # No overhead ? use this !
288 break
Sylvain Munaut1a914432011-12-08 20:08:26 +0100289
Harald Weltec91085e2022-02-10 18:05:45 +0100290 # Generate output
291 out = []
292 out.append(chr(e)) # Offset
293 for c in s:
294 x = (256 + ord(c) - e) % 256
295 if x in (0, 1, 39):
296 out.append('\x01')
297 out.append(chr(x+1))
298 else:
299 out.append(chr(x))
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100300
Harald Weltec91085e2022-02-10 18:05:45 +0100301 return ''.join(out)
302
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100303
Sylvain Munaut76504e02010-12-07 00:24:32 +0100304def gen_parameters(opts):
Harald Weltec91085e2022-02-10 18:05:45 +0100305 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki, PIN-ADM from the
306 options given by the user"""
Sylvain Munaut76504e02010-12-07 00:24:32 +0100307
Harald Weltec91085e2022-02-10 18:05:45 +0100308 # MCC/MNC
309 mcc = opts.mcc
310 mnc = opts.mnc
Sylvain Munaut76504e02010-12-07 00:24:32 +0100311
Harald Weltec91085e2022-02-10 18:05:45 +0100312 if not mcc.isdigit() or not mnc.isdigit():
313 raise ValueError('mcc & mnc must only contain decimal digits')
314 if len(mcc) < 1 or len(mcc) > 3:
315 raise ValueError('mcc must be between 1 .. 3 digits')
316 if len(mnc) < 1 or len(mnc) > 3:
317 raise ValueError('mnc must be between 1 .. 3 digits')
Harald Welte7f1d3c42020-05-12 21:12:44 +0200318
Harald Weltec91085e2022-02-10 18:05:45 +0100319 # MCC always has 3 digits
320 mcc = lpad(mcc, 3, "0")
321 # MNC must be at least 2 digits
322 mnc = lpad(mnc, 2, "0")
Sylvain Munaut76504e02010-12-07 00:24:32 +0100323
Harald Weltec91085e2022-02-10 18:05:45 +0100324 # Digitize country code (2 or 3 digits)
325 cc_digits = _cc_digits(opts.country)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100326
Harald Weltec91085e2022-02-10 18:05:45 +0100327 # Digitize MCC/MNC (5 or 6 digits)
328 plmn_digits = _mcc_mnc_digits(mcc, mnc)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100329
Harald Weltec91085e2022-02-10 18:05:45 +0100330 if opts.name is not None:
331 if len(opts.name) > 16:
332 raise ValueError('Service Provider Name must max 16 characters!')
Supreeth Herle840a9e22020-01-21 13:32:46 +0100333
Harald Weltec91085e2022-02-10 18:05:45 +0100334 if opts.msisdn is not None:
335 msisdn = opts.msisdn
336 if msisdn[0] == '+':
337 msisdn = msisdn[1:]
338 if not msisdn.isdigit():
339 raise ValueError('MSISDN must be digits only! '
340 'Start with \'+\' for international numbers.')
341 if len(msisdn) > 10 * 2:
342 # TODO: Support MSISDN of length > 20 (10 Bytes)
343 raise ValueError(
344 'MSISDNs longer than 20 digits are not (yet) supported.')
Supreeth Herle5a541012019-12-22 08:59:16 +0100345
Harald Weltec91085e2022-02-10 18:05:45 +0100346 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
347 if opts.iccid is not None:
348 iccid = opts.iccid
349 if not _isnum(iccid, 19) and not _isnum(iccid, 20):
350 raise ValueError('ICCID must be 19 or 20 digits !')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100351
Harald Weltec91085e2022-02-10 18:05:45 +0100352 else:
353 if opts.num is None:
354 raise ValueError('Neither ICCID nor card number specified !')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100355
Harald Weltec91085e2022-02-10 18:05:45 +0100356 iccid = (
357 '89' + # Common prefix (telecom)
358 cc_digits + # Country Code on 2/3 digits
359 plmn_digits # MCC/MNC on 5/6 digits
360 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100361
Harald Weltec91085e2022-02-10 18:05:45 +0100362 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100363
Harald Weltec91085e2022-02-10 18:05:45 +0100364 if opts.secret is None:
365 # The raw number
366 iccid += ('%%0%dd' % ml) % opts.num
367 else:
368 # Randomized digits
369 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100370
Harald Weltec91085e2022-02-10 18:05:45 +0100371 # Add checksum digit
372 iccid += ('%1d' % calculate_luhn(iccid))
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100373
Harald Weltec91085e2022-02-10 18:05:45 +0100374 # IMSI (15 digits usually)
375 if opts.imsi is not None:
376 imsi = opts.imsi
377 if not _isnum(imsi):
378 raise ValueError('IMSI must be digits only !')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100379
Harald Weltec91085e2022-02-10 18:05:45 +0100380 else:
381 if opts.num is None:
382 raise ValueError('Neither IMSI nor card number specified !')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100383
Harald Weltec91085e2022-02-10 18:05:45 +0100384 ml = 15 - len(plmn_digits)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100385
Harald Weltec91085e2022-02-10 18:05:45 +0100386 if opts.secret is None:
387 # The raw number
388 msin = ('%%0%dd' % ml) % opts.num
389 else:
390 # Randomized digits
391 msin = _digits(opts.secret, 'imsi', ml, opts.num)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100392
Harald Weltec91085e2022-02-10 18:05:45 +0100393 imsi = (
394 plmn_digits + # MCC/MNC on 5/6 digits
395 msin # MSIN
396 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100397
Harald Weltec91085e2022-02-10 18:05:45 +0100398 # SMSP
399 if opts.smsp is not None:
400 smsp = opts.smsp
401 if not _ishex(smsp):
402 raise ValueError('SMSP must be hex digits only !')
403 if len(smsp) < 28*2:
404 raise ValueError('SMSP must be at least 28 bytes')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100405
Harald Weltec91085e2022-02-10 18:05:45 +0100406 else:
407 ton = "81"
408 if opts.smsc is not None:
409 smsc = opts.smsc
410 if smsc[0] == '+':
411 ton = "91"
412 smsc = smsc[1:]
413 if not _isnum(smsc):
414 raise ValueError('SMSC must be digits only!\n \
Daniel Willmann4fa8f1c2018-10-02 18:10:21 +0200415 Start with \'+\' for international numbers')
Harald Weltec91085e2022-02-10 18:05:45 +0100416 else:
417 smsc = '00%d' % opts.country + '5555' # Hack ...
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100418
Harald Weltec91085e2022-02-10 18:05:45 +0100419 smsc = '%02d' % ((len(smsc) + 3)//2,) + ton + \
420 swap_nibbles(rpad(smsc, 20))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100421
Harald Weltec91085e2022-02-10 18:05:45 +0100422 smsp = (
423 'e1' + # Parameters indicator
424 'ff' * 12 + # TP-Destination address
425 smsc + # TP-Service Centre Address
426 '00' + # TP-Protocol identifier
427 '00' + # TP-Data coding scheme
428 '00' # TP-Validity period
429 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100430
Harald Weltec91085e2022-02-10 18:05:45 +0100431 # ACC
432 if opts.acc is not None:
433 acc = opts.acc
434 if not _ishex(acc):
435 raise ValueError('ACC must be hex digits only !')
436 if len(acc) != 2*2:
437 raise ValueError('ACC must be exactly 2 bytes')
Alexander Chemeris21885242013-07-02 16:56:55 +0400438
Harald Weltec91085e2022-02-10 18:05:45 +0100439 else:
440 acc = None
Alexander Chemeris21885242013-07-02 16:56:55 +0400441
Harald Weltec91085e2022-02-10 18:05:45 +0100442 # Ki (random)
443 if opts.ki is not None:
444 ki = opts.ki
445 if not re.match('^[0-9a-fA-F]{32}$', ki):
446 raise ValueError('Ki needs to be 128 bits, in hex format')
447 else:
448 ki = ''.join(['%02x' % random.randrange(0, 256) for i in range(16)])
Sylvain Munaut76504e02010-12-07 00:24:32 +0100449
Harald Weltec91085e2022-02-10 18:05:45 +0100450 # OPC (random)
451 if opts.opc is not None:
452 opc = opts.opc
453 if not re.match('^[0-9a-fA-F]{32}$', opc):
454 raise ValueError('OPC needs to be 128 bits, in hex format')
Harald Welte93b38cd2012-03-22 14:31:36 +0100455
Harald Weltec91085e2022-02-10 18:05:45 +0100456 elif opts.op is not None:
457 opc = derive_milenage_opc(ki, opts.op)
458 else:
459 opc = ''.join(['%02x' % random.randrange(0, 256) for i in range(16)])
Harald Welte93b38cd2012-03-22 14:31:36 +0100460
Harald Weltec91085e2022-02-10 18:05:45 +0100461 pin_adm = sanitize_pin_adm(opts.pin_adm, opts.pin_adm_hex)
Harald Welte93b38cd2012-03-22 14:31:36 +0100462
Harald Weltec91085e2022-02-10 18:05:45 +0100463 # ePDG Selection Information
464 if opts.epdgSelection:
465 if len(opts.epdgSelection) < 5 or len(opts.epdgSelection) > 6:
466 raise ValueError('ePDG Selection Information is not valid')
467 epdg_mcc = opts.epdgSelection[:3]
468 epdg_mnc = opts.epdgSelection[3:]
469 if not epdg_mcc.isdigit() or not epdg_mnc.isdigit():
470 raise ValueError(
471 'PLMN for ePDG Selection must only contain decimal digits')
Supreeth Herlef964df42020-03-24 13:15:37 +0100472
Harald Weltec91085e2022-02-10 18:05:45 +0100473 # Return that
474 return {
475 'name': opts.name,
476 'iccid': iccid,
477 'mcc': mcc,
478 'mnc': mnc,
479 'imsi': imsi,
480 'smsp': smsp,
481 'ki': ki,
482 'opc': opc,
483 'acc': acc,
484 'pin_adm': pin_adm,
485 'msisdn': opts.msisdn,
486 'epdgid': opts.epdgid,
487 'epdgSelection': opts.epdgSelection,
488 'pcscf': opts.pcscf,
489 'ims_hdomain': opts.ims_hdomain,
490 'impi': opts.impi,
491 'impu': opts.impu,
492 'opmode': opts.opmode,
493 }
Sylvain Munaut76504e02010-12-07 00:24:32 +0100494
495
496def print_parameters(params):
497
Harald Weltec91085e2022-02-10 18:05:45 +0100498 s = ["Generated card parameters :"]
499 if 'name' in params:
500 s.append(" > Name : %(name)s")
501 if 'smsp' in params:
502 s.append(" > SMSP : %(smsp)s")
503 s.append(" > ICCID : %(iccid)s")
504 s.append(" > MCC/MNC : %(mcc)s/%(mnc)s")
505 s.append(" > IMSI : %(imsi)s")
506 s.append(" > Ki : %(ki)s")
507 s.append(" > OPC : %(opc)s")
508 if 'acc' in params:
509 s.append(" > ACC : %(acc)s")
510 s.append(" > ADM1(hex): %(pin_adm)s")
511 if 'opmode' in params:
512 s.append(" > OPMODE : %(opmode)s")
513 print("\n".join(s) % params)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100514
515
Harald Welte130524b2012-08-13 15:53:43 +0200516def write_params_csv(opts, params):
Harald Weltec91085e2022-02-10 18:05:45 +0100517 # csv
518 if opts.write_csv:
519 import csv
520 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
521 f = open(opts.write_csv, 'a')
522 cw = csv.writer(f)
523 cw.writerow([params[x] for x in row])
524 f.close()
525
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100526
Daniel Willmann164b9632019-09-03 19:13:51 +0200527def _read_params_csv(opts, iccid=None, imsi=None):
Harald Weltec91085e2022-02-10 18:05:45 +0100528 import csv
529 f = open(opts.read_csv, 'r')
530 cr = csv.DictReader(f)
Philipp Maier120a0002019-09-12 13:11:45 +0200531
Harald Weltec91085e2022-02-10 18:05:45 +0100532 # Lower-case fieldnames
533 cr.fieldnames = [field.lower() for field in cr.fieldnames]
Philipp Maier120a0002019-09-12 13:11:45 +0200534
Harald Weltec91085e2022-02-10 18:05:45 +0100535 i = 0
536 if not 'iccid' in cr.fieldnames:
537 raise Exception("CSV file in wrong format!")
538 for row in cr:
539 if opts.num is not None and opts.read_iccid is False and opts.read_imsi is False:
540 if opts.num == i:
541 f.close()
542 return row
543 i += 1
544 if row['iccid'] == iccid:
545 f.close()
546 return row
Daniel Willmann164b9632019-09-03 19:13:51 +0200547
Harald Weltec91085e2022-02-10 18:05:45 +0100548 if row['imsi'] == imsi:
549 f.close()
550 return row
Harald Welte7f62cec2012-08-13 20:07:41 +0200551
Harald Weltec91085e2022-02-10 18:05:45 +0100552 f.close()
553 return None
554
Harald Weltec26b8292012-08-15 15:25:51 +0200555
Daniel Willmann164b9632019-09-03 19:13:51 +0200556def read_params_csv(opts, imsi=None, iccid=None):
Harald Weltec91085e2022-02-10 18:05:45 +0100557 row = _read_params_csv(opts, iccid=iccid, imsi=imsi)
558 if row is not None:
559 row['mcc'] = row.get('mcc', mcc_from_imsi(row.get('imsi')))
560 row['mnc'] = row.get('mnc', mnc_from_imsi(row.get('imsi')))
Philipp Maier7592eee2019-09-12 13:03:23 +0200561
Harald Weltec91085e2022-02-10 18:05:45 +0100562 pin_adm = None
563 # We need to escape the pin_adm we get from the csv
564 if 'pin_adm' in row:
565 pin_adm = ''.join(['%02x' % (ord(x)) for x in row['pin_adm']])
566 # Stay compatible to the odoo csv format
567 elif 'adm1' in row:
568 pin_adm = ''.join(['%02x' % (ord(x)) for x in row['adm1']])
569 if pin_adm:
570 row['pin_adm'] = rpad(pin_adm, 16)
Philipp Maiere053da52019-09-05 13:08:36 +0200571
Harald Weltec91085e2022-02-10 18:05:45 +0100572 # If the CSV-File defines a pin_adm_hex field use this field to
573 # generate pin_adm from that.
574 pin_adm_hex = row.get('pin_adm_hex')
575 if pin_adm_hex:
576 if len(pin_adm_hex) == 16:
577 row['pin_adm'] = pin_adm_hex
578 # Ensure that it's hex-encoded
579 try:
580 try_encode = h2b(pin_adm)
581 except ValueError:
582 raise ValueError(
583 "pin_adm_hex needs to be hex encoded using this option")
584 else:
585 raise ValueError(
586 "pin_adm_hex needs to be exactly 16 digits (hex encoded)")
Philipp Maiere053da52019-09-05 13:08:36 +0200587
Harald Weltec91085e2022-02-10 18:05:45 +0100588 return row
Harald Welte7f62cec2012-08-13 20:07:41 +0200589
Harald Weltec26b8292012-08-15 15:25:51 +0200590
Harald Welte130524b2012-08-13 15:53:43 +0200591def write_params_hlr(opts, params):
Harald Weltec91085e2022-02-10 18:05:45 +0100592 # SQLite3 OpenBSC HLR
593 if opts.write_hlr:
594 import sqlite3
595 conn = sqlite3.connect(opts.write_hlr)
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100596
Harald Weltec91085e2022-02-10 18:05:45 +0100597 c = conn.execute(
598 'INSERT INTO Subscriber ' +
599 '(imsi, name, extension, authorized, created, updated) ' +
600 'VALUES ' +
601 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
602 [
603 params['imsi'],
604 params['name'],
605 '9' + params['iccid'][-5:-1]
606 ],
607 )
608 sub_id = c.lastrowid
609 c.close()
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100610
Harald Weltec91085e2022-02-10 18:05:45 +0100611 c = conn.execute(
612 'INSERT INTO AuthKeys ' +
613 '(subscriber_id, algorithm_id, a3a8_ki)' +
614 'VALUES ' +
615 '(?,?,?)',
616 [sub_id, 2, sqlite3.Binary(
617 _dbi_binary_quote(h2b(params['ki'])))],
618 )
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100619
Harald Weltec91085e2022-02-10 18:05:45 +0100620 conn.commit()
621 conn.close()
622
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100623
Harald Welte130524b2012-08-13 15:53:43 +0200624def write_parameters(opts, params):
Harald Weltec91085e2022-02-10 18:05:45 +0100625 write_params_csv(opts, params)
626 write_params_hlr(opts, params)
Harald Welte130524b2012-08-13 15:53:43 +0200627
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100628
Harald Weltec91085e2022-02-10 18:05:45 +0100629BATCH_STATE = ['name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num']
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100630BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100631
Harald Weltec91085e2022-02-10 18:05:45 +0100632
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100633def init_batch(opts):
Harald Weltec91085e2022-02-10 18:05:45 +0100634 # Need to do something ?
635 if not opts.batch_mode:
636 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100637
Harald Weltec91085e2022-02-10 18:05:45 +0100638 for k in BATCH_INCOMPATIBLE:
639 if getattr(opts, k):
640 print("Incompatible option with batch_state: %s" % (k,))
641 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100642
Harald Weltec91085e2022-02-10 18:05:45 +0100643 # Don't load state if there is none ...
644 if not opts.batch_state:
645 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100646
Harald Weltec91085e2022-02-10 18:05:45 +0100647 if not os.path.isfile(opts.batch_state):
648 print("No state file yet")
649 return
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100650
Harald Weltec91085e2022-02-10 18:05:45 +0100651 # Get stored data
652 fh = open(opts.batch_state)
653 d = json.loads(fh.read())
654 fh.close()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100655
Harald Weltec91085e2022-02-10 18:05:45 +0100656 for k, v in d.iteritems():
657 setattr(opts, k, v)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100658
659
660def save_batch(opts):
Harald Weltec91085e2022-02-10 18:05:45 +0100661 # Need to do something ?
662 if not opts.batch_mode or not opts.batch_state:
663 return
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100664
Harald Weltec91085e2022-02-10 18:05:45 +0100665 d = json.dumps(dict([(k, getattr(opts, k)) for k in BATCH_STATE]))
666 fh = open(opts.batch_state, 'w')
667 fh.write(d)
668 fh.close()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100669
670
Philipp Maier82511e52021-09-17 13:38:36 +0200671def process_card(opts, first, ch):
Philipp Maierc5b422e2019-08-30 11:41:02 +0200672
Harald Weltec91085e2022-02-10 18:05:45 +0100673 if opts.dry_run is False:
674 # Connect transport
675 ch.get(first)
Philipp Maierc5b422e2019-08-30 11:41:02 +0200676
Harald Weltec91085e2022-02-10 18:05:45 +0100677 if opts.dry_run is False:
678 # Get card
679 card = card_detect(opts.type, scc)
680 if card is None:
681 print("No card detected!")
682 return -1
Philipp Maierc5b422e2019-08-30 11:41:02 +0200683
Harald Weltec91085e2022-02-10 18:05:45 +0100684 # Probe only
685 if opts.probe:
686 return 0
Philipp Maierc5b422e2019-08-30 11:41:02 +0200687
Harald Weltec91085e2022-02-10 18:05:45 +0100688 # Erase if requested
689 if opts.erase:
690 print("Formatting ...")
691 card.erase()
692 card.reset()
Philipp Maierc5b422e2019-08-30 11:41:02 +0200693
Harald Weltec91085e2022-02-10 18:05:45 +0100694 # Generate parameters
695 if opts.source == 'cmdline':
696 cp = gen_parameters(opts)
697 elif opts.source == 'csv':
698 imsi = None
699 iccid = None
700 if opts.read_iccid:
701 if opts.dry_run:
702 # Connect transport
703 ch.get(False)
704 (res, _) = scc.read_binary(['3f00', '2fe2'], length=10)
705 iccid = dec_iccid(res)
706 elif opts.read_imsi:
707 if opts.dry_run:
708 # Connect transport
709 ch.get(False)
710 (res, _) = scc.read_binary(EF['IMSI'])
711 imsi = swap_nibbles(res)[3:]
712 else:
713 imsi = opts.imsi
714 cp = read_params_csv(opts, imsi=imsi, iccid=iccid)
715 if cp is None:
716 print("Error reading parameters from CSV file!\n")
717 return 2
718 print_parameters(cp)
Philipp Maierc5b422e2019-08-30 11:41:02 +0200719
Harald Weltec91085e2022-02-10 18:05:45 +0100720 if opts.dry_run is False:
721 # Program the card
722 print("Programming ...")
723 card.program(cp)
724 else:
725 print("Dry Run: NOT PROGRAMMING!")
Philipp Maierc5b422e2019-08-30 11:41:02 +0200726
Harald Weltec91085e2022-02-10 18:05:45 +0100727 # Write parameters permanently
728 write_parameters(opts, cp)
Philipp Maierc5b422e2019-08-30 11:41:02 +0200729
Harald Weltec91085e2022-02-10 18:05:45 +0100730 # Batch mode state update and save
731 if opts.num is not None:
732 opts.num += 1
733 save_batch(opts)
Philipp Maierc5b422e2019-08-30 11:41:02 +0200734
Harald Weltec91085e2022-02-10 18:05:45 +0100735 ch.done()
736 return 0
Philipp Maierc5b422e2019-08-30 11:41:02 +0200737
738
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100739if __name__ == '__main__':
740
Harald Weltec91085e2022-02-10 18:05:45 +0100741 # Parse options
742 opts = parse_options()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100743
Harald Weltec91085e2022-02-10 18:05:45 +0100744 # Init card reader driver
745 sl = init_reader(opts)
746 if sl is None:
747 exit(1)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100748
Harald Weltec91085e2022-02-10 18:05:45 +0100749 # Create command layer
750 scc = SimCardCommands(transport=sl)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100751
Harald Weltec91085e2022-02-10 18:05:45 +0100752 # If we use a CSV file as data input, check if the CSV file exists.
753 if opts.source == 'csv':
754 print("Using CSV file as data input: " + str(opts.read_csv))
755 if not os.path.isfile(opts.read_csv):
756 print("CSV file not found!")
757 sys.exit(1)
Philipp Maier196b08c2019-09-12 11:49:44 +0200758
Harald Weltec91085e2022-02-10 18:05:45 +0100759 # Batch mode init
760 init_batch(opts)
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100761
Harald Weltec91085e2022-02-10 18:05:45 +0100762 if opts.card_handler_config:
763 ch = CardHandlerAuto(sl, opts.card_handler_config)
764 else:
765 ch = CardHandler(sl)
Philipp Maierc5b422e2019-08-30 11:41:02 +0200766
Harald Weltec91085e2022-02-10 18:05:45 +0100767 # Iterate
768 first = True
769 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100770
Harald Weltec91085e2022-02-10 18:05:45 +0100771 while 1:
772 try:
773 rc = process_card(opts, first, ch)
774 except (KeyboardInterrupt):
775 print("")
776 print("Terminated by user!")
777 sys.exit(0)
778 except (SystemExit):
779 raise
780 except:
781 print("")
782 print("Card programming failed with an exception:")
783 print("---------------------8<---------------------")
784 traceback.print_exc()
785 print("---------------------8<---------------------")
786 print("")
787 rc = -1
Harald Weltee9e5ecb2012-08-15 15:26:30 +0200788
Harald Weltec91085e2022-02-10 18:05:45 +0100789 # Something did not work as well as expected, however, lets
790 # make sure the card is pulled from the reader.
791 if rc != 0:
792 ch.error()
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100793
Harald Weltec91085e2022-02-10 18:05:45 +0100794 # If we are not in batch mode we are done in any case, so lets
795 # exit here.
796 if not opts.batch_mode:
797 sys.exit(rc)
Philipp Maierc5b422e2019-08-30 11:41:02 +0200798
Harald Weltec91085e2022-02-10 18:05:45 +0100799 first = False