blob: df66b80d517779d71e6ad6832e180587a346151f [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
29import random
30import re
31import sys
32
33from pySim.commands import SimCardCommands
34from pySim.cards import _cards_classes
Sylvain Munaut143e99d2010-12-08 22:35:04 +010035from pySim.utils import h2b
Sylvain Munaut76504e02010-12-07 00:24:32 +010036
37
38def parse_options():
39
40 parser = OptionParser(usage="usage: %prog [options]")
41
42 parser.add_option("-d", "--device", dest="device", metavar="DEV",
43 help="Serial Device for SIM access [default: %default]",
44 default="/dev/ttyUSB0",
45 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010046 parser.add_option("-b", "--baud", dest="baudrate", type="int", metavar="BAUD",
47 help="Baudrate used for SIM access [default: %default]",
48 default=9600,
49 )
Sylvain Munaut9c8729a2010-12-08 23:20:27 +010050 parser.add_option("-p", "--pcsc-device", dest="pcsc_dev", type='int', metavar="PCSC",
Sylvain Munaute9fdecb2010-12-08 22:33:19 +010051 help="Which PC/SC reader number for SIM access",
52 default=None,
53 )
Sylvain Munaut76504e02010-12-07 00:24:32 +010054 parser.add_option("-t", "--type", dest="type",
55 help="Card type (user -t list to view) [default: %default]",
56 default="auto",
57 )
58 parser.add_option("-e", "--erase", dest="erase", action='store_true',
59 help="Erase beforehand [default: %default]",
60 default=False,
61 )
62
63 parser.add_option("-n", "--name", dest="name",
64 help="Operator name [default: %default]",
65 default="Magic",
66 )
67 parser.add_option("-c", "--country", dest="country", type="int", metavar="CC",
68 help="Country code [default: %default]",
69 default=1,
70 )
71 parser.add_option("-x", "--mcc", dest="mcc", type="int",
72 help="Mobile Country Code [default: %default]",
73 default=901,
74 )
75 parser.add_option("-y", "--mnc", dest="mnc", type="int",
Sylvain Munaut17716032010-12-08 22:33:51 +010076 help="Mobile Network Code [default: %default]",
Sylvain Munaut76504e02010-12-07 00:24:32 +010077 default=55,
78 )
79 parser.add_option("-m", "--smsp", dest="smsp",
80 help="SMSP [default: '00 + country code + 5555']",
81 )
82
83 parser.add_option("-s", "--iccid", dest="iccid", metavar="ID",
84 help="Integrated Circuit Card ID",
85 )
86 parser.add_option("-i", "--imsi", dest="imsi",
87 help="International Mobile Subscriber Identity",
88 )
89 parser.add_option("-k", "--ki", dest="ki",
90 help="Ki (default is to randomize)",
91 )
92
93 parser.add_option("-z", "--secret", dest="secret", metavar="STR",
94 help="Secret used for ICCID/IMSI autogen",
95 )
96 parser.add_option("-j", "--num", dest="num", type=int,
97 help="Card # used for ICCID/IMSI autogen",
98 )
99
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100100 parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
101 help="Append generated parameters in CSV file",
102 )
103 parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
104 help="Append generated parameters to OpenBSC HLR sqlite3",
105 )
106
Sylvain Munaut76504e02010-12-07 00:24:32 +0100107 (options, args) = parser.parse_args()
108
109 if options.type == 'list':
110 for kls in _cards_classes:
111 print kls.name
112 sys.exit(0)
113
114 if ((options.imsi is None) or (options.iccid is None)) and (options.num is None):
115 parser.error("If either IMSI or ICCID isn't specified, num is required")
116
117 if args:
118 parser.error("Extraneous arguments")
119
120 return options
121
122
123def _digits(secret, usage, len, num):
124 s = hashlib.sha1(secret + usage + '%d' % num)
125 d = ''.join(['%02d'%ord(x) for x in s.digest()])
126 return d[0:len]
127
128def _mcc_mnc_digits(mcc, mnc):
129 return ('%03d%03d' if mnc > 100 else '%03d%02d') % (mcc, mnc)
130
131def _cc_digits(cc):
132 return ('%03d' if cc > 100 else '%02d') % cc
133
134def _isnum(s, l=-1):
135 return s.isdigit() and ((l== -1) or (len(s) == l))
136
137
138def gen_parameters(opts):
139 """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki from the
140 options given by the user"""
141
142 # MCC/MNC
143 mcc = opts.mcc
144 mnc = opts.mnc
145
146 if not ((0 < mcc < 999) and (0 < mnc < 999)):
147 raise ValueError('mcc & mnc must be between 0 and 999')
148
149 # Digitize country code (2 or 3 digits)
150 cc_digits = _cc_digits(opts.country)
151
152 # Digitize MCC/MNC (5 or 6 digits)
153 plmn_digits = _mcc_mnc_digits(mcc, mnc)
154
155 # ICCID (20 digits)
156 if opts.iccid is not None:
157 iccid = opts.iccid
158 if not _isnum(iccid, 20):
159 raise ValueError('ICCID must be 20 digits !');
160
161 else:
162 if opts.num is None:
163 raise ValueError('Neither ICCID nor card number specified !')
164
165 iccid = (
166 '89' + # Common prefix (telecom)
167 cc_digits + # Country Code on 2/3 digits
168 plmn_digits # MCC/MNC on 5/6 digits
169 )
170
171 ml = 20 - len(iccid)
172
173 if opts.secret is None:
174 # The raw number
175 iccid += ('%%0%dd' % ml) % opts.num
176 else:
177 # Randomized digits
178 iccid += _digits(opts.secret, 'ccid', ml, opts.num)
179
180 # IMSI (15 digits usually)
181 if opts.imsi is not None:
182 imsi = opts.imsi
183 if not _isnum(imsi):
184 raise ValueError('IMSI must be digits only !')
185
186 else:
187 if opts.num is None:
188 raise ValueError('Neither IMSI nor card number specified !')
189
190 ml = 15 - len(plmn_digits)
191
192 if opts.secret is None:
193 # The raw number
194 msin = ('%%0%dd' % ml) % opts.num
195 else:
196 # Randomized digits
197 msin = _digits(opts.secret, 'imsi', ml, opts.num)
198
199 imsi = (
200 plmn_digits + # MCC/MNC on 5/6 digits
201 msin # MSIN
202 )
203
204 # SMSP
205 if opts.smsp is not None:
206 smsp = opts.smsp
207 if not _isnum(smsp):
208 raise ValueError('SMSP must be digits only !')
209
210 else:
211 smsp = '00%d' % opts.country + '5555' # Hack ...
212
213 # Ki (random)
214 if opts.ki is not None:
215 ki = opts.ki
216 if not re.match('^[0-9a-fA-F]{32}$', ki):
217 raise ValueError('Ki needs to be 128 bits, in hex format')
218
219 else:
220 ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
221
222 # Return that
223 return {
224 'name' : opts.name,
225 'iccid' : iccid,
226 'mcc' : mcc,
227 'mnc' : mnc,
228 'imsi' : imsi,
229 'smsp' : smsp,
230 'ki' : ki,
231 }
232
233
234def print_parameters(params):
235
236 print """Generated card parameters :
237 > Name : %(name)s
238 > SMSP : %(smsp)s
239 > ICCID : %(iccid)s
240 > MCC/MNC : %(mcc)d/%(mnc)d
241 > IMSI : %(imsi)s
242 > Ki : %(ki)s
243""" % params
244
245
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100246def write_parameters(opts, params):
247 # CSV
248 if opts.write_csv:
249 import csv
250 row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki']
251 f = open(opts.write_csv, 'a')
252 cw = csv.writer(f)
253 cw.writerow([params[x] for x in row])
254 f.close()
255
256 # SQLite3 OpenBSC HLR
257 if opts.write_hlr:
258 import sqlite3
259 conn = sqlite3.connect(opts.write_hlr)
260
261 c = conn.execute(
262 'INSERT INTO Subscriber ' +
263 '(imsi, name, extension, authorized, created, updated) ' +
264 'VALUES ' +
265 '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
266 [
267 params['imsi'],
268 params['name'],
269 '9' + params['iccid'][-5:]
270 ],
271 )
272 sub_id = c.lastrowid
273 c.close()
274
275 c = conn.execute(
276 'INSERT INTO AuthKeys ' +
277 '(subscriber_id, algorithm_id, a3a8_ki)' +
278 'VALUES ' +
279 '(?,?,?)',
280 [ sub_id, 2, sqlite3.Binary(h2b(params['ki'])) ],
281 )
282
283 conn.commit()
284 conn.close()
285
286
287
Sylvain Munaut76504e02010-12-07 00:24:32 +0100288if __name__ == '__main__':
289
290 # Get/Gen the parameters
291 opts = parse_options()
292 cp = gen_parameters(opts)
293 print_parameters(cp)
Sylvain Munaut143e99d2010-12-08 22:35:04 +0100294 write_parameters(opts, cp)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100295
296 # Connect to the card
297 if opts.pcsc_dev is None:
298 from pySim.transport.serial import SerialSimLink
299 sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
300 else:
301 from pySim.transport.pcsc import PcscSimLink
Sylvain Munaut9c8729a2010-12-08 23:20:27 +0100302 sl = PcscSimLink(opts.pcsc_dev)
Sylvain Munaut76504e02010-12-07 00:24:32 +0100303 scc = SimCardCommands(transport=sl)
304
Sylvain Munautbdca2522010-12-09 13:31:58 +0100305 print "Insert Card now"
306 sl.wait_for_card()
307
Sylvain Munaut76504e02010-12-07 00:24:32 +0100308 # Detect type if needed
309 card = None
310 ctypes = dict([(kls.name, kls) for kls in _cards_classes])
311
312 if opts.type == "auto":
313 for kls in _cards_classes:
314 card = kls.autodetect(scc)
315 if card:
316 print "Autodetected card type %s" % card.name
317 card.reset()
318 break
319
320 if card is None:
321 print "Autodetection failed"
322 sys.exit(-1)
323
324 elif opts.type in ctypes:
325 card = ctypes[opts.type](scc)
326
327 else:
328 print "Unknown card type %s" % opts.type
329 sys.exit(-1)
330
331 # Erase it if asked
332 if opts.erase:
333 print "Formatting ..."
334 card.erase()
335 card.reset()
336
337 # Program it
338 print "Programming ..."
339 card.program(cp)
340
341 print "Done !"
342