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