blob: 46b1842dcf7c6c15984fb146ce2a4310511ee7ca [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 )
Harald Welte93b38cd2012-03-22 14:31:36 +0100102 parser.add_option("-o", "--opc", dest="opc",
103 help="OPC (default is to randomize)",
104 )
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100105 parser.add_option("--op", dest="op",
106 help="Set OP to derive OPC from OP and KI",
107 )
Harald Welte93b38cd2012-03-22 14:31:36 +0100108
Sylvain Munaut76504e02010-12-07 00:24:32 +0100109
110 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
111 help="Secret used for ICCID/IMSI autogen",
112 )
113 parser.add_option("-j", "--num", dest="num", type=int,
114 help="Card # used for ICCID/IMSI autogen",
115 )
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100116 parser.add_option("--batch", dest="batch_mode",
117 help="Enable batch mode [default: %default]",
118 default=False, action='store_true',
119 )
120 parser.add_option("--batch-state", dest="batch_state", metavar="FILE",
121 help="Optional batch state file",
122 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100123
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100124 parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
125 help="Append generated parameters in CSV file",
126 )
127 parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
128 help="Append generated parameters to OpenBSC HLR sqlite3",
129 )
130
Sylvain Munaut76504e02010-12-07 00:24:32 +0100131 (options, args) = parser.parse_args()
132
133 if options.type == 'list':
134 for kls in _cards_classes:
135 print kls.name
136 sys.exit(0)
137
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100138 if (options.batch_mode) and (options.num is None):
139 options.num = 0
140
Sylvain Munaut98d2b852010-12-23 20:27:25 +0100141 if (options.batch_mode):
142 if (options.imsi is not None) or (options.iccid is not None):
143 parser.error("Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more informations")
144
Sylvain Munaut76504e02010-12-07 00:24:32 +0100145 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
146 parser.error("If either IMSI or ICCID isn't specified, num is required")
147
148 if args:
149 parser.error("Extraneous arguments")
150
151 return options
152
153
154def _digits(secret, usage, len, num):
155 s = hashlib.sha1(secret + usage + '%d' % num)
156 d = ''.join(['%02d'%ord(x) for x in s.digest()])
157 return d[0:len]
158
159def _mcc_mnc_digits(mcc, mnc):
160 return ('%03d%03d' if mnc > 100 else '%03d%02d') % (mcc, mnc)
161
162def _cc_digits(cc):
163 return ('%03d' if cc > 100 else '%02d') % cc
164
165def _isnum(s, l=-1):
166 return s.isdigit() and ((l== -1) or (len(s) == l))
167
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100168def _ishex(s, l=-1):
169 hc = '0123456789abcdef'
170 return all([x in hc for x in s.lower()]) and ((l== -1) or (len(s) == l))
171
Sylvain Munaut76504e02010-12-07 00:24:32 +0100172
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100173def _dbi_binary_quote(s):
174 # Count usage of each char
175 cnt = {}
176 for c in s:
177 cnt[c] = cnt.get(c, 0) + 1
178
179 # Find best offset
180 e = 0
181 m = len(s)
182 for i in range(1, 256):
183 if i == 39:
184 continue
185 sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
186 if sum_ < m:
187 m = sum_
188 e = i
189 if m == 0: # No overhead ? use this !
190 break;
Sylvain Munaut1a914432011-12-08 20:08:26 +0100191
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100192 # Generate output
193 out = []
194 out.append( chr(e) ) # Offset
195 for c in s:
196 x = (256 + ord(c) - e) % 256
197 if x in (0, 1, 39):
198 out.append('\x01')
199 out.append(chr(x+1))
200 else:
201 out.append(chr(x))
202
203 return ''.join(out)
204
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100205def calculate_luhn(cc):
206 num = map(int, str(cc))
207 check_digit = 10 - sum(num[-2::-2] + [sum(divmod(d * 2, 10)) for d in num[::-2]]) % 10
208 return 0 if check_digit == 10 else check_digit
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100209
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100210def derive_milenage_opc(ki_hex, op_hex):
211 """
212 Run the milenage algorithm.
213 """
214 from Crypto.Cipher import AES
215 from Crypto.Util.strxor import strxor
216 from pySim.utils import b2h
217
218 # We pass in hex string and now need to work on bytes
219 aes = AES.new(h2b(ki_hex))
220 opc_bytes = aes.encrypt(h2b(op_hex))
221 return b2h(strxor(opc_bytes, h2b(op_hex)))
222
Sylvain Munaut76504e02010-12-07 00:24:32 +0100223def gen_parameters(opts):
224 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki from the
225 options given by the user"""
226
227 # MCC/MNC
228 mcc = opts.mcc
229 mnc = opts.mnc
230
231 if not ((0 < mcc < 999) and (0 < mnc < 999)):
232 raise ValueError('mcc & mnc must be between 0 and 999')
233
234 # Digitize country code (2 or 3 digits)
235 cc_digits = _cc_digits(opts.country)
236
237 # Digitize MCC/MNC (5 or 6 digits)
238 plmn_digits = _mcc_mnc_digits(mcc, mnc)
239
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100240 # ICCID (19 digits, E.118), though some phase1 vendors use 20 :(
Sylvain Munaut76504e02010-12-07 00:24:32 +0100241 if opts.iccid is not None:
242 iccid = opts.iccid
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100243 if not _isnum(iccid, 19):
244 raise ValueError('ICCID must be 19 digits !');
Sylvain Munaut76504e02010-12-07 00:24:32 +0100245
246 else:
247 if opts.num is None:
248 raise ValueError('Neither ICCID nor card number specified !')
249
250 iccid = (
251 '89' + # Common prefix (telecom)
252 cc_digits + # Country Code on 2/3 digits
253 plmn_digits # MCC/MNC on 5/6 digits
254 )
255
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100256 ml = 18 - len(iccid)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100257
258 if opts.secret is None:
259 # The raw number
260 iccid += ('%%0%dd' % ml) % opts.num
261 else:
262 # Randomized digits
263 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
264
Harald Welte2c0ff3a2011-12-07 12:34:13 +0100265 # Add checksum digit
266 iccid += ('%1d' % calculate_luhn(iccid))
267
Sylvain Munaut76504e02010-12-07 00:24:32 +0100268 # IMSI (15 digits usually)
269 if opts.imsi is not None:
270 imsi = opts.imsi
271 if not _isnum(imsi):
272 raise ValueError('IMSI must be digits only !')
273
274 else:
275 if opts.num is None:
276 raise ValueError('Neither IMSI nor card number specified !')
277
278 ml = 15 - len(plmn_digits)
279
280 if opts.secret is None:
281 # The raw number
282 msin = ('%%0%dd' % ml) % opts.num
283 else:
284 # Randomized digits
285 msin = _digits(opts.secret, 'imsi', ml, opts.num)
286
287 imsi = (
288 plmn_digits + # MCC/MNC on 5/6 digits
289 msin # MSIN
290 )
291
292 # SMSP
293 if opts.smsp is not None:
294 smsp = opts.smsp
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100295 if not _ishex(smsp):
296 raise ValueError('SMSP must be hex digits only !')
297 if len(smsp) < 28*2:
298 raise ValueError('SMSP must be at least 28 bytes')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100299
300 else:
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100301 if opts.smsc is not None:
302 smsc = opts.smsc
303 if not _isnum(smsc):
304 raise ValueError('SMSC must be digits only !')
305 else:
306 smsc = '00%d' % opts.country + '5555' # Hack ...
307
Sylvain Munaut9977c862011-12-10 09:57:16 +0100308 smsc = '%02d' % ((len(smsc) + 3)//2,) + "81" + swap_nibbles(rpad(smsc, 20))
Sylvain Munaut607ce2a2011-12-08 20:16:43 +0100309
310 smsp = (
311 'e1' + # Parameters indicator
312 'ff' * 12 + # TP-Destination address
313 smsc + # TP-Service Centre Address
314 '00' + # TP-Protocol identifier
315 '00' + # TP-Data coding scheme
316 '00' # TP-Validity period
317 )
Sylvain Munaut76504e02010-12-07 00:24:32 +0100318
319 # Ki (random)
320 if opts.ki is not None:
321 ki = opts.ki
322 if not re.match('^[0-9a-fA-F]{32}$', ki):
323 raise ValueError('Ki needs to be 128 bits, in hex format')
Sylvain Munaut76504e02010-12-07 00:24:32 +0100324 else:
325 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
326
Harald Welte93b38cd2012-03-22 14:31:36 +0100327 # Ki (random)
328 if opts.opc is not None:
329 opc = opts.opc
330 if not re.match('^[0-9a-fA-F]{32}$', opc):
331 raise ValueError('OPC needs to be 128 bits, in hex format')
332
Holger Hans Peter Freythercca41792012-03-22 15:23:14 +0100333 elif opts.op is not None:
334 opc = derive_milenage_opc(ki, opts.op)
Harald Welte93b38cd2012-03-22 14:31:36 +0100335 else:
336 opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
337
338
Sylvain Munaut76504e02010-12-07 00:24:32 +0100339 # Return that
340 return {
341 'name' : opts.name,
342 'iccid' : iccid,
343 'mcc' : mcc,
344 'mnc' : mnc,
345 'imsi' : imsi,
346 'smsp' : smsp,
347 'ki' : ki,
Harald Welte93b38cd2012-03-22 14:31:36 +0100348 'opc' : opc,
Sylvain Munaut76504e02010-12-07 00:24:32 +0100349 }
350
351
352def print_parameters(params):
353
354 print """Generated card parameters :
355 > Name : %(name)s
356 > SMSP : %(smsp)s
357 > ICCID : %(iccid)s
358 > MCC/MNC : %(mcc)d/%(mnc)d
359 > IMSI : %(imsi)s
360 > Ki : %(ki)s
Harald Welte93b38cd2012-03-22 14:31:36 +0100361 > OPC : %(opc)s
Sylvain Munaut76504e02010-12-07 00:24:32 +0100362""" % params
363
364
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100365def write_parameters(opts, params):
366 # CSV
367 if opts.write_csv:
368 import csv
Harald Welte93b38cd2012-03-22 14:31:36 +0100369 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100370 f = open(opts.write_csv, 'a')
371 cw = csv.writer(f)
372 cw.writerow([params[x] for x in row])
373 f.close()
374
375 # SQLite3 OpenBSC HLR
376 if opts.write_hlr:
377 import sqlite3
378 conn = sqlite3.connect(opts.write_hlr)
379
380 c = conn.execute(
381 'INSERT INTO Subscriber ' +
382 '(imsi, name, extension, authorized, created, updated) ' +
383 'VALUES ' +
384 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
385 [
386 params['imsi'],
387 params['name'],
388 '9' + params['iccid'][-5:]
389 ],
390 )
391 sub_id = c.lastrowid
392 c.close()
393
394 c = conn.execute(
395 'INSERT INTO AuthKeys ' +
396 '(subscriber_id, algorithm_id, a3a8_ki)' +
397 'VALUES ' +
398 '(?,?,?)',
Sylvain Munaut9f120e02010-12-23 20:28:24 +0100399 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100400 )
401
402 conn.commit()
403 conn.close()
404
405
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100406BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ]
407BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki']
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100408
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100409def init_batch(opts):
410 # Need to do something ?
411 if not opts.batch_mode:
412 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100413
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100414 for k in BATCH_INCOMPATIBLE:
415 if getattr(opts, k):
416 print "Incompatible option with batch_state: %s" % (k,)
417 sys.exit(-1)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100418
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100419 # Don't load state if there is none ...
420 if not opts.batch_state:
421 return
Sylvain Munaut76504e02010-12-07 00:24:32 +0100422
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100423 if not os.path.isfile(opts.batch_state):
424 print "No state file yet"
425 return
426
427 # Get stored data
428 fh = open(opts.batch_state)
429 d = json.loads(fh.read())
430 fh.close()
431
432 for k,v in d.iteritems():
433 setattr(opts, k, v)
434
435
436def save_batch(opts):
437 # Need to do something ?
438 if not opts.batch_mode or not opts.batch_state:
439 return
440
441 d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE]))
442 fh = open(opts.batch_state, 'w')
443 fh.write(d)
444 fh.close()
445
446
447def card_detect(opts, scc):
Sylvain Munautbdca2522010-12-09 13:31:58 +0100448
Sylvain Munaut76504e02010-12-07 00:24:32 +0100449 # Detect type if needed
450 card = None
451 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
452
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100453 if opts.type in ("auto", "auto_once"):
Sylvain Munaut76504e02010-12-07 00:24:32 +0100454 for kls in _cards_classes:
455 card = kls.autodetect(scc)
456 if card:
457 print "Autodetected card type %s" % card.name
458 card.reset()
459 break
460
461 if card is None:
462 print "Autodetection failed"
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100463 return
464
465 if opts.type == "auto_once":
466 opts.type = card.name
Sylvain Munaut76504e02010-12-07 00:24:32 +0100467
468 elif opts.type in ctypes:
469 card = ctypes[opts.type](scc)
470
471 else:
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100472 raise ValueError("Unknown card type %s" % opts.type)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100473
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100474 return card
Sylvain Munaut76504e02010-12-07 00:24:32 +0100475
Sylvain Munaut76504e02010-12-07 00:24:32 +0100476
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100477if __name__ == '__main__':
478
479 # Parse options
480 opts = parse_options()
481
482 # Connect to the card
483 if opts.pcsc_dev is None:
484 from pySim.transport.serial import SerialSimLink
485 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
486 else:
487 from pySim.transport.pcsc import PcscSimLink
488 sl = PcscSimLink(opts.pcsc_dev)
489
490 # Create command layer
491 scc = SimCardCommands(transport=sl)
492
493 # Batch mode init
494 init_batch(opts)
495
496 # Iterate
497 done = False
498 first = True
499 card = None
Sylvain Munaut1a914432011-12-08 20:08:26 +0100500
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100501 while not done:
502 # Connect transport
503 print "Insert card now (or CTRL-C to cancel)"
504 sl.wait_for_card(newcardonly=not first)
505
506 # Not the first anymore !
507 first = False
508
509 # Get card
510 card = card_detect(opts, scc)
511 if card is None:
512 if opts.batch_mode:
513 first = False
514 continue
515 else:
516 sys.exit(-1)
517
518 # Erase if requested
519 if opts.erase:
520 print "Formatting ..."
521 card.erase()
522 card.reset()
523
524 # Generate parameters
525 cp = gen_parameters(opts)
526 print_parameters(cp)
527
528 # Program the card
529 print "Programming ..."
530 card.program(cp)
531
532 # Write parameters permanently
533 write_parameters(opts, cp)
534
535 # Batch mode state update and save
Sylvain Munaut8d243e82010-12-23 20:27:48 +0100536 if opts.num is not None:
537 opts.num += 1
Sylvain Munaut8f7d3ba2010-12-09 13:32:48 +0100538 save_batch(opts)
539
540 # Done for this card and maybe for everything ?
541 print "Done !\n"
542
543 if not opts.batch_mode:
544 done = True
Sylvain Munaut76504e02010-12-07 00:24:32 +0100545