Pau Espin Pedrol | ac23ad5 | 2017-12-29 20:30:35 +0100 | [diff] [blame] | 1 | #!/usr/bin/env python2 |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 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 | |
| 27 | import hashlib |
| 28 | from optparse import OptionParser |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 29 | import os |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 30 | import random |
| 31 | import re |
| 32 | import sys |
| 33 | |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 34 | try: |
| 35 | import json |
Holger Hans Peter Freyther | 5dffefb | 2011-11-22 21:18:06 +0100 | [diff] [blame] | 36 | except ImportError: |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 37 | # Python < 2.5 |
| 38 | import simplejson as json |
| 39 | |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 40 | from pySim.commands import SimCardCommands |
| 41 | from pySim.cards import _cards_classes |
Alexander Chemeris | 19fffa1 | 2018-01-11 13:06:43 +0900 | [diff] [blame] | 42 | from pySim.utils import h2b, swap_nibbles, rpad, derive_milenage_opc, calculate_luhn |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 43 | |
| 44 | |
| 45 | def 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 Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 53 | 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 Munaut | 9c8729a | 2010-12-08 23:20:27 +0100 | [diff] [blame] | 57 | parser.add_option("-p", "--pcsc-device", dest="pcsc_dev", type='int', metavar="PCSC", |
Sylvain Munaut | e9fdecb | 2010-12-08 22:33:19 +0100 | [diff] [blame] | 58 | help="Which PC/SC reader number for SIM access", |
| 59 | default=None, |
| 60 | ) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 61 | parser.add_option("-t", "--type", dest="type", |
| 62 | help="Card type (user -t list to view) [default: %default]", |
| 63 | default="auto", |
| 64 | ) |
Jan Balke | c3ebd33 | 2015-01-26 12:22:55 +0100 | [diff] [blame] | 65 | parser.add_option("-a", "--pin-adm", dest="pin_adm", |
| 66 | help="ADM PIN used for provisioning (overwrites default)", |
| 67 | ) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 68 | parser.add_option("-e", "--erase", dest="erase", action='store_true', |
| 69 | help="Erase beforehand [default: %default]", |
| 70 | default=False, |
| 71 | ) |
| 72 | |
Harald Welte | 7f62cec | 2012-08-13 20:07:41 +0200 | [diff] [blame] | 73 | parser.add_option("-S", "--source", dest="source", |
| 74 | help="Data Source[default: %default]", |
| 75 | default="cmdline", |
| 76 | ) |
| 77 | |
| 78 | # if mode is "cmdline" |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 79 | parser.add_option("-n", "--name", dest="name", |
| 80 | help="Operator name [default: %default]", |
| 81 | default="Magic", |
| 82 | ) |
| 83 | parser.add_option("-c", "--country", dest="country", type="int", metavar="CC", |
| 84 | help="Country code [default: %default]", |
| 85 | default=1, |
| 86 | ) |
| 87 | parser.add_option("-x", "--mcc", dest="mcc", type="int", |
| 88 | help="Mobile Country Code [default: %default]", |
| 89 | default=901, |
| 90 | ) |
| 91 | parser.add_option("-y", "--mnc", dest="mnc", type="int", |
Sylvain Munaut | 1771603 | 2010-12-08 22:33:51 +0100 | [diff] [blame] | 92 | help="Mobile Network Code [default: %default]", |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 93 | default=55, |
| 94 | ) |
Sylvain Munaut | 607ce2a | 2011-12-08 20:16:43 +0100 | [diff] [blame] | 95 | parser.add_option("-m", "--smsc", dest="smsc", |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 96 | help="SMSP [default: '00 + country code + 5555']", |
| 97 | ) |
Sylvain Munaut | 607ce2a | 2011-12-08 20:16:43 +0100 | [diff] [blame] | 98 | parser.add_option("-M", "--smsp", dest="smsp", |
| 99 | help="Raw SMSP content in hex [default: auto from SMSC]", |
| 100 | ) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 101 | |
| 102 | parser.add_option("-s", "--iccid", dest="iccid", metavar="ID", |
| 103 | help="Integrated Circuit Card ID", |
| 104 | ) |
| 105 | parser.add_option("-i", "--imsi", dest="imsi", |
| 106 | help="International Mobile Subscriber Identity", |
| 107 | ) |
| 108 | parser.add_option("-k", "--ki", dest="ki", |
| 109 | help="Ki (default is to randomize)", |
| 110 | ) |
Harald Welte | 93b38cd | 2012-03-22 14:31:36 +0100 | [diff] [blame] | 111 | parser.add_option("-o", "--opc", dest="opc", |
| 112 | help="OPC (default is to randomize)", |
| 113 | ) |
Holger Hans Peter Freyther | cca4179 | 2012-03-22 15:23:14 +0100 | [diff] [blame] | 114 | parser.add_option("--op", dest="op", |
| 115 | help="Set OP to derive OPC from OP and KI", |
| 116 | ) |
Alexander Chemeris | 2188524 | 2013-07-02 16:56:55 +0400 | [diff] [blame] | 117 | parser.add_option("--acc", dest="acc", |
| 118 | help="Set ACC bits (Access Control Code). not all card types are supported", |
Holger Hans Peter Freyther | 4e82468 | 2012-08-15 15:56:05 +0200 | [diff] [blame] | 119 | ) |
| 120 | parser.add_option("--read-imsi", dest="read_imsi", action="store_true", |
| 121 | help="Read the IMSI from the CARD", default=False |
Alexander Chemeris | 2188524 | 2013-07-02 16:56:55 +0400 | [diff] [blame] | 122 | ) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 123 | parser.add_option("-z", "--secret", dest="secret", metavar="STR", |
| 124 | help="Secret used for ICCID/IMSI autogen", |
| 125 | ) |
| 126 | parser.add_option("-j", "--num", dest="num", type=int, |
| 127 | help="Card # used for ICCID/IMSI autogen", |
| 128 | ) |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 129 | parser.add_option("--batch", dest="batch_mode", |
| 130 | help="Enable batch mode [default: %default]", |
| 131 | default=False, action='store_true', |
| 132 | ) |
| 133 | parser.add_option("--batch-state", dest="batch_state", metavar="FILE", |
| 134 | help="Optional batch state file", |
| 135 | ) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 136 | |
Harald Welte | 7f62cec | 2012-08-13 20:07:41 +0200 | [diff] [blame] | 137 | # if mode is "csv" |
| 138 | parser.add_option("--read-csv", dest="read_csv", metavar="FILE", |
| 139 | help="Read parameters from CSV file rather than command line") |
| 140 | |
| 141 | |
Sylvain Munaut | 143e99d | 2010-12-08 22:35:04 +0100 | [diff] [blame] | 142 | parser.add_option("--write-csv", dest="write_csv", metavar="FILE", |
| 143 | help="Append generated parameters in CSV file", |
| 144 | ) |
| 145 | parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE", |
| 146 | help="Append generated parameters to OpenBSC HLR sqlite3", |
| 147 | ) |
Harald Welte | e9e5ecb | 2012-08-15 15:26:30 +0200 | [diff] [blame] | 148 | parser.add_option("--dry-run", dest="dry_run", |
| 149 | help="Perform a 'dry run', don't actually program the card", |
| 150 | default=False, action="store_true") |
Sylvain Munaut | 143e99d | 2010-12-08 22:35:04 +0100 | [diff] [blame] | 151 | |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 152 | (options, args) = parser.parse_args() |
| 153 | |
| 154 | if options.type == 'list': |
| 155 | for kls in _cards_classes: |
| 156 | print kls.name |
| 157 | sys.exit(0) |
| 158 | |
Harald Welte | 7f62cec | 2012-08-13 20:07:41 +0200 | [diff] [blame] | 159 | if options.source == 'csv': |
Holger Hans Peter Freyther | 4e82468 | 2012-08-15 15:56:05 +0200 | [diff] [blame] | 160 | if (options.imsi is None) and (options.batch_mode is False) and (options.read_imsi is False): |
| 161 | parser.error("CSV mode needs either an IMSI, --read-imsi or batch mode") |
Harald Welte | 7f62cec | 2012-08-13 20:07:41 +0200 | [diff] [blame] | 162 | if options.read_csv is None: |
| 163 | parser.error("CSV mode requires a CSV input file") |
| 164 | elif options.source == 'cmdline': |
| 165 | if ((options.imsi is None) or (options.iccid is None)) and (options.num is None): |
| 166 | parser.error("If either IMSI or ICCID isn't specified, num is required") |
| 167 | else: |
| 168 | parser.error("Only `cmdline' and `csv' sources supported") |
| 169 | |
| 170 | if (options.read_csv is not None) and (options.source != 'csv'): |
| 171 | parser.error("You cannot specify a CSV input file in source != csv") |
| 172 | |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 173 | if (options.batch_mode) and (options.num is None): |
| 174 | options.num = 0 |
| 175 | |
Sylvain Munaut | 98d2b85 | 2010-12-23 20:27:25 +0100 | [diff] [blame] | 176 | if (options.batch_mode): |
| 177 | if (options.imsi is not None) or (options.iccid is not None): |
| 178 | parser.error("Can't give ICCID/IMSI for batch mode, need to use automatic parameters ! see --num and --secret for more informations") |
| 179 | |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 180 | if args: |
| 181 | parser.error("Extraneous arguments") |
| 182 | |
| 183 | return options |
| 184 | |
| 185 | |
| 186 | def _digits(secret, usage, len, num): |
| 187 | s = hashlib.sha1(secret + usage + '%d' % num) |
| 188 | d = ''.join(['%02d'%ord(x) for x in s.digest()]) |
| 189 | return d[0:len] |
| 190 | |
| 191 | def _mcc_mnc_digits(mcc, mnc): |
| 192 | return ('%03d%03d' if mnc > 100 else '%03d%02d') % (mcc, mnc) |
| 193 | |
| 194 | def _cc_digits(cc): |
| 195 | return ('%03d' if cc > 100 else '%02d') % cc |
| 196 | |
| 197 | def _isnum(s, l=-1): |
| 198 | return s.isdigit() and ((l== -1) or (len(s) == l)) |
| 199 | |
Sylvain Munaut | 607ce2a | 2011-12-08 20:16:43 +0100 | [diff] [blame] | 200 | def _ishex(s, l=-1): |
| 201 | hc = '0123456789abcdef' |
| 202 | return all([x in hc for x in s.lower()]) and ((l== -1) or (len(s) == l)) |
| 203 | |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 204 | |
Sylvain Munaut | 9f120e0 | 2010-12-23 20:28:24 +0100 | [diff] [blame] | 205 | def _dbi_binary_quote(s): |
| 206 | # Count usage of each char |
| 207 | cnt = {} |
| 208 | for c in s: |
| 209 | cnt[c] = cnt.get(c, 0) + 1 |
| 210 | |
| 211 | # Find best offset |
| 212 | e = 0 |
| 213 | m = len(s) |
| 214 | for i in range(1, 256): |
| 215 | if i == 39: |
| 216 | continue |
| 217 | sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0) |
| 218 | if sum_ < m: |
| 219 | m = sum_ |
| 220 | e = i |
| 221 | if m == 0: # No overhead ? use this ! |
| 222 | break; |
Sylvain Munaut | 1a91443 | 2011-12-08 20:08:26 +0100 | [diff] [blame] | 223 | |
Sylvain Munaut | 9f120e0 | 2010-12-23 20:28:24 +0100 | [diff] [blame] | 224 | # Generate output |
| 225 | out = [] |
| 226 | out.append( chr(e) ) # Offset |
| 227 | for c in s: |
| 228 | x = (256 + ord(c) - e) % 256 |
| 229 | if x in (0, 1, 39): |
| 230 | out.append('\x01') |
| 231 | out.append(chr(x+1)) |
| 232 | else: |
| 233 | out.append(chr(x)) |
| 234 | |
| 235 | return ''.join(out) |
| 236 | |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 237 | def gen_parameters(opts): |
Jan Balke | c3ebd33 | 2015-01-26 12:22:55 +0100 | [diff] [blame] | 238 | """Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki, PIN-ADM from the |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 239 | options given by the user""" |
| 240 | |
| 241 | # MCC/MNC |
| 242 | mcc = opts.mcc |
| 243 | mnc = opts.mnc |
| 244 | |
| 245 | if not ((0 < mcc < 999) and (0 < mnc < 999)): |
| 246 | raise ValueError('mcc & mnc must be between 0 and 999') |
| 247 | |
| 248 | # Digitize country code (2 or 3 digits) |
| 249 | cc_digits = _cc_digits(opts.country) |
| 250 | |
| 251 | # Digitize MCC/MNC (5 or 6 digits) |
| 252 | plmn_digits = _mcc_mnc_digits(mcc, mnc) |
| 253 | |
Harald Welte | 2c0ff3a | 2011-12-07 12:34:13 +0100 | [diff] [blame] | 254 | # ICCID (19 digits, E.118), though some phase1 vendors use 20 :( |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 255 | if opts.iccid is not None: |
| 256 | iccid = opts.iccid |
Harald Welte | 2c0ff3a | 2011-12-07 12:34:13 +0100 | [diff] [blame] | 257 | if not _isnum(iccid, 19): |
| 258 | raise ValueError('ICCID must be 19 digits !'); |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 259 | |
| 260 | else: |
| 261 | if opts.num is None: |
| 262 | raise ValueError('Neither ICCID nor card number specified !') |
| 263 | |
| 264 | iccid = ( |
| 265 | '89' + # Common prefix (telecom) |
| 266 | cc_digits + # Country Code on 2/3 digits |
| 267 | plmn_digits # MCC/MNC on 5/6 digits |
| 268 | ) |
| 269 | |
Harald Welte | 2c0ff3a | 2011-12-07 12:34:13 +0100 | [diff] [blame] | 270 | ml = 18 - len(iccid) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 271 | |
| 272 | if opts.secret is None: |
| 273 | # The raw number |
| 274 | iccid += ('%%0%dd' % ml) % opts.num |
| 275 | else: |
| 276 | # Randomized digits |
| 277 | iccid += _digits(opts.secret, 'ccid', ml, opts.num) |
| 278 | |
Harald Welte | 2c0ff3a | 2011-12-07 12:34:13 +0100 | [diff] [blame] | 279 | # Add checksum digit |
| 280 | iccid += ('%1d' % calculate_luhn(iccid)) |
| 281 | |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 282 | # IMSI (15 digits usually) |
| 283 | if opts.imsi is not None: |
| 284 | imsi = opts.imsi |
| 285 | if not _isnum(imsi): |
| 286 | raise ValueError('IMSI must be digits only !') |
| 287 | |
| 288 | else: |
| 289 | if opts.num is None: |
| 290 | raise ValueError('Neither IMSI nor card number specified !') |
| 291 | |
| 292 | ml = 15 - len(plmn_digits) |
| 293 | |
| 294 | if opts.secret is None: |
| 295 | # The raw number |
| 296 | msin = ('%%0%dd' % ml) % opts.num |
| 297 | else: |
| 298 | # Randomized digits |
| 299 | msin = _digits(opts.secret, 'imsi', ml, opts.num) |
| 300 | |
| 301 | imsi = ( |
| 302 | plmn_digits + # MCC/MNC on 5/6 digits |
| 303 | msin # MSIN |
| 304 | ) |
| 305 | |
| 306 | # SMSP |
| 307 | if opts.smsp is not None: |
| 308 | smsp = opts.smsp |
Sylvain Munaut | 607ce2a | 2011-12-08 20:16:43 +0100 | [diff] [blame] | 309 | if not _ishex(smsp): |
| 310 | raise ValueError('SMSP must be hex digits only !') |
| 311 | if len(smsp) < 28*2: |
| 312 | raise ValueError('SMSP must be at least 28 bytes') |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 313 | |
| 314 | else: |
Sylvain Munaut | 607ce2a | 2011-12-08 20:16:43 +0100 | [diff] [blame] | 315 | if opts.smsc is not None: |
| 316 | smsc = opts.smsc |
| 317 | if not _isnum(smsc): |
| 318 | raise ValueError('SMSC must be digits only !') |
| 319 | else: |
| 320 | smsc = '00%d' % opts.country + '5555' # Hack ... |
| 321 | |
Sylvain Munaut | 9977c86 | 2011-12-10 09:57:16 +0100 | [diff] [blame] | 322 | smsc = '%02d' % ((len(smsc) + 3)//2,) + "81" + swap_nibbles(rpad(smsc, 20)) |
Sylvain Munaut | 607ce2a | 2011-12-08 20:16:43 +0100 | [diff] [blame] | 323 | |
| 324 | smsp = ( |
| 325 | 'e1' + # Parameters indicator |
| 326 | 'ff' * 12 + # TP-Destination address |
| 327 | smsc + # TP-Service Centre Address |
| 328 | '00' + # TP-Protocol identifier |
| 329 | '00' + # TP-Data coding scheme |
| 330 | '00' # TP-Validity period |
| 331 | ) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 332 | |
Alexander Chemeris | 2188524 | 2013-07-02 16:56:55 +0400 | [diff] [blame] | 333 | # ACC |
| 334 | if opts.acc is not None: |
| 335 | acc = opts.acc |
| 336 | if not _ishex(acc): |
| 337 | raise ValueError('ACC must be hex digits only !') |
| 338 | if len(acc) != 2*2: |
| 339 | raise ValueError('ACC must be exactly 2 bytes') |
| 340 | |
| 341 | else: |
| 342 | acc = None |
| 343 | |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 344 | # Ki (random) |
| 345 | if opts.ki is not None: |
| 346 | ki = opts.ki |
| 347 | if not re.match('^[0-9a-fA-F]{32}$', ki): |
| 348 | raise ValueError('Ki needs to be 128 bits, in hex format') |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 349 | else: |
| 350 | ki = ''.join(['%02x' % random.randrange(0,256) for i in range(16)]) |
| 351 | |
Alexander Chemeris | d17ca3d | 2017-07-18 16:40:58 +0300 | [diff] [blame] | 352 | # OPC (random) |
Harald Welte | 93b38cd | 2012-03-22 14:31:36 +0100 | [diff] [blame] | 353 | if opts.opc is not None: |
| 354 | opc = opts.opc |
| 355 | if not re.match('^[0-9a-fA-F]{32}$', opc): |
| 356 | raise ValueError('OPC needs to be 128 bits, in hex format') |
| 357 | |
Holger Hans Peter Freyther | cca4179 | 2012-03-22 15:23:14 +0100 | [diff] [blame] | 358 | elif opts.op is not None: |
| 359 | opc = derive_milenage_opc(ki, opts.op) |
Harald Welte | 93b38cd | 2012-03-22 14:31:36 +0100 | [diff] [blame] | 360 | else: |
| 361 | opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)]) |
| 362 | |
Jan Balke | c3ebd33 | 2015-01-26 12:22:55 +0100 | [diff] [blame] | 363 | if opts.pin_adm is not None: |
Alexander Chemeris | a51592e | 2018-01-10 14:07:30 +0900 | [diff] [blame] | 364 | pin_adm = opts.pin_adm |
| 365 | if not re.match('^([0-9a-fA-F][0-9a-fA-F])+$', pin_adm): |
| 366 | raise ValueError('ADM pin needs to be in hex format (even number of hex digits)') |
Jan Balke | c3ebd33 | 2015-01-26 12:22:55 +0100 | [diff] [blame] | 367 | else: |
| 368 | pin_adm = None |
| 369 | |
Harald Welte | 93b38cd | 2012-03-22 14:31:36 +0100 | [diff] [blame] | 370 | |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 371 | # Return that |
| 372 | return { |
| 373 | 'name' : opts.name, |
| 374 | 'iccid' : iccid, |
| 375 | 'mcc' : mcc, |
| 376 | 'mnc' : mnc, |
| 377 | 'imsi' : imsi, |
| 378 | 'smsp' : smsp, |
| 379 | 'ki' : ki, |
Harald Welte | 93b38cd | 2012-03-22 14:31:36 +0100 | [diff] [blame] | 380 | 'opc' : opc, |
Alexander Chemeris | 2188524 | 2013-07-02 16:56:55 +0400 | [diff] [blame] | 381 | 'acc' : acc, |
Jan Balke | c3ebd33 | 2015-01-26 12:22:55 +0100 | [diff] [blame] | 382 | 'pin_adm' : pin_adm, |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 383 | } |
| 384 | |
| 385 | |
| 386 | def print_parameters(params): |
| 387 | |
| 388 | print """Generated card parameters : |
| 389 | > Name : %(name)s |
| 390 | > SMSP : %(smsp)s |
| 391 | > ICCID : %(iccid)s |
| 392 | > MCC/MNC : %(mcc)d/%(mnc)d |
| 393 | > IMSI : %(imsi)s |
| 394 | > Ki : %(ki)s |
Harald Welte | 93b38cd | 2012-03-22 14:31:36 +0100 | [diff] [blame] | 395 | > OPC : %(opc)s |
Alexander Chemeris | 2188524 | 2013-07-02 16:56:55 +0400 | [diff] [blame] | 396 | > ACC : %(acc)s |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 397 | """ % params |
| 398 | |
| 399 | |
Harald Welte | 130524b | 2012-08-13 15:53:43 +0200 | [diff] [blame] | 400 | def write_params_csv(opts, params): |
| 401 | # csv |
Sylvain Munaut | 143e99d | 2010-12-08 22:35:04 +0100 | [diff] [blame] | 402 | if opts.write_csv: |
| 403 | import csv |
Harald Welte | 93b38cd | 2012-03-22 14:31:36 +0100 | [diff] [blame] | 404 | row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc'] |
Sylvain Munaut | 143e99d | 2010-12-08 22:35:04 +0100 | [diff] [blame] | 405 | f = open(opts.write_csv, 'a') |
| 406 | cw = csv.writer(f) |
| 407 | cw.writerow([params[x] for x in row]) |
| 408 | f.close() |
| 409 | |
Harald Welte | c26b829 | 2012-08-15 15:25:51 +0200 | [diff] [blame] | 410 | def _read_params_csv(opts, imsi): |
Harald Welte | 7f62cec | 2012-08-13 20:07:41 +0200 | [diff] [blame] | 411 | import csv |
| 412 | row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki', 'opc'] |
| 413 | f = open(opts.read_csv, 'r') |
| 414 | cr = csv.DictReader(f, row) |
| 415 | i = 0 |
| 416 | for row in cr: |
Holger Hans Peter Freyther | 4e82468 | 2012-08-15 15:56:05 +0200 | [diff] [blame] | 417 | if opts.num is not None and opts.read_imsi is False: |
Harald Welte | 7f62cec | 2012-08-13 20:07:41 +0200 | [diff] [blame] | 418 | if opts.num == i: |
Harald Welte | c26b829 | 2012-08-15 15:25:51 +0200 | [diff] [blame] | 419 | f.close() |
| 420 | return row; |
| 421 | i += 1 |
Harald Welte | 7f62cec | 2012-08-13 20:07:41 +0200 | [diff] [blame] | 422 | if row['imsi'] == imsi: |
Harald Welte | c26b829 | 2012-08-15 15:25:51 +0200 | [diff] [blame] | 423 | f.close() |
| 424 | return row; |
Harald Welte | 7f62cec | 2012-08-13 20:07:41 +0200 | [diff] [blame] | 425 | |
| 426 | f.close() |
Harald Welte | c26b829 | 2012-08-15 15:25:51 +0200 | [diff] [blame] | 427 | return None |
| 428 | |
| 429 | def read_params_csv(opts, imsi): |
| 430 | row = _read_params_csv(opts, imsi) |
| 431 | if row is not None: |
| 432 | row['mcc'] = int(row['mcc']) |
| 433 | row['mnc'] = int(row['mnc']) |
Harald Welte | 7f62cec | 2012-08-13 20:07:41 +0200 | [diff] [blame] | 434 | return row |
| 435 | |
Harald Welte | c26b829 | 2012-08-15 15:25:51 +0200 | [diff] [blame] | 436 | |
Harald Welte | 130524b | 2012-08-13 15:53:43 +0200 | [diff] [blame] | 437 | def write_params_hlr(opts, params): |
Sylvain Munaut | 143e99d | 2010-12-08 22:35:04 +0100 | [diff] [blame] | 438 | # SQLite3 OpenBSC HLR |
| 439 | if opts.write_hlr: |
| 440 | import sqlite3 |
| 441 | conn = sqlite3.connect(opts.write_hlr) |
| 442 | |
| 443 | c = conn.execute( |
| 444 | 'INSERT INTO Subscriber ' + |
| 445 | '(imsi, name, extension, authorized, created, updated) ' + |
| 446 | 'VALUES ' + |
| 447 | '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));', |
| 448 | [ |
| 449 | params['imsi'], |
| 450 | params['name'], |
Harald Welte | e9e5ecb | 2012-08-15 15:26:30 +0200 | [diff] [blame] | 451 | '9' + params['iccid'][-5:-1] |
Sylvain Munaut | 143e99d | 2010-12-08 22:35:04 +0100 | [diff] [blame] | 452 | ], |
| 453 | ) |
| 454 | sub_id = c.lastrowid |
| 455 | c.close() |
| 456 | |
| 457 | c = conn.execute( |
| 458 | 'INSERT INTO AuthKeys ' + |
| 459 | '(subscriber_id, algorithm_id, a3a8_ki)' + |
| 460 | 'VALUES ' + |
| 461 | '(?,?,?)', |
Sylvain Munaut | 9f120e0 | 2010-12-23 20:28:24 +0100 | [diff] [blame] | 462 | [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ], |
Sylvain Munaut | 143e99d | 2010-12-08 22:35:04 +0100 | [diff] [blame] | 463 | ) |
| 464 | |
| 465 | conn.commit() |
| 466 | conn.close() |
| 467 | |
Harald Welte | 130524b | 2012-08-13 15:53:43 +0200 | [diff] [blame] | 468 | def write_parameters(opts, params): |
| 469 | write_params_csv(opts, params) |
Harald Welte | 7f62cec | 2012-08-13 20:07:41 +0200 | [diff] [blame] | 470 | write_params_hlr(opts, params) |
Harald Welte | 130524b | 2012-08-13 15:53:43 +0200 | [diff] [blame] | 471 | |
Sylvain Munaut | 143e99d | 2010-12-08 22:35:04 +0100 | [diff] [blame] | 472 | |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 473 | BATCH_STATE = [ 'name', 'country', 'mcc', 'mnc', 'smsp', 'secret', 'num' ] |
| 474 | BATCH_INCOMPATIBLE = ['iccid', 'imsi', 'ki'] |
Sylvain Munaut | 143e99d | 2010-12-08 22:35:04 +0100 | [diff] [blame] | 475 | |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 476 | def init_batch(opts): |
| 477 | # Need to do something ? |
| 478 | if not opts.batch_mode: |
| 479 | return |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 480 | |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 481 | for k in BATCH_INCOMPATIBLE: |
| 482 | if getattr(opts, k): |
| 483 | print "Incompatible option with batch_state: %s" % (k,) |
| 484 | sys.exit(-1) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 485 | |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 486 | # Don't load state if there is none ... |
| 487 | if not opts.batch_state: |
| 488 | return |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 489 | |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 490 | if not os.path.isfile(opts.batch_state): |
| 491 | print "No state file yet" |
| 492 | return |
| 493 | |
| 494 | # Get stored data |
| 495 | fh = open(opts.batch_state) |
| 496 | d = json.loads(fh.read()) |
| 497 | fh.close() |
| 498 | |
| 499 | for k,v in d.iteritems(): |
| 500 | setattr(opts, k, v) |
| 501 | |
| 502 | |
| 503 | def save_batch(opts): |
| 504 | # Need to do something ? |
| 505 | if not opts.batch_mode or not opts.batch_state: |
| 506 | return |
| 507 | |
| 508 | d = json.dumps(dict([(k,getattr(opts,k)) for k in BATCH_STATE])) |
| 509 | fh = open(opts.batch_state, 'w') |
| 510 | fh.write(d) |
| 511 | fh.close() |
| 512 | |
| 513 | |
| 514 | def card_detect(opts, scc): |
Sylvain Munaut | bdca252 | 2010-12-09 13:31:58 +0100 | [diff] [blame] | 515 | |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 516 | # Detect type if needed |
| 517 | card = None |
| 518 | ctypes = dict([(kls.name, kls) for kls in _cards_classes]) |
| 519 | |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 520 | if opts.type in ("auto", "auto_once"): |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 521 | for kls in _cards_classes: |
| 522 | card = kls.autodetect(scc) |
| 523 | if card: |
| 524 | print "Autodetected card type %s" % card.name |
| 525 | card.reset() |
| 526 | break |
| 527 | |
| 528 | if card is None: |
| 529 | print "Autodetection failed" |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 530 | return |
| 531 | |
| 532 | if opts.type == "auto_once": |
| 533 | opts.type = card.name |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 534 | |
| 535 | elif opts.type in ctypes: |
| 536 | card = ctypes[opts.type](scc) |
| 537 | |
| 538 | else: |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 539 | raise ValueError("Unknown card type %s" % opts.type) |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 540 | |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 541 | return card |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 542 | |
Sylvain Munaut | 76504e0 | 2010-12-07 00:24:32 +0100 | [diff] [blame] | 543 | |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 544 | if __name__ == '__main__': |
| 545 | |
| 546 | # Parse options |
| 547 | opts = parse_options() |
| 548 | |
| 549 | # Connect to the card |
| 550 | if opts.pcsc_dev is None: |
| 551 | from pySim.transport.serial import SerialSimLink |
| 552 | sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate) |
| 553 | else: |
| 554 | from pySim.transport.pcsc import PcscSimLink |
| 555 | sl = PcscSimLink(opts.pcsc_dev) |
| 556 | |
| 557 | # Create command layer |
| 558 | scc = SimCardCommands(transport=sl) |
| 559 | |
| 560 | # Batch mode init |
| 561 | init_batch(opts) |
| 562 | |
| 563 | # Iterate |
| 564 | done = False |
| 565 | first = True |
| 566 | card = None |
Sylvain Munaut | 1a91443 | 2011-12-08 20:08:26 +0100 | [diff] [blame] | 567 | |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 568 | while not done: |
Harald Welte | e9e5ecb | 2012-08-15 15:26:30 +0200 | [diff] [blame] | 569 | |
| 570 | if opts.dry_run is False: |
| 571 | # Connect transport |
| 572 | print "Insert card now (or CTRL-C to cancel)" |
| 573 | sl.wait_for_card(newcardonly=not first) |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 574 | |
| 575 | # Not the first anymore ! |
| 576 | first = False |
| 577 | |
Harald Welte | e9e5ecb | 2012-08-15 15:26:30 +0200 | [diff] [blame] | 578 | if opts.dry_run is False: |
| 579 | # Get card |
| 580 | card = card_detect(opts, scc) |
| 581 | if card is None: |
| 582 | if opts.batch_mode: |
| 583 | first = False |
| 584 | continue |
| 585 | else: |
| 586 | sys.exit(-1) |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 587 | |
Harald Welte | e9e5ecb | 2012-08-15 15:26:30 +0200 | [diff] [blame] | 588 | # Erase if requested |
| 589 | if opts.erase: |
| 590 | print "Formatting ..." |
| 591 | card.erase() |
| 592 | card.reset() |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 593 | |
| 594 | # Generate parameters |
Harald Welte | 7f62cec | 2012-08-13 20:07:41 +0200 | [diff] [blame] | 595 | if opts.source == 'cmdline': |
| 596 | cp = gen_parameters(opts) |
| 597 | elif opts.source == 'csv': |
Holger Hans Peter Freyther | 4e82468 | 2012-08-15 15:56:05 +0200 | [diff] [blame] | 598 | if opts.read_imsi: |
| 599 | if opts.dry_run: |
| 600 | # Connect transport |
| 601 | print "Insert card now (or CTRL-C to cancel)" |
| 602 | sl.wait_for_card(newcardonly=not first) |
Alexander Chemeris | 47c73ab | 2018-01-10 14:10:17 +0900 | [diff] [blame] | 603 | (res,_) = scc.read_binary(EF['IMSI']) |
Holger Hans Peter Freyther | 4e82468 | 2012-08-15 15:56:05 +0200 | [diff] [blame] | 604 | imsi = swap_nibbles(res)[3:] |
| 605 | else: |
| 606 | imsi = opts.imsi |
| 607 | cp = read_params_csv(opts, imsi) |
Harald Welte | 7f62cec | 2012-08-13 20:07:41 +0200 | [diff] [blame] | 608 | if cp is None: |
| 609 | print "Error reading parameters\n" |
| 610 | sys.exit(2) |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 611 | print_parameters(cp) |
| 612 | |
Harald Welte | e9e5ecb | 2012-08-15 15:26:30 +0200 | [diff] [blame] | 613 | if opts.dry_run is False: |
| 614 | # Program the card |
| 615 | print "Programming ..." |
| 616 | if opts.dry_run is not True: |
| 617 | card.program(cp) |
| 618 | else: |
| 619 | print "Dry Run: NOT PROGRAMMING!" |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 620 | |
| 621 | # Write parameters permanently |
| 622 | write_parameters(opts, cp) |
| 623 | |
| 624 | # Batch mode state update and save |
Sylvain Munaut | 8d243e8 | 2010-12-23 20:27:48 +0100 | [diff] [blame] | 625 | if opts.num is not None: |
| 626 | opts.num += 1 |
Sylvain Munaut | 8f7d3ba | 2010-12-09 13:32:48 +0100 | [diff] [blame] | 627 | save_batch(opts) |
| 628 | |
| 629 | # Done for this card and maybe for everything ? |
| 630 | print "Done !\n" |
| 631 | |
| 632 | if not opts.batch_mode: |
| 633 | done = True |