blob: d057a51e534d480bf49c06bf0c72da910a597f51 [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
191
Sylvain Munaut76504e02010-12-07 00:24:32 +0100192def gen_parameters(opts):
193 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki from the
194 options given by the user"""
195
196 # MCC/MNC
197 mcc = opts.mcc
198 mnc = opts.mnc
199
200 if not ((0 < mcc < 999) and (0 < mnc < 999)):
201 raise ValueError('mcc & mnc must be between 0 and 999')
202
203 # Digitize country code (2 or 3 digits)
204 cc_digits = _cc_digits(opts.country)
205
206 # Digitize MCC/MNC (5 or 6 digits)
207 plmn_digits = _mcc_mnc_digits(mcc, mnc)
208
209 # ICCID (20 digits)
210 if opts.iccid is not None:
211 iccid = opts.iccid
212 if not _isnum(iccid, 20):
213 raise ValueError('ICCID must be 20 digits !');
214
215 else:
216 if opts.num is None:
217 raise ValueError('Neither ICCID nor card number specified !')
218
219 iccid = (
220 '89' + # Common prefix (telecom)
221 cc_digits + # Country Code on 2/3 digits
222 plmn_digits # MCC/MNC on 5/6 digits
223 )
224
225 ml = 20 - len(iccid)
226
227 if opts.secret is None:
228 # The raw number
229 iccid += ('%%0%dd' % ml) % opts.num
230 else:
231 # Randomized digits
232 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
233
234 # IMSI (15 digits usually)
235 if opts.imsi is not None:
236 imsi = opts.imsi
237 if not _isnum(imsi):
238 raise ValueError('IMSI must be digits only !')
239
240 else:
241 if opts.num is None:
242 raise ValueError('Neither IMSI nor card number specified !')
243
244 ml = 15 - len(plmn_digits)
245
246 if opts.secret is None:
247 # The raw number
248 msin = ('%%0%dd' % ml) % opts.num
249 else:
250 # Randomized digits
251 msin = _digits(opts.secret, 'imsi', ml, opts.num)
252
253 imsi = (
254 plmn_digits + # MCC/MNC on 5/6 digits
255 msin # MSIN
256 )
257
258 # SMSP
259 if opts.smsp is not None:
260 smsp = opts.smsp
261 if not _isnum(smsp):
262 raise ValueError('SMSP must be digits only !')
263
264 else:
265 smsp = '00%d' % opts.country + '5555' # Hack ...
266
267 # Ki (random)
268 if opts.ki is not None:
269 ki = opts.ki
270 if not re.match('^[0-9a-fA-F]{32}$', ki):
271 raise ValueError('Ki needs to be 128 bits, in hex format')
272
273 else:
274 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
275
276 # Return that
277 return {
278 'name' : opts.name,
279 'iccid' : iccid,
280 'mcc' : mcc,
281 'mnc' : mnc,
282 'imsi' : imsi,
283 'smsp' : smsp,
284 'ki' : ki,
285 }
286
287
288def print_parameters(params):
289
290 print """Generated card parameters :
291 > Name : %(name)s
292 > SMSP : %(smsp)s
293 > ICCID : %(iccid)s
294 > MCC/MNC : %(mcc)d/%(mnc)d
295 > IMSI : %(imsi)s
296 > Ki : %(ki)s
297""" % params
298
299
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100300def write_parameters(opts, params):
301 # CSV
302 if opts.write_csv:
303 import csv
304 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki']
305 f = open(opts.write_csv, 'a')
306 cw = csv.writer(f)
307 cw.writerow([params[x] for x in row])
308 f.close()
309
310 # SQLite3 OpenBSC HLR
311 if opts.write_hlr:
312 import sqlite3
313 conn = sqlite3.connect(opts.write_hlr)
314
315 c = conn.execute(
316 'INSERT INTO Subscriber ' +
317 '(imsi, name, extension, authorized, created, updated) ' +
318 'VALUES ' +
319 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
320 [
321 params['imsi'],
322 params['name'],
323 '9' + params['iccid'][-5:]
324 ],
325 )
326 sub_id = c.lastrowid
327 c.close()
328
329 c = conn.execute(
330 'INSERT INTO AuthKeys ' +
331 '(subscriber_id, algorithm_id, a3a8_ki)' +
332 'VALUES ' +
333 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100334 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100335 )
336
337 conn.commit()
338 conn.close()
339
340
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100341BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
342BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100343
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100344def init_batch(opts):
345 # Need to do something ?
346 if not opts.batch_mode:
347 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100348
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100349 for k in BATCH_INCOMPATIBLE:
350 if getattr(opts, k):
351 print "Incompatible option with batch_state: %s" % (k,)
352 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100353
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100354 # Don't load state if there is none ...
355 if not opts.batch_state:
356 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100357
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100358 if not os.path.isfile(opts.batch_state):
359 print "No state file yet"
360 return
361
362 # Get stored data
363 fh = open(opts.batch_state)
364 d = json.loads(fh.read())
365 fh.close()
366
367 for k,v in d.iteritems():
368 setattr(opts, k, v)
369
370
371def save_batch(opts):
372 # Need to do something ?
373 if not opts.batch_mode or not opts.batch_state:
374 return
375
376 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
377 fh = open(opts.batch_state, 'w')
378 fh.write(d)
379 fh.close()
380
381
382def card_detect(opts, scc):
Sylvain Munautbdca2522010-12-09 13:31:58 +0100383
Sylvain Munaut76504e02010-12-07 00:24:32 +0100384 # Detect type if needed
385 card = None
386 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
387
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100388 if opts.type in ("auto", "auto_once"):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100389 for kls in _cards_classes:
390 card = kls.autodetect(scc)
391 if card:
392 print "Autodetected card type %s" % card.name
393 card.reset()
394 break
395
396 if card is None:
397 print "Autodetection failed"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100398 return
399
400 if opts.type == "auto_once":
401 opts.type = card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100402
403 elif opts.type in ctypes:
404 card = ctypes[opts.type](scc)
405
406 else:
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100407 raise ValueError("Unknown card type %s" % opts.type)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100408
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100409 return card
Sylvain Munaut76504e02010-12-07 00:24:32 +0100410
Sylvain Munaut76504e02010-12-07 00:24:32 +0100411
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100412if __name__ == '__main__':
413
414 # Parse options
415 opts = parse_options()
416
417 # Connect to the card
418 if opts.pcsc_dev is None:
419 from pySim.transport.serial import SerialSimLink
420 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
421 else:
422 from pySim.transport.pcsc import PcscSimLink
423 sl = PcscSimLink(opts.pcsc_dev)
424
425 # Create command layer
426 scc = SimCardCommands(transport=sl)
427
428 # Batch mode init
429 init_batch(opts)
430
431 # Iterate
432 done = False
433 first = True
434 card = None
435
436 while not done:
437 # Connect transport
438 print "Insert card now (or CTRL-C to cancel)"
439 sl.wait_for_card(newcardonly=not first)
440
441 # Not the first anymore !
442 first = False
443
444 # Get card
445 card = card_detect(opts, scc)
446 if card is None:
447 if opts.batch_mode:
448 first = False
449 continue
450 else:
451 sys.exit(-1)
452
453 # Erase if requested
454 if opts.erase:
455 print "Formatting ..."
456 card.erase()
457 card.reset()
458
459 # Generate parameters
460 cp = gen_parameters(opts)
461 print_parameters(cp)
462
463 # Program the card
464 print "Programming ..."
465 card.program(cp)
466
467 # Write parameters permanently
468 write_parameters(opts, cp)
469
470 # Batch mode state update and save
Sylvain Munaut8d243e82010-12-23 20:27:48 +0100471 if opts.num is not None:
472 opts.num += 1
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100473 save_batch(opts)
474
475 # Done for this card and maybe for everything ?
476 print "Done !\n"
477
478 if not opts.batch_mode:
479 done = True
Sylvain Munaut76504e02010-12-07 00:24:32 +0100480