blob: 493d434379536af0364f52f1226bc9450a6cfd90 [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 Munaut143e99d2010-12-08 22:35:04 +010042from pySim.utils import h2b
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 )
86 parser.add_option("-m", "--smsp", dest="smsp",
87 help="SMSP [default: '00 + country code + 5555']",
88 )
89
90 parser.add_option("-s", "--iccid", dest="iccid", metavar="ID",
91 help="Integrated Circuit Card ID",
92 )
93 parser.add_option("-i", "--imsi", dest="imsi",
94 help="International Mobile Subscriber Identity",
95 )
96 parser.add_option("-k", "--ki", dest="ki",
97 help="Ki (default is to randomize)",
98 )
99
100 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
101 help="Secret used for ICCID/IMSI autogen",
102 )
103 parser.add_option("-j", "--num", dest="num", type=int,
104 help="Card # used for ICCID/IMSI autogen",
105 )
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100106 parser.add_option("--batch", dest="batch_mode",
107 help="Enable batch mode [default: %default]",
108 default=False, action='store_true',
109 )
110 parser.add_option("--batch-state", dest="batch_state", metavar="FILE",
111 help="Optional batch state file",
112 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100113
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100114 parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
115 help="Append generated parameters in CSV file",
116 )
117 parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
118 help="Append generated parameters to OpenBSC HLR sqlite3",
119 )
120
Sylvain Munaut76504e02010-12-07 00:24:32 +0100121 (options, args) = parser.parse_args()
122
123 if options.type == 'list':
124 for kls in _cards_classes:
125 print kls.name
126 sys.exit(0)
127
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100128 if (options.batch_mode) and (options.num is None):
129 options.num = 0
130
Sylvain Munaut98d2b852010-12-23 20:27:25 +0100131 if (options.batch_mode):
132 if (options.imsi is not None) or (options.iccid is not None):
133 parser.error("Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more informations")
134
Sylvain Munaut76504e02010-12-07 00:24:32 +0100135 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
136 parser.error("If either IMSI or ICCID isn't specified, num is required")
137
138 if args:
139 parser.error("Extraneous arguments")
140
141 return options
142
143
144def _digits(secret, usage, len, num):
145 s = hashlib.sha1(secret + usage + '%d' % num)
146 d = ''.join(['%02d'%ord(x) for x in s.digest()])
147 return d[0:len]
148
149def _mcc_mnc_digits(mcc, mnc):
150 return ('%03d%03d' if mnc > 100 else '%03d%02d') % (mcc, mnc)
151
152def _cc_digits(cc):
153 return ('%03d' if cc > 100 else '%02d') % cc
154
155def _isnum(s, l=-1):
156 return s.isdigit() and ((l== -1) or (len(s) == l))
157
158
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100159def _dbi_binary_quote(s):
160 # Count usage of each char
161 cnt = {}
162 for c in s:
163 cnt[c] = cnt.get(c, 0) + 1
164
165 # Find best offset
166 e = 0
167 m = len(s)
168 for i in range(1, 256):
169 if i == 39:
170 continue
171 sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
172 if sum_ < m:
173 m = sum_
174 e = i
175 if m == 0: # No overhead ? use this !
176 break;
177
178 # Generate output
179 out = []
180 out.append( chr(e) ) # Offset
181 for c in s:
182 x = (256 + ord(c) - e) % 256
183 if x in (0, 1, 39):
184 out.append('\x01')
185 out.append(chr(x+1))
186 else:
187 out.append(chr(x))
188
189 return ''.join(out)
190
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100191def calculate_luhn(cc):
192 num = map(int, str(cc))
193 check_digit = 10 - sum(num[-2::-2] + [sum(divmod(d * 2, 10)) for d in num[::-2]]) % 10
194 return 0 if check_digit == 10 else check_digit
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100195
Sylvain Munaut76504e02010-12-07 00:24:32 +0100196def gen_parameters(opts):
197 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki from the
198 options given by the user"""
199
200 # MCC/MNC
201 mcc = opts.mcc
202 mnc = opts.mnc
203
204 if not ((0 < mcc < 999) and (0 < mnc < 999)):
205 raise ValueError('mcc & mnc must be between 0 and 999')
206
207 # Digitize country code (2 or 3 digits)
208 cc_digits = _cc_digits(opts.country)
209
210 # Digitize MCC/MNC (5 or 6 digits)
211 plmn_digits = _mcc_mnc_digits(mcc, mnc)
212
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100213 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
Sylvain Munaut76504e02010-12-07 00:24:32 +0100214 if opts.iccid is not None:
215 iccid = opts.iccid
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100216 if not _isnum(iccid, 19):
217 raise ValueError('ICCID must be 19 digits !');
Sylvain Munaut76504e02010-12-07 00:24:32 +0100218
219 else:
220 if opts.num is None:
221 raise ValueError('Neither ICCID nor card number specified !')
222
223 iccid = (
224 '89' + # Common prefix (telecom)
225 cc_digits + # Country Code on 2/3 digits
226 plmn_digits # MCC/MNC on 5/6 digits
227 )
228
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100229 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100230
231 if opts.secret is None:
232 # The raw number
233 iccid += ('%%0%dd' % ml) % opts.num
234 else:
235 # Randomized digits
236 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
237
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100238 # Add checksum digit
239 iccid += ('%1d' % calculate_luhn(iccid))
240
Sylvain Munaut76504e02010-12-07 00:24:32 +0100241 # IMSI (15 digits usually)
242 if opts.imsi is not None:
243 imsi = opts.imsi
244 if not _isnum(imsi):
245 raise ValueError('IMSI must be digits only !')
246
247 else:
248 if opts.num is None:
249 raise ValueError('Neither IMSI nor card number specified !')
250
251 ml = 15 - len(plmn_digits)
252
253 if opts.secret is None:
254 # The raw number
255 msin = ('%%0%dd' % ml) % opts.num
256 else:
257 # Randomized digits
258 msin = _digits(opts.secret, 'imsi', ml, opts.num)
259
260 imsi = (
261 plmn_digits + # MCC/MNC on 5/6 digits
262 msin # MSIN
263 )
264
265 # SMSP
266 if opts.smsp is not None:
267 smsp = opts.smsp
268 if not _isnum(smsp):
269 raise ValueError('SMSP must be digits only !')
270
271 else:
272 smsp = '00%d' % opts.country + '5555' # Hack ...
273
274 # Ki (random)
275 if opts.ki is not None:
276 ki = opts.ki
277 if not re.match('^[0-9a-fA-F]{32}$', ki):
278 raise ValueError('Ki needs to be 128 bits, in hex format')
279
280 else:
281 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
282
283 # Return that
284 return {
285 'name' : opts.name,
286 'iccid' : iccid,
287 'mcc' : mcc,
288 'mnc' : mnc,
289 'imsi' : imsi,
290 'smsp' : smsp,
291 'ki' : ki,
292 }
293
294
295def print_parameters(params):
296
297 print """Generated card parameters :
298 > Name : %(name)s
299 > SMSP : %(smsp)s
300 > ICCID : %(iccid)s
301 > MCC/MNC : %(mcc)d/%(mnc)d
302 > IMSI : %(imsi)s
303 > Ki : %(ki)s
304""" % params
305
306
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100307def write_parameters(opts, params):
308 # CSV
309 if opts.write_csv:
310 import csv
311 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki']
312 f = open(opts.write_csv, 'a')
313 cw = csv.writer(f)
314 cw.writerow([params[x] for x in row])
315 f.close()
316
317 # SQLite3 OpenBSC HLR
318 if opts.write_hlr:
319 import sqlite3
320 conn = sqlite3.connect(opts.write_hlr)
321
322 c = conn.execute(
323 'INSERT INTO Subscriber ' +
324 '(imsi, name, extension, authorized, created, updated) ' +
325 'VALUES ' +
326 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
327 [
328 params['imsi'],
329 params['name'],
330 '9' + params['iccid'][-5:]
331 ],
332 )
333 sub_id = c.lastrowid
334 c.close()
335
336 c = conn.execute(
337 'INSERT INTO AuthKeys ' +
338 '(subscriber_id, algorithm_id, a3a8_ki)' +
339 'VALUES ' +
340 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100341 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100342 )
343
344 conn.commit()
345 conn.close()
346
347
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100348BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
349BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100350
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100351def init_batch(opts):
352 # Need to do something ?
353 if not opts.batch_mode:
354 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100355
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100356 for k in BATCH_INCOMPATIBLE:
357 if getattr(opts, k):
358 print "Incompatible option with batch_state: %s" % (k,)
359 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100360
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100361 # Don't load state if there is none ...
362 if not opts.batch_state:
363 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100364
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100365 if not os.path.isfile(opts.batch_state):
366 print "No state file yet"
367 return
368
369 # Get stored data
370 fh = open(opts.batch_state)
371 d = json.loads(fh.read())
372 fh.close()
373
374 for k,v in d.iteritems():
375 setattr(opts, k, v)
376
377
378def save_batch(opts):
379 # Need to do something ?
380 if not opts.batch_mode or not opts.batch_state:
381 return
382
383 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
384 fh = open(opts.batch_state, 'w')
385 fh.write(d)
386 fh.close()
387
388
389def card_detect(opts, scc):
Sylvain Munautbdca2522010-12-09 13:31:58 +0100390
Sylvain Munaut76504e02010-12-07 00:24:32 +0100391 # Detect type if needed
392 card = None
393 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
394
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100395 if opts.type in ("auto", "auto_once"):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100396 for kls in _cards_classes:
397 card = kls.autodetect(scc)
398 if card:
399 print "Autodetected card type %s" % card.name
400 card.reset()
401 break
402
403 if card is None:
404 print "Autodetection failed"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100405 return
406
407 if opts.type == "auto_once":
408 opts.type = card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100409
410 elif opts.type in ctypes:
411 card = ctypes[opts.type](scc)
412
413 else:
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100414 raise ValueError("Unknown card type %s" % opts.type)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100415
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100416 return card
Sylvain Munaut76504e02010-12-07 00:24:32 +0100417
Sylvain Munaut76504e02010-12-07 00:24:32 +0100418
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100419if __name__ == '__main__':
420
421 # Parse options
422 opts = parse_options()
423
424 # Connect to the card
425 if opts.pcsc_dev is None:
426 from pySim.transport.serial import SerialSimLink
427 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
428 else:
429 from pySim.transport.pcsc import PcscSimLink
430 sl = PcscSimLink(opts.pcsc_dev)
431
432 # Create command layer
433 scc = SimCardCommands(transport=sl)
434
435 # Batch mode init
436 init_batch(opts)
437
438 # Iterate
439 done = False
440 first = True
441 card = None
442
443 while not done:
444 # Connect transport
445 print "Insert card now (or CTRL-C to cancel)"
446 sl.wait_for_card(newcardonly=not first)
447
448 # Not the first anymore !
449 first = False
450
451 # Get card
452 card = card_detect(opts, scc)
453 if card is None:
454 if opts.batch_mode:
455 first = False
456 continue
457 else:
458 sys.exit(-1)
459
460 # Erase if requested
461 if opts.erase:
462 print "Formatting ..."
463 card.erase()
464 card.reset()
465
466 # Generate parameters
467 cp = gen_parameters(opts)
468 print_parameters(cp)
469
470 # Program the card
471 print "Programming ..."
472 card.program(cp)
473
474 # Write parameters permanently
475 write_parameters(opts, cp)
476
477 # Batch mode state update and save
Sylvain Munaut8d243e82010-12-23 20:27:48 +0100478 if opts.num is not None:
479 opts.num += 1
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100480 save_batch(opts)
481
482 # Done for this card and maybe for everything ?
483 print "Done !\n"
484
485 if not opts.batch_mode:
486 done = True
Sylvain Munaut76504e02010-12-07 00:24:32 +0100487