Compare commits
4 Commits
ewild/ppk_
...
ccc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f81cbf1f0 | ||
|
|
487d01833d | ||
|
|
33339a6daa | ||
|
|
93ec5f3566 |
153
ccc-fix.py
Executable file
153
ccc-fix.py
Executable file
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
#
|
||||
# Utility to write the cards
|
||||
#
|
||||
#
|
||||
# Copyright (C) 2009 Sylvain Munaut <tnt@246tNt.com>
|
||||
# Copyright (C) 2010 Harald Welte <laforge@gnumonks.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
from optparse import OptionParser
|
||||
|
||||
from pySim.commands import SimCardCommands
|
||||
from pySim.cards import _cards_classes
|
||||
|
||||
|
||||
|
||||
def card_detect(opts, scc):
|
||||
|
||||
# Detect type if needed
|
||||
card = None
|
||||
ctypes = dict([(kls.name, kls) for kls in _cards_classes])
|
||||
|
||||
if opts.type in ("auto", "auto_once"):
|
||||
for kls in _cards_classes:
|
||||
card = kls.autodetect(scc)
|
||||
if card:
|
||||
print "Autodetected card type %s" % card.name
|
||||
card.reset()
|
||||
break
|
||||
|
||||
if card is None:
|
||||
print "Autodetection failed"
|
||||
return
|
||||
|
||||
if opts.type == "auto_once":
|
||||
opts.type = card.name
|
||||
|
||||
elif opts.type in ctypes:
|
||||
card = ctypes[opts.type](scc)
|
||||
|
||||
else:
|
||||
raise ValueError("Unknown card type %s" % opts.type)
|
||||
|
||||
return card
|
||||
|
||||
|
||||
#
|
||||
# Main
|
||||
#
|
||||
|
||||
def parse_options():
|
||||
|
||||
parser = OptionParser(usage="usage: %prog [options]")
|
||||
|
||||
# Card interface
|
||||
parser.add_option("-d", "--device", dest="device", metavar="DEV",
|
||||
help="Serial Device for SIM access [default: %default]",
|
||||
default="/dev/ttyUSB0",
|
||||
)
|
||||
parser.add_option("-b", "--baud", dest="baudrate", type="int", metavar="BAUD",
|
||||
help="Baudrate used for SIM access [default: %default]",
|
||||
default=9600,
|
||||
)
|
||||
parser.add_option("-p", "--pcsc-device", dest="pcsc_dev", type='int', metavar="PCSC",
|
||||
help="Which PC/SC reader number for SIM access",
|
||||
default=None,
|
||||
)
|
||||
parser.add_option("-t", "--type", dest="type",
|
||||
help="Card type (user -t list to view) [default: %default]",
|
||||
default="auto",
|
||||
)
|
||||
|
||||
(options, args) = parser.parse_args()
|
||||
|
||||
if options.type == 'list':
|
||||
for kls in _cards_classes:
|
||||
print kls.name
|
||||
sys.exit(0)
|
||||
|
||||
if args:
|
||||
parser.error("Extraneous arguments")
|
||||
|
||||
return options
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
# Parse options
|
||||
opts = parse_options()
|
||||
|
||||
# Connect to the card
|
||||
if opts.pcsc_dev is None:
|
||||
from pySim.transport.serial import SerialSimLink
|
||||
sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
|
||||
else:
|
||||
from pySim.transport.pcsc import PcscSimLink
|
||||
sl = PcscSimLink(opts.pcsc_dev)
|
||||
|
||||
# Create command layer
|
||||
scc = SimCardCommands(transport=sl)
|
||||
|
||||
# Iterate
|
||||
done = False
|
||||
first = True
|
||||
card = None
|
||||
|
||||
while not done:
|
||||
# Connect transport
|
||||
print "Insert card now (or CTRL-C to cancel)"
|
||||
sl.wait_for_card(newcardonly=not first)
|
||||
|
||||
# Not the first anymore !
|
||||
first = False
|
||||
|
||||
# Get card
|
||||
card = card_detect(opts, scc)
|
||||
if card is None:
|
||||
if opts.batch_mode:
|
||||
first = False
|
||||
continue
|
||||
else:
|
||||
sys.exit(-1)
|
||||
|
||||
# Check type
|
||||
if card.name != 'fakemagicsim':
|
||||
print "Can't fix this type of card ..."
|
||||
continue
|
||||
|
||||
# Fix record
|
||||
data, sw = scc.read_record(['000c'], 1)
|
||||
data_new = data[0:100] + 'fffffffffffffffffffffffffdffffffffffffffffffffffff0791947106004034ffffffffffffff'
|
||||
scc.update_record(['000c'], 1, data_new)
|
||||
|
||||
# Done for this card and maybe for everything ?
|
||||
print "Card should be fixed now !\n"
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
254
ccc-gen.py
Executable file
254
ccc-gen.py
Executable file
@@ -0,0 +1,254 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
#
|
||||
# Utility to generate the HLR
|
||||
#
|
||||
#
|
||||
# Copyright (C) 2010 Sylvain Munaut <tnt@246tNt.com>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
from optparse import OptionParser
|
||||
|
||||
from ccc import StateManager, CardParametersGenerator, isnum
|
||||
from pySim.utils import h2b, swap_nibbles, rpad
|
||||
|
||||
|
||||
#
|
||||
# OpenBSC HLR Writing
|
||||
#
|
||||
|
||||
def _dbi_binary_quote(s):
|
||||
# Count usage of each char
|
||||
cnt = {}
|
||||
for c in s:
|
||||
cnt[c] = cnt.get(c, 0) + 1
|
||||
|
||||
# Find best offset
|
||||
e = 0
|
||||
m = len(s)
|
||||
for i in range(1, 256):
|
||||
if i == 39:
|
||||
continue
|
||||
sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
|
||||
if sum_ < m:
|
||||
m = sum_
|
||||
e = i
|
||||
if m == 0: # No overhead ? use this !
|
||||
break;
|
||||
|
||||
# Generate output
|
||||
out = []
|
||||
out.append( chr(e) ) # Offset
|
||||
for c in s:
|
||||
x = (256 + ord(c) - e) % 256
|
||||
if x in (0, 1, 39):
|
||||
out.append('\x01')
|
||||
out.append(chr(x+1))
|
||||
else:
|
||||
out.append(chr(x))
|
||||
|
||||
return ''.join(out)
|
||||
|
||||
|
||||
def hlr_write_cards(filename, network, cards):
|
||||
|
||||
import sqlite3
|
||||
|
||||
conn = sqlite3.connect(filename)
|
||||
|
||||
for card in cards:
|
||||
c = conn.execute(
|
||||
'INSERT INTO Subscriber ' +
|
||||
'(imsi, name, extension, authorized, created, updated) ' +
|
||||
'VALUES ' +
|
||||
'(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
|
||||
[
|
||||
card.imsi,
|
||||
'%s #%d' % (network.name, card.num),
|
||||
'9%05d' % card.num,
|
||||
],
|
||||
)
|
||||
sub_id = c.lastrowid
|
||||
c.close()
|
||||
|
||||
c = conn.execute(
|
||||
'INSERT INTO AuthKeys ' +
|
||||
'(subscriber_id, algorithm_id, a3a8_ki)' +
|
||||
'VALUES ' +
|
||||
'(?,?,?)',
|
||||
[ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(card.ki))) ],
|
||||
)
|
||||
c.close()
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
#
|
||||
# CSV Writing
|
||||
#
|
||||
|
||||
def csv_write_cards(filename, network, cards):
|
||||
import csv
|
||||
fh = open(filename, 'a')
|
||||
cw = csv.writer(fh)
|
||||
cw.writerows(cards)
|
||||
fh.close()
|
||||
|
||||
|
||||
#
|
||||
# Main stuff
|
||||
#
|
||||
|
||||
def parse_options():
|
||||
|
||||
parser = OptionParser(usage="usage: %prog [options]")
|
||||
|
||||
# Network parameters
|
||||
parser.add_option("-n", "--name", dest="name",
|
||||
help="Operator name [default: %default]",
|
||||
default="CCC Event",
|
||||
)
|
||||
parser.add_option("-c", "--country", dest="country", type="int", metavar="CC",
|
||||
help="Country code [default: %default]",
|
||||
default=49,
|
||||
)
|
||||
parser.add_option("-x", "--mcc", dest="mcc", type="int",
|
||||
help="Mobile Country Code [default: %default]",
|
||||
default=262,
|
||||
)
|
||||
parser.add_option("-y", "--mnc", dest="mnc", type="int",
|
||||
help="Mobile Network Code [default: %default]",
|
||||
default=42,
|
||||
)
|
||||
parser.add_option("-m", "--smsc", dest="smsc",
|
||||
help="SMSP [default: '00 + country code + 5555']",
|
||||
)
|
||||
parser.add_option("-M", "--smsp", dest="smsp",
|
||||
help="Raw SMSP content in hex [default: auto from SMSC]",
|
||||
)
|
||||
|
||||
# Autogen
|
||||
parser.add_option("-z", "--secret", dest="secret", metavar="STR",
|
||||
help="Secret used for ICCID/IMSI autogen",
|
||||
)
|
||||
parser.add_option("-k", "--count", dest="count", type="int", metavar="CNT",
|
||||
help="Number of entried to generate [default: %default]",
|
||||
default=1000,
|
||||
)
|
||||
|
||||
# Output
|
||||
parser.add_option("--state", dest="state_file", metavar="FILE",
|
||||
help="Use this state file",
|
||||
)
|
||||
parser.add_option("--write-csv", dest="write_csv", metavar="FILE",
|
||||
help="Append generated parameters in CSV file",
|
||||
)
|
||||
parser.add_option("--write-hlr", dest="write_hlr", metavar="FILE",
|
||||
help="Append generated parameters to OpenBSC HLR sqlite3",
|
||||
)
|
||||
|
||||
(options, args) = parser.parse_args()
|
||||
|
||||
if args:
|
||||
parser.error("Extraneous arguments")
|
||||
|
||||
# Check everything
|
||||
if 1 < len(options.name) > 16:
|
||||
parser.error("Name must be between 1 and 16 characters")
|
||||
|
||||
if 0 < options.country > 999:
|
||||
parser.error("Invalid country code")
|
||||
|
||||
if 0 < options.mcc > 999:
|
||||
parser.error("Invalid Mobile Country Code (MCC)")
|
||||
if 0 < options.mnc > 999:
|
||||
parser.error("Invalid Mobile Network Code (MNC)")
|
||||
|
||||
# SMSP
|
||||
if options.smsp is not None:
|
||||
smsp = options.smsp
|
||||
if not _ishex(smsp):
|
||||
raise ValueError('SMSP must be hex digits only !')
|
||||
if len(smsp) < 28*2:
|
||||
raise ValueError('SMSP must be at least 28 bytes')
|
||||
|
||||
else:
|
||||
if options.smsc is not None:
|
||||
smsc = options.smsc
|
||||
if not _isnum(smsc):
|
||||
raise ValueError('SMSC must be digits only !')
|
||||
else:
|
||||
smsc = '00%d' % options.country + '5555' # Hack ...
|
||||
|
||||
smsc = '%02d' % ((len(smsc) + 3)//2,) + "81" + swap_nibbles(rpad(smsc, 20))
|
||||
|
||||
options.smsp = (
|
||||
'e1' + # Parameters indicator
|
||||
'ff' * 12 + # TP-Destination address
|
||||
smsc + # TP-Service Centre Address
|
||||
'00' + # TP-Protocol identifier
|
||||
'00' + # TP-Data coding scheme
|
||||
'00' # TP-Validity period
|
||||
)
|
||||
|
||||
return options
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
# Parse options
|
||||
opts = parse_options()
|
||||
|
||||
# Load state
|
||||
sm = StateManager(opts.state_file, opts)
|
||||
sm.load()
|
||||
|
||||
# Instanciate generator
|
||||
np = sm.network
|
||||
cpg = CardParametersGenerator(np.cc, np.mcc, np.mnc, sm.get_secret())
|
||||
|
||||
# Generate cards
|
||||
imsis = set()
|
||||
cards = []
|
||||
while len(cards) < opts.count:
|
||||
# Next number
|
||||
i = sm.next_gen_num()
|
||||
|
||||
# Generate card number
|
||||
cp = cpg.generate(i)
|
||||
|
||||
# Check for dupes
|
||||
if cp.imsi in imsis:
|
||||
continue
|
||||
imsis.add(cp.imsi)
|
||||
|
||||
# Collect
|
||||
cards.append(cp)
|
||||
|
||||
# Save cards
|
||||
if opts.write_hlr:
|
||||
hlr_write_cards(opts.write_hlr, np, cards)
|
||||
|
||||
if opts.write_csv:
|
||||
csv_write_cards(opts.write_csv, np, cards)
|
||||
|
||||
# Save state
|
||||
sm.save()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
213
ccc-prog.py
Executable file
213
ccc-prog.py
Executable file
@@ -0,0 +1,213 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
#
|
||||
# Utility to write the cards
|
||||
#
|
||||
#
|
||||
# Copyright (C) 2009 Sylvain Munaut <tnt@246tNt.com>
|
||||
# Copyright (C) 2010 Harald Welte <laforge@gnumonks.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
from optparse import OptionParser
|
||||
|
||||
from pySim.commands import SimCardCommands
|
||||
from pySim.cards import _cards_classes
|
||||
|
||||
from ccc import StateManager, CardParameters
|
||||
|
||||
|
||||
|
||||
def csv_load_cards(filename):
|
||||
import csv
|
||||
fh = open(filename, 'r')
|
||||
cr = csv.reader(fh)
|
||||
cards = dict([(int(x[0]), CardParameters(int(x[0]), x[1], x[2], x[3])) for x in cr])
|
||||
fh.close()
|
||||
return cards
|
||||
|
||||
|
||||
def card_detect(opts, scc):
|
||||
|
||||
# Detect type if needed
|
||||
card = None
|
||||
ctypes = dict([(kls.name, kls) for kls in _cards_classes])
|
||||
|
||||
if opts.type in ("auto", "auto_once"):
|
||||
for kls in _cards_classes:
|
||||
card = kls.autodetect(scc)
|
||||
if card:
|
||||
print "Autodetected card type %s" % card.name
|
||||
card.reset()
|
||||
break
|
||||
|
||||
if card is None:
|
||||
print "Autodetection failed"
|
||||
return
|
||||
|
||||
if opts.type == "auto_once":
|
||||
opts.type = card.name
|
||||
|
||||
elif opts.type in ctypes:
|
||||
card = ctypes[opts.type](scc)
|
||||
|
||||
else:
|
||||
raise ValueError("Unknown card type %s" % opts.type)
|
||||
|
||||
return card
|
||||
|
||||
|
||||
def print_parameters(params):
|
||||
|
||||
print """Generated card parameters :
|
||||
> Name : %(name)s
|
||||
> SMSP : %(smsp)s
|
||||
> ICCID : %(iccid)s
|
||||
> MCC/MNC : %(mcc)d/%(mnc)d
|
||||
> IMSI : %(imsi)s
|
||||
> Ki : %(ki)s
|
||||
""" % params
|
||||
|
||||
|
||||
#
|
||||
# Main
|
||||
#
|
||||
|
||||
def parse_options():
|
||||
|
||||
parser = OptionParser(usage="usage: %prog [options]")
|
||||
|
||||
# Card interface
|
||||
parser.add_option("-d", "--device", dest="device", metavar="DEV",
|
||||
help="Serial Device for SIM access [default: %default]",
|
||||
default="/dev/ttyUSB0",
|
||||
)
|
||||
parser.add_option("-b", "--baud", dest="baudrate", type="int", metavar="BAUD",
|
||||
help="Baudrate used for SIM access [default: %default]",
|
||||
default=9600,
|
||||
)
|
||||
parser.add_option("-p", "--pcsc-device", dest="pcsc_dev", type='int', metavar="PCSC",
|
||||
help="Which PC/SC reader number for SIM access",
|
||||
default=None,
|
||||
)
|
||||
parser.add_option("-t", "--type", dest="type",
|
||||
help="Card type (user -t list to view) [default: %default]",
|
||||
default="auto",
|
||||
)
|
||||
parser.add_option("-e", "--erase", dest="erase", action='store_true',
|
||||
help="Erase beforehand [default: %default]",
|
||||
default=False,
|
||||
)
|
||||
|
||||
# Data source
|
||||
parser.add_option("--state", dest="state_file", metavar="FILE",
|
||||
help="Use this state file",
|
||||
)
|
||||
parser.add_option("--read-csv", dest="read_csv", metavar="FILE",
|
||||
help="Read parameters from CSV file",
|
||||
)
|
||||
|
||||
(options, args) = parser.parse_args()
|
||||
|
||||
if options.type == 'list':
|
||||
for kls in _cards_classes:
|
||||
print kls.name
|
||||
sys.exit(0)
|
||||
|
||||
if args:
|
||||
parser.error("Extraneous arguments")
|
||||
|
||||
return options
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
# Parse options
|
||||
opts = parse_options()
|
||||
|
||||
# Connect to the card
|
||||
if opts.pcsc_dev is None:
|
||||
from pySim.transport.serial import SerialSimLink
|
||||
sl = SerialSimLink(device=opts.device, baudrate=opts.baudrate)
|
||||
else:
|
||||
from pySim.transport.pcsc import PcscSimLink
|
||||
sl = PcscSimLink(opts.pcsc_dev)
|
||||
|
||||
# Create command layer
|
||||
scc = SimCardCommands(transport=sl)
|
||||
|
||||
# Load state
|
||||
sm = StateManager(opts.state_file)
|
||||
sm.load()
|
||||
|
||||
np = sm.network
|
||||
|
||||
# Load cards
|
||||
cards = csv_load_cards(opts.read_csv)
|
||||
|
||||
# Iterate
|
||||
done = False
|
||||
first = True
|
||||
card = None
|
||||
|
||||
while not done:
|
||||
# Connect transport
|
||||
print "Insert card now (or CTRL-C to cancel)"
|
||||
sl.wait_for_card(newcardonly=not first)
|
||||
|
||||
# Not the first anymore !
|
||||
first = False
|
||||
|
||||
# Get card
|
||||
card = card_detect(opts, scc)
|
||||
if card is None:
|
||||
if opts.batch_mode:
|
||||
first = False
|
||||
continue
|
||||
else:
|
||||
sys.exit(-1)
|
||||
|
||||
# Erase if requested
|
||||
if opts.erase:
|
||||
print "Formatting ..."
|
||||
card.erase()
|
||||
card.reset()
|
||||
|
||||
# Get parameters
|
||||
cp = cards[sm.next_write_num()]
|
||||
cpp = {
|
||||
'name': np.name,
|
||||
'smsp': np.smsp,
|
||||
'iccid': cp.iccid,
|
||||
'mcc': np.mcc,
|
||||
'mnc': np.mnc,
|
||||
'imsi': cp.imsi,
|
||||
'ki': cp.ki,
|
||||
}
|
||||
print_parameters(cpp)
|
||||
|
||||
# Program the card
|
||||
print "Programming ..."
|
||||
card.program(cpp)
|
||||
|
||||
# Update state
|
||||
sm.save()
|
||||
|
||||
# Done for this card and maybe for everything ?
|
||||
print "Card written !\n"
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
193
ccc.py
Normal file
193
ccc.py
Normal file
@@ -0,0 +1,193 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
#
|
||||
# CCC Event HLR management common stuff
|
||||
#
|
||||
#
|
||||
# Copyright (C) 2010 Sylvain Munaut <tnt@246tNt.com>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import random
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
try:
|
||||
import json
|
||||
except Importerror:
|
||||
# Python < 2.5
|
||||
import simplejson as json
|
||||
|
||||
#
|
||||
# Various helpers
|
||||
#
|
||||
|
||||
def isnum(s, l=-1):
|
||||
return s.isdigit() and ((l== -1) or (len(s) == l))
|
||||
|
||||
|
||||
#
|
||||
# Storage tuples
|
||||
#
|
||||
|
||||
CardParameters = namedtuple("CardParameters", "num iccid imsi ki")
|
||||
NetworkParameters = namedtuple("NetworkParameters", "name cc mcc mnc smsp")
|
||||
|
||||
|
||||
#
|
||||
# State management
|
||||
#
|
||||
|
||||
class StateManager(object):
|
||||
|
||||
def __init__(self, filename=None, options=None):
|
||||
# Filename for state storage
|
||||
self._filename = filename
|
||||
|
||||
# Params from options
|
||||
self._net_name = options.name if options else None
|
||||
self._net_cc = options.country if options else None
|
||||
self._net_mcc = options.mcc if options else None
|
||||
self._net_mnc = options.mnc if options else None
|
||||
self._net_smsp = options.smsp if options else None
|
||||
|
||||
self._secret = options.secret if options else None
|
||||
|
||||
# Default
|
||||
self._num_gen = 0
|
||||
self._num_write = 0
|
||||
|
||||
def load(self):
|
||||
# Skip if no state file
|
||||
if self._filename is None:
|
||||
return
|
||||
|
||||
# Skip if doesn't exist yet
|
||||
if not os.path.isfile(self._filename):
|
||||
return
|
||||
|
||||
# Read
|
||||
fh = open(self._filename, 'r')
|
||||
data = fh.read()
|
||||
fh.close()
|
||||
|
||||
# Decode json and merge
|
||||
dd = json.loads(data)
|
||||
|
||||
self._net_name = dd['name']
|
||||
self._net_cc = dd['cc']
|
||||
self._net_mcc = dd['mcc']
|
||||
self._net_mnc = dd['mnc']
|
||||
self._net_smsp = dd['smsp']
|
||||
self._secret = dd['secret']
|
||||
self._num_gen = dd['num_gen']
|
||||
self._num_write = dd['num_write']
|
||||
|
||||
def save(self):
|
||||
# Skip if no state file
|
||||
if self._filename is None:
|
||||
return
|
||||
|
||||
# Serialize
|
||||
data = json.dumps({
|
||||
'name': self._net_name,
|
||||
'cc': self._net_cc,
|
||||
'mcc': self._net_mcc,
|
||||
'mnc': self._net_mnc,
|
||||
'smsp': self._net_smsp,
|
||||
'secret': self._secret,
|
||||
'num_gen': self._num_gen,
|
||||
'num_write': self._num_write,
|
||||
})
|
||||
|
||||
# Save in json
|
||||
fh = open(self._filename, 'w')
|
||||
fh.write(data)
|
||||
fh.close()
|
||||
|
||||
@property
|
||||
def network(self):
|
||||
return NetworkParameters(
|
||||
self._net_name,
|
||||
self._net_cc,
|
||||
self._net_mcc,
|
||||
self._net_mnc,
|
||||
self._net_smsp,
|
||||
)
|
||||
|
||||
def get_secret(self):
|
||||
return self._secret
|
||||
|
||||
def next_gen_num(self):
|
||||
n = self._num_gen
|
||||
self._num_gen += 1
|
||||
return n
|
||||
|
||||
def next_write_num(self):
|
||||
n = self._num_write
|
||||
self._num_write += 1
|
||||
return n
|
||||
|
||||
#
|
||||
# Card parameters generation
|
||||
#
|
||||
|
||||
class CardParametersGenerator(object):
|
||||
|
||||
def __init__(self, cc, mcc, mnc, secret):
|
||||
# Digitize country code (2 or 3 digits)
|
||||
self._cc_digits = ('%03d' if cc > 100 else '%02d') % cc
|
||||
|
||||
# Digitize MCC/MNC (5 or 6 digits)
|
||||
self._plmn_digits = ('%03d%03d' if mnc > 100 else '%03d%02d') % (mcc, mnc)
|
||||
|
||||
# Store secret
|
||||
self._secret = secret
|
||||
|
||||
def _digits(self, usage, len_, num):
|
||||
s = hashlib.sha1(self._secret + usage + '%d' % num)
|
||||
d = ''.join(['%02d'%ord(x) for x in s.digest()])
|
||||
return d[0:len_]
|
||||
|
||||
def _gen_iccid(self, num):
|
||||
iccid = (
|
||||
'89' + # Common prefix (telecom)
|
||||
self._cc_digits + # Country Code on 2/3 digits
|
||||
self._plmn_digits # MCC/MNC on 5/6 digits
|
||||
)
|
||||
ml = 20 - len(iccid)
|
||||
iccid += self._digits('ccid', ml, num)
|
||||
return iccid
|
||||
|
||||
def _gen_imsi(self, num):
|
||||
ml = 15 - len(self._plmn_digits)
|
||||
msin = self._digits('imsi', ml, num)
|
||||
return (
|
||||
self._plmn_digits + # MCC/MNC on 5/6 digits
|
||||
msin # MSIN
|
||||
)
|
||||
|
||||
def _gen_ki(self):
|
||||
return ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
|
||||
|
||||
def generate(self, num):
|
||||
return CardParameters(
|
||||
num,
|
||||
self._gen_iccid(num),
|
||||
self._gen_imsi(num),
|
||||
self._gen_ki(),
|
||||
)
|
||||
Reference in New Issue
Block a user