blob: 12021aaff908d2c948369cc8ef95220073ccc539 [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
36except Importerror:
37 # 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
159def gen_parameters(opts):
160 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki from the
161 options given by the user"""
162
163 # MCC/MNC
164 mcc = opts.mcc
165 mnc = opts.mnc
166
167 if not ((0 < mcc < 999) and (0 < mnc < 999)):
168 raise ValueError('mcc & mnc must be between 0 and 999')
169
170 # Digitize country code (2 or 3 digits)
171 cc_digits = _cc_digits(opts.country)
172
173 # Digitize MCC/MNC (5 or 6 digits)
174 plmn_digits = _mcc_mnc_digits(mcc, mnc)
175
176 # ICCID (20 digits)
177 if opts.iccid is not None:
178 iccid = opts.iccid
179 if not _isnum(iccid, 20):
180 raise ValueError('ICCID must be 20 digits !');
181
182 else:
183 if opts.num is None:
184 raise ValueError('Neither ICCID nor card number specified !')
185
186 iccid = (
187 '89' + # Common prefix (telecom)
188 cc_digits + # Country Code on 2/3 digits
189 plmn_digits # MCC/MNC on 5/6 digits
190 )
191
192 ml = 20 - len(iccid)
193
194 if opts.secret is None:
195 # The raw number
196 iccid += ('%%0%dd' % ml) % opts.num
197 else:
198 # Randomized digits
199 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
200
201 # IMSI (15 digits usually)
202 if opts.imsi is not None:
203 imsi = opts.imsi
204 if not _isnum(imsi):
205 raise ValueError('IMSI must be digits only !')
206
207 else:
208 if opts.num is None:
209 raise ValueError('Neither IMSI nor card number specified !')
210
211 ml = 15 - len(plmn_digits)
212
213 if opts.secret is None:
214 # The raw number
215 msin = ('%%0%dd' % ml) % opts.num
216 else:
217 # Randomized digits
218 msin = _digits(opts.secret, 'imsi', ml, opts.num)
219
220 imsi = (
221 plmn_digits + # MCC/MNC on 5/6 digits
222 msin # MSIN
223 )
224
225 # SMSP
226 if opts.smsp is not None:
227 smsp = opts.smsp
228 if not _isnum(smsp):
229 raise ValueError('SMSP must be digits only !')
230
231 else:
232 smsp = '00%d' % opts.country + '5555' # Hack ...
233
234 # Ki (random)
235 if opts.ki is not None:
236 ki = opts.ki
237 if not re.match('^[0-9a-fA-F]{32}$', ki):
238 raise ValueError('Ki needs to be 128 bits, in hex format')
239
240 else:
241 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
242
243 # Return that
244 return {
245 'name' : opts.name,
246 'iccid' : iccid,
247 'mcc' : mcc,
248 'mnc' : mnc,
249 'imsi' : imsi,
250 'smsp' : smsp,
251 'ki' : ki,
252 }
253
254
255def print_parameters(params):
256
257 print """Generated card parameters :
258 > Name : %(name)s
259 > SMSP : %(smsp)s
260 > ICCID : %(iccid)s
261 > MCC/MNC : %(mcc)d/%(mnc)d
262 > IMSI : %(imsi)s
263 > Ki : %(ki)s
264""" % params
265
266
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100267def write_parameters(opts, params):
268 # CSV
269 if opts.write_csv:
270 import csv
271 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki']
272 f = open(opts.write_csv, 'a')
273 cw = csv.writer(f)
274 cw.writerow([params[x] for x in row])
275 f.close()
276
277 # SQLite3 OpenBSC HLR
278 if opts.write_hlr:
279 import sqlite3
280 conn = sqlite3.connect(opts.write_hlr)
281
282 c = conn.execute(
283 'INSERT INTO Subscriber ' +
284 '(imsi, name, extension, authorized, created, updated) ' +
285 'VALUES ' +
286 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
287 [
288 params['imsi'],
289 params['name'],
290 '9' + params['iccid'][-5:]
291 ],
292 )
293 sub_id = c.lastrowid
294 c.close()
295
296 c = conn.execute(
297 'INSERT INTO AuthKeys ' +
298 '(subscriber_id, algorithm_id, a3a8_ki)' +
299 'VALUES ' +
300 '(?,?,?)',
301 [ sub_id, 2, sqlite3.Binary(h2b(params['ki'])) ],
302 )
303
304 conn.commit()
305 conn.close()
306
307
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100308BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
309BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100310
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100311def init_batch(opts):
312 # Need to do something ?
313 if not opts.batch_mode:
314 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100315
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100316 for k in BATCH_INCOMPATIBLE:
317 if getattr(opts, k):
318 print "Incompatible option with batch_state: %s" % (k,)
319 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100320
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100321 # Don't load state if there is none ...
322 if not opts.batch_state:
323 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100324
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100325 if not os.path.isfile(opts.batch_state):
326 print "No state file yet"
327 return
328
329 # Get stored data
330 fh = open(opts.batch_state)
331 d = json.loads(fh.read())
332 fh.close()
333
334 for k,v in d.iteritems():
335 setattr(opts, k, v)
336
337
338def save_batch(opts):
339 # Need to do something ?
340 if not opts.batch_mode or not opts.batch_state:
341 return
342
343 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
344 fh = open(opts.batch_state, 'w')
345 fh.write(d)
346 fh.close()
347
348
349def card_detect(opts, scc):
Sylvain Munautbdca2522010-12-09 13:31:58 +0100350
Sylvain Munaut76504e02010-12-07 00:24:32 +0100351 # Detect type if needed
352 card = None
353 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
354
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100355 if opts.type in ("auto", "auto_once"):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100356 for kls in _cards_classes:
357 card = kls.autodetect(scc)
358 if card:
359 print "Autodetected card type %s" % card.name
360 card.reset()
361 break
362
363 if card is None:
364 print "Autodetection failed"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100365 return
366
367 if opts.type == "auto_once":
368 opts.type = card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100369
370 elif opts.type in ctypes:
371 card = ctypes[opts.type](scc)
372
373 else:
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100374 raise ValueError("Unknown card type %s" % opts.type)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100375
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100376 return card
Sylvain Munaut76504e02010-12-07 00:24:32 +0100377
Sylvain Munaut76504e02010-12-07 00:24:32 +0100378
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100379if __name__ == '__main__':
380
381 # Parse options
382 opts = parse_options()
383
384 # Connect to the card
385 if opts.pcsc_dev is None:
386 from pySim.transport.serial import SerialSimLink
387 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
388 else:
389 from pySim.transport.pcsc import PcscSimLink
390 sl = PcscSimLink(opts.pcsc_dev)
391
392 # Create command layer
393 scc = SimCardCommands(transport=sl)
394
395 # Batch mode init
396 init_batch(opts)
397
398 # Iterate
399 done = False
400 first = True
401 card = None
402
403 while not done:
404 # Connect transport
405 print "Insert card now (or CTRL-C to cancel)"
406 sl.wait_for_card(newcardonly=not first)
407
408 # Not the first anymore !
409 first = False
410
411 # Get card
412 card = card_detect(opts, scc)
413 if card is None:
414 if opts.batch_mode:
415 first = False
416 continue
417 else:
418 sys.exit(-1)
419
420 # Erase if requested
421 if opts.erase:
422 print "Formatting ..."
423 card.erase()
424 card.reset()
425
426 # Generate parameters
427 cp = gen_parameters(opts)
428 print_parameters(cp)
429
430 # Program the card
431 print "Programming ..."
432 card.program(cp)
433
434 # Write parameters permanently
435 write_parameters(opts, cp)
436
437 # Batch mode state update and save
438 opts.num += 1
439 save_batch(opts)
440
441 # Done for this card and maybe for everything ?
442 print "Done !\n"
443
444 if not opts.batch_mode:
445 done = True
Sylvain Munaut76504e02010-12-07 00:24:32 +0100446