blob: 9f240db21bb0ed6994a176e43c9a0228d1e600fa [file] [log] [blame]
Sylvain Munaut76504e02010-12-07 00:24:32 +01001#!/usr/bin/env python
2
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
33
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +010034try:
35 import json
Holger Hans Peter Freyther5dffefb2011-11-22 21:18:06 +010036except ImportError:
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +010037 # Python < 2.5
38 import simplejson as json
39
Sylvain Munaut76504e02010-12-07 00:24:32 +010040from pySim.commands import SimCardCommands
41from pySim.cards import _cards_classes
Sylvain Munaut607ce2a2011-12-08 20:16:43 +010042from pySim.utils import h2b, swap_nibbles, rpad
Sylvain Munaut76504e02010-12-07 00:24:32 +010043
44
45def parse_options():
46
47 parser = OptionParser(usage="usage: %prog [options]")
48
49 parser.add_option("-d", "--device", dest="device", metavar="DEV",
50 help="Serial Device for SIM access [default: %default]",
51 default="/dev/ttyUSB0",
52 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010053 parser.add_option("-b", "--baud", dest="baudrate", type="int", metavar="BAUD",
54 help="Baudrate used for SIM access [default: %default]",
55 default=9600,
56 )
Sylvain Munaut9c8729a2010-12-08 23:20:27 +010057 parser.add_option("-p", "--pcsc-device", dest="pcsc_dev", type='int', metavar="PCSC",
Sylvain Munaute9fdecb2010-12-08 22:33:19 +010058 help="Which PC/SC reader number for SIM access",
59 default=None,
60 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010061 parser.add_option("-t", "--type", dest="type",
62 help="Card type (user -t list to view) [default: %default]",
63 default="auto",
64 )
65 parser.add_option("-e", "--erase", dest="erase", action='store_true',
66 help="Erase beforehand [default: %default]",
67 default=False,
68 )
69
70 parser.add_option("-n", "--name", dest="name",
71 help="Operator name [default: %default]",
72 default="Magic",
73 )
74 parser.add_option("-c", "--country", dest="country", type="int", metavar="CC",
75 help="Country code [default: %default]",
76 default=1,
77 )
78 parser.add_option("-x", "--mcc", dest="mcc", type="int",
79 help="Mobile Country Code [default: %default]",
80 default=901,
81 )
82 parser.add_option("-y", "--mnc", dest="mnc", type="int",
Sylvain Munaut17716032010-12-08 22:33:51 +010083 help="Mobile Network Code [default: %default]",
Sylvain Munaut76504e02010-12-07 00:24:32 +010084 default=55,
85 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +010086 parser.add_option("-m", "--smsc", dest="smsc",
Sylvain Munaut76504e02010-12-07 00:24:32 +010087 help="SMSP [default: '00 + country code + 5555']",
88 )
Sylvain Munaut607ce2a2011-12-08 20:16:43 +010089 parser.add_option("-M", "--smsp", dest="smsp",
90 help="Raw SMSP content in hex [default: auto from SMSC]",
91 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010092
93 parser.add_option("-s", "--iccid", dest="iccid", metavar="ID",
94 help="Integrated Circuit Card ID",
95 )
96 parser.add_option("-i", "--imsi", dest="imsi",
97 help="International Mobile Subscriber Identity",
98 )
99 parser.add_option("-k", "--ki", dest="ki",
100 help="Ki (default is to randomize)",
101 )
102
103 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
104 help="Secret used for ICCID/IMSI autogen",
105 )
106 parser.add_option("-j", "--num", dest="num", type=int,
107 help="Card # used for ICCID/IMSI autogen",
108 )
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100109 parser.add_option("--batch", dest="batch_mode",
110 help="Enable batch mode [default: %default]",
111 default=False, action='store_true',
112 )
113 parser.add_option("--batch-state", dest="batch_state", metavar="FILE",
114 help="Optional batch state file",
115 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100116
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100117 parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
118 help="Append generated parameters in CSV file",
119 )
120 parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
121 help="Append generated parameters to OpenBSC HLR sqlite3",
122 )
123
Sylvain Munaut76504e02010-12-07 00:24:32 +0100124 (options, args) = parser.parse_args()
125
126 if options.type == 'list':
127 for kls in _cards_classes:
128 print kls.name
129 sys.exit(0)
130
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100131 if (options.batch_mode) and (options.num is None):
132 options.num = 0
133
Sylvain Munaut98d2b852010-12-23 20:27:25 +0100134 if (options.batch_mode):
135 if (options.imsi is not None) or (options.iccid is not None):
136 parser.error("Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more informations")
137
Sylvain Munaut76504e02010-12-07 00:24:32 +0100138 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
139 parser.error("If either IMSI or ICCID isn't specified, num is required")
140
141 if args:
142 parser.error("Extraneous arguments")
143
144 return options
145
146
147def _digits(secret, usage, len, num):
148 s = hashlib.sha1(secret + usage + '%d' % num)
149 d = ''.join(['%02d'%ord(x) for x in s.digest()])
150 return d[0:len]
151
152def _mcc_mnc_digits(mcc, mnc):
153 return ('%03d%03d' if mnc > 100 else '%03d%02d') % (mcc, mnc)
154
155def _cc_digits(cc):
156 return ('%03d' if cc > 100 else '%02d') % cc
157
158def _isnum(s, l=-1):
159 return s.isdigit() and ((l== -1) or (len(s) == l))
160
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100161def _ishex(s, l=-1):
162 hc = '0123456789abcdef'
163 return all([x in hc for x in s.lower()]) and ((l== -1) or (len(s) == l))
164
Sylvain Munaut76504e02010-12-07 00:24:32 +0100165
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100166def _dbi_binary_quote(s):
167 # Count usage of each char
168 cnt = {}
169 for c in s:
170 cnt[c] = cnt.get(c, 0) + 1
171
172 # Find best offset
173 e = 0
174 m = len(s)
175 for i in range(1, 256):
176 if i == 39:
177 continue
178 sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
179 if sum_ < m:
180 m = sum_
181 e = i
182 if m == 0: # No overhead ? use this !
183 break;
Sylvain Munaut1a914432011-12-08 20:08:26 +0100184
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100185 # Generate output
186 out = []
187 out.append( chr(e) ) # Offset
188 for c in s:
189 x = (256 + ord(c) - e) % 256
190 if x in (0, 1, 39):
191 out.append('\x01')
192 out.append(chr(x+1))
193 else:
194 out.append(chr(x))
195
196 return ''.join(out)
197
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100198def calculate_luhn(cc):
199 num = map(int, str(cc))
200 check_digit = 10 - sum(num[-2::-2] + [sum(divmod(d * 2, 10)) for d in num[::-2]]) % 10
201 return 0 if check_digit == 10 else check_digit
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100202
Sylvain Munaut76504e02010-12-07 00:24:32 +0100203def gen_parameters(opts):
204 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki from the
205 options given by the user"""
206
207 # MCC/MNC
208 mcc = opts.mcc
209 mnc = opts.mnc
210
211 if not ((0 < mcc < 999) and (0 < mnc < 999)):
212 raise ValueError('mcc & mnc must be between 0 and 999')
213
214 # Digitize country code (2 or 3 digits)
215 cc_digits = _cc_digits(opts.country)
216
217 # Digitize MCC/MNC (5 or 6 digits)
218 plmn_digits = _mcc_mnc_digits(mcc, mnc)
219
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100220 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
Sylvain Munaut76504e02010-12-07 00:24:32 +0100221 if opts.iccid is not None:
222 iccid = opts.iccid
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100223 if not _isnum(iccid, 19):
224 raise ValueError('ICCID must be 19 digits !');
Sylvain Munaut76504e02010-12-07 00:24:32 +0100225
226 else:
227 if opts.num is None:
228 raise ValueError('Neither ICCID nor card number specified !')
229
230 iccid = (
231 '89' + # Common prefix (telecom)
232 cc_digits + # Country Code on 2/3 digits
233 plmn_digits # MCC/MNC on 5/6 digits
234 )
235
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100236 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100237
238 if opts.secret is None:
239 # The raw number
240 iccid += ('%%0%dd' % ml) % opts.num
241 else:
242 # Randomized digits
243 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
244
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100245 # Add checksum digit
246 iccid += ('%1d' % calculate_luhn(iccid))
247
Sylvain Munaut76504e02010-12-07 00:24:32 +0100248 # IMSI (15 digits usually)
249 if opts.imsi is not None:
250 imsi = opts.imsi
251 if not _isnum(imsi):
252 raise ValueError('IMSI must be digits only !')
253
254 else:
255 if opts.num is None:
256 raise ValueError('Neither IMSI nor card number specified !')
257
258 ml = 15 - len(plmn_digits)
259
260 if opts.secret is None:
261 # The raw number
262 msin = ('%%0%dd' % ml) % opts.num
263 else:
264 # Randomized digits
265 msin = _digits(opts.secret, 'imsi', ml, opts.num)
266
267 imsi = (
268 plmn_digits + # MCC/MNC on 5/6 digits
269 msin # MSIN
270 )
271
272 # SMSP
273 if opts.smsp is not None:
274 smsp = opts.smsp
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100275 if not _ishex(smsp):
276 raise ValueError('SMSP must be hex digits only !')
277 if len(smsp) < 28*2:
278 raise ValueError('SMSP must be at least 28 bytes')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100279
280 else:
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100281 if opts.smsc is not None:
282 smsc = opts.smsc
283 if not _isnum(smsc):
284 raise ValueError('SMSC must be digits only !')
285 else:
286 smsc = '00%d' % opts.country + '5555' # Hack ...
287
288 smsc = '%02d' % ((len(smsc) + 3)//2,) + "80" + swap_nibbles(rpad(smsc, 20))
289
290 smsp = (
291 'e1' + # Parameters indicator
292 'ff' * 12 + # TP-Destination address
293 smsc + # TP-Service Centre Address
294 '00' + # TP-Protocol identifier
295 '00' + # TP-Data coding scheme
296 '00' # TP-Validity period
297 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100298
299 # Ki (random)
300 if opts.ki is not None:
301 ki = opts.ki
302 if not re.match('^[0-9a-fA-F]{32}$', ki):
303 raise ValueError('Ki needs to be 128 bits, in hex format')
304
305 else:
306 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
307
308 # Return that
309 return {
310 'name' : opts.name,
311 'iccid' : iccid,
312 'mcc' : mcc,
313 'mnc' : mnc,
314 'imsi' : imsi,
315 'smsp' : smsp,
316 'ki' : ki,
317 }
318
319
320def print_parameters(params):
321
322 print """Generated card parameters :
323 > Name : %(name)s
324 > SMSP : %(smsp)s
325 > ICCID : %(iccid)s
326 > MCC/MNC : %(mcc)d/%(mnc)d
327 > IMSI : %(imsi)s
328 > Ki : %(ki)s
329""" % params
330
331
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100332def write_parameters(opts, params):
333 # CSV
334 if opts.write_csv:
335 import csv
336 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki']
337 f = open(opts.write_csv, 'a')
338 cw = csv.writer(f)
339 cw.writerow([params[x] for x in row])
340 f.close()
341
342 # SQLite3 OpenBSC HLR
343 if opts.write_hlr:
344 import sqlite3
345 conn = sqlite3.connect(opts.write_hlr)
346
347 c = conn.execute(
348 'INSERT INTO Subscriber ' +
349 '(imsi, name, extension, authorized, created, updated) ' +
350 'VALUES ' +
351 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
352 [
353 params['imsi'],
354 params['name'],
355 '9' + params['iccid'][-5:]
356 ],
357 )
358 sub_id = c.lastrowid
359 c.close()
360
361 c = conn.execute(
362 'INSERT INTO AuthKeys ' +
363 '(subscriber_id, algorithm_id, a3a8_ki)' +
364 'VALUES ' +
365 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100366 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100367 )
368
369 conn.commit()
370 conn.close()
371
372
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100373BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
374BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100375
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100376def init_batch(opts):
377 # Need to do something ?
378 if not opts.batch_mode:
379 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100380
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100381 for k in BATCH_INCOMPATIBLE:
382 if getattr(opts, k):
383 print "Incompatible option with batch_state: %s" % (k,)
384 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100385
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100386 # Don't load state if there is none ...
387 if not opts.batch_state:
388 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100389
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100390 if not os.path.isfile(opts.batch_state):
391 print "No state file yet"
392 return
393
394 # Get stored data
395 fh = open(opts.batch_state)
396 d = json.loads(fh.read())
397 fh.close()
398
399 for k,v in d.iteritems():
400 setattr(opts, k, v)
401
402
403def save_batch(opts):
404 # Need to do something ?
405 if not opts.batch_mode or not opts.batch_state:
406 return
407
408 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
409 fh = open(opts.batch_state, 'w')
410 fh.write(d)
411 fh.close()
412
413
414def card_detect(opts, scc):
Sylvain Munautbdca2522010-12-09 13:31:58 +0100415
Sylvain Munaut76504e02010-12-07 00:24:32 +0100416 # Detect type if needed
417 card = None
418 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
419
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100420 if opts.type in ("auto", "auto_once"):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100421 for kls in _cards_classes:
422 card = kls.autodetect(scc)
423 if card:
424 print "Autodetected card type %s" % card.name
425 card.reset()
426 break
427
428 if card is None:
429 print "Autodetection failed"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100430 return
431
432 if opts.type == "auto_once":
433 opts.type = card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100434
435 elif opts.type in ctypes:
436 card = ctypes[opts.type](scc)
437
438 else:
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100439 raise ValueError("Unknown card type %s" % opts.type)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100440
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100441 return card
Sylvain Munaut76504e02010-12-07 00:24:32 +0100442
Sylvain Munaut76504e02010-12-07 00:24:32 +0100443
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100444if __name__ == '__main__':
445
446 # Parse options
447 opts = parse_options()
448
449 # Connect to the card
450 if opts.pcsc_dev is None:
451 from pySim.transport.serial import SerialSimLink
452 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
453 else:
454 from pySim.transport.pcsc import PcscSimLink
455 sl = PcscSimLink(opts.pcsc_dev)
456
457 # Create command layer
458 scc = SimCardCommands(transport=sl)
459
460 # Batch mode init
461 init_batch(opts)
462
463 # Iterate
464 done = False
465 first = True
466 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100467
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100468 while not done:
469 # Connect transport
470 print "Insert card now (or CTRL-C to cancel)"
471 sl.wait_for_card(newcardonly=not first)
472
473 # Not the first anymore !
474 first = False
475
476 # Get card
477 card = card_detect(opts, scc)
478 if card is None:
479 if opts.batch_mode:
480 first = False
481 continue
482 else:
483 sys.exit(-1)
484
485 # Erase if requested
486 if opts.erase:
487 print "Formatting ..."
488 card.erase()
489 card.reset()
490
491 # Generate parameters
492 cp = gen_parameters(opts)
493 print_parameters(cp)
494
495 # Program the card
496 print "Programming ..."
497 card.program(cp)
498
499 # Write parameters permanently
500 write_parameters(opts, cp)
501
502 # Batch mode state update and save
Sylvain Munaut8d243e82010-12-23 20:27:48 +0100503 if opts.num is not None:
504 opts.num += 1
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100505 save_batch(opts)
506
507 # Done for this card and maybe for everything ?
508 print "Done !\n"
509
510 if not opts.batch_mode:
511 done = True
Sylvain Munaut76504e02010-12-07 00:24:32 +0100512