Compare commits
4 Commits
zecke/tmp2
...
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(),
|
||||
)
|
||||
@@ -62,9 +62,6 @@ def parse_options():
|
||||
help="Card type (user -t list to view) [default: %default]",
|
||||
default="auto",
|
||||
)
|
||||
parser.add_option("-a", "--pin-adm", dest="pin_adm",
|
||||
help="ADM PIN used for provisioning (overwrites default)",
|
||||
)
|
||||
parser.add_option("-e", "--erase", dest="erase", action='store_true',
|
||||
help="Erase beforehand [default: %default]",
|
||||
default=False,
|
||||
@@ -227,7 +224,7 @@ def derive_milenage_opc(ki_hex, op_hex):
|
||||
return b2h(strxor(opc_bytes, h2b(op_hex)))
|
||||
|
||||
def gen_parameters(opts):
|
||||
"""Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki, PIN-ADM from the
|
||||
"""Generates Name, ICCID, MCC, MNC, IMSI, SMSP, Ki from the
|
||||
options given by the user"""
|
||||
|
||||
# MCC/MNC
|
||||
@@ -352,14 +349,6 @@ def gen_parameters(opts):
|
||||
else:
|
||||
opc = ''.join(['%02x' % random.randrange(0,256) for i in range(16)])
|
||||
|
||||
if opts.pin_adm is not None:
|
||||
if len(opts.pin_adm) > 8:
|
||||
raise ValueError("PIN-ADM needs to be <=8 digits")
|
||||
pin_adm = ''.join(['%02x'%(ord(x)) for x in opts.pin_adm])
|
||||
pin_adm = rpad(pin_adm, 16)
|
||||
else:
|
||||
pin_adm = None
|
||||
|
||||
|
||||
# Return that
|
||||
return {
|
||||
@@ -372,7 +361,6 @@ def gen_parameters(opts):
|
||||
'ki' : ki,
|
||||
'opc' : opc,
|
||||
'acc' : acc,
|
||||
'pin_adm' : pin_adm,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -264,11 +264,7 @@ class GrcardSim(Card):
|
||||
#self._scc.verify_chv(4, h2b("4444444444444444"))
|
||||
|
||||
# Authenticate using ADM PIN 5
|
||||
if p['pin_adm']:
|
||||
pin = p['pin_adm']
|
||||
else:
|
||||
pin = h2b("4444444444444444")
|
||||
self._scc.verify_chv(5, pin)
|
||||
self._scc.verify_chv(5, h2b("4444444444444444"))
|
||||
|
||||
# EF.ICCID
|
||||
r = self._scc.select_file(['3f00', '2fe2'])
|
||||
@@ -369,17 +365,11 @@ class SysmoSIMgr2(Card):
|
||||
# P1: 3A for PIN, 3B for PUK
|
||||
# P2: CHV number, as in VERIFY CHV for PIN, and as in UNBLOCK CHV for PUK
|
||||
# P3: 08, CHV length (curiously the PUK is also 08 length, instead of 10)
|
||||
if p['pin_adm']:
|
||||
pin = p['pin_adm']
|
||||
else:
|
||||
pin = h2b("4444444444444444")
|
||||
|
||||
pdu = 'A0D43A0508' + b2h(pin)
|
||||
pdu = 'A0D43A0508' + "4444444444444444"
|
||||
data, sw = self._scc._tp.send_apdu(pdu)
|
||||
|
||||
# authenticate as ADM (enough to write file, and can set PINs)
|
||||
|
||||
self._scc.verify_chv(0x05, pin)
|
||||
self._scc.verify_chv(0x05, h2b("4444444444444444"))
|
||||
|
||||
# write EF.ICCID
|
||||
data, sw = self._scc.update_binary('2fe2', enc_iccid(p['iccid']))
|
||||
@@ -415,60 +405,7 @@ class SysmoSIMgr2(Card):
|
||||
def erase(self):
|
||||
return
|
||||
|
||||
class SysmoUSIMSJS1(Card):
|
||||
"""
|
||||
sysmocom sysmoUSIM-SJS1
|
||||
"""
|
||||
|
||||
name = 'sysmoUSIM-SJS1'
|
||||
|
||||
def __init__(self, ssc):
|
||||
super(SysmoUSIMSJS1, self).__init__(ssc)
|
||||
self._scc.cla_byte = "00"
|
||||
|
||||
@classmethod
|
||||
def autodetect(kls, scc):
|
||||
# TODO: look for ATR 3B 9F 96 80 1F C7 80 31 A0 73 BE 21 13 67 43 20 07 18 00 00 01 A5
|
||||
return None
|
||||
|
||||
def program(self, p):
|
||||
|
||||
|
||||
# select MF
|
||||
r = self._scc.select_file(['3f00'])
|
||||
|
||||
# select DF_GSM
|
||||
r = self._scc.select_file(['7f20'])
|
||||
|
||||
# authenticate as ADM using default key (written on the card..)
|
||||
if not p['pin_adm']:
|
||||
raise ValueError("Please provide a PIN-ADM as there is no default one")
|
||||
|
||||
self._scc.verify_chv(0x0A, h2b(p['pin_adm']))
|
||||
|
||||
|
||||
# set Ki in proprietary file
|
||||
data, sw = self._scc.update_binary('00FF', p['ki'])
|
||||
|
||||
# set Ki in proprietary file
|
||||
content = "01" + p['opc']
|
||||
data, sw = self._scc.update_binary('00F7', content)
|
||||
|
||||
# write EF.IMSI
|
||||
data, sw = self._scc.update_binary('6f07', enc_imsi(p['imsi']))
|
||||
|
||||
# write EF.AUTH
|
||||
content = "0101"
|
||||
r = self._scc.select_file(['7FCC', '6f00'])
|
||||
data, sw = self._scc.update_binary('6f00', content)
|
||||
|
||||
|
||||
|
||||
def erase(self):
|
||||
return
|
||||
|
||||
|
||||
|
||||
# In order for autodetection ...
|
||||
_cards_classes = [ FakeMagicSim, SuperSim, MagicSim, GrcardSim,
|
||||
SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1, SysmoUSIMSJS1 ]
|
||||
SysmoSIMgr1, SysmoSIMgr2, SysmoUSIMgr1 ]
|
||||
|
||||
@@ -28,20 +28,11 @@ from pySim.utils import rpad, b2h
|
||||
class SimCardCommands(object):
|
||||
def __init__(self, transport):
|
||||
self._tp = transport;
|
||||
self._cla_byte = "a0"
|
||||
|
||||
@property
|
||||
def cla_byte(self):
|
||||
return self._cla_byte
|
||||
@cla_byte.setter
|
||||
def cla_byte(self, value):
|
||||
self._cla_byte = value
|
||||
|
||||
|
||||
def select_file(self, dir_list):
|
||||
rv = []
|
||||
for i in dir_list:
|
||||
data, sw = self._tp.send_apdu_checksw(self.cla_byte + "a4000C02" + i)
|
||||
data, sw = self._tp.send_apdu_checksw("a0a4000002" + i)
|
||||
rv.append(data)
|
||||
return rv
|
||||
|
||||
@@ -51,14 +42,14 @@ class SimCardCommands(object):
|
||||
r = self.select_file(ef)
|
||||
if length is None:
|
||||
length = int(r[-1][4:8], 16) - offset
|
||||
pdu = self.cla_byte + 'b0%04x%02x' % (offset, (min(256, length) & 0xff))
|
||||
pdu = 'a0b0%04x%02x' % (offset, (min(256, length) & 0xff))
|
||||
return self._tp.send_apdu(pdu)
|
||||
|
||||
def update_binary(self, ef, data, offset=0):
|
||||
if not hasattr(type(ef), '__iter__'):
|
||||
ef = [ef]
|
||||
self.select_file(ef)
|
||||
pdu = self.cla_byte + 'd6%04x%02x' % (offset, len(data)/2) + data
|
||||
pdu = 'a0d6%04x%02x' % (offset, len(data)/2) + data
|
||||
return self._tp.send_apdu_checksw(pdu)
|
||||
|
||||
def read_record(self, ef, rec_no):
|
||||
@@ -66,7 +57,7 @@ class SimCardCommands(object):
|
||||
ef = [ef]
|
||||
r = self.select_file(ef)
|
||||
rec_length = int(r[-1][28:30], 16)
|
||||
pdu = self.cla_byte + 'b2%02x04%02x' % (rec_no, rec_length)
|
||||
pdu = 'a0b2%02x04%02x' % (rec_no, rec_length)
|
||||
return self._tp.send_apdu(pdu)
|
||||
|
||||
def update_record(self, ef, rec_no, data, force_len=False):
|
||||
@@ -79,7 +70,7 @@ class SimCardCommands(object):
|
||||
raise ValueError('Invalid data length (expected %d, got %d)' % (rec_length, len(data)/2))
|
||||
else:
|
||||
rec_length = len(data)/2
|
||||
pdu = (self.cla_byte + 'dc%02x04%02x' % (rec_no, rec_length)) + data
|
||||
pdu = ('a0dc%02x04%02x' % (rec_no, rec_length)) + data
|
||||
return self._tp.send_apdu_checksw(pdu)
|
||||
|
||||
def record_size(self, ef):
|
||||
@@ -94,11 +85,11 @@ class SimCardCommands(object):
|
||||
if len(rand) != 32:
|
||||
raise ValueError('Invalid rand')
|
||||
self.select_file(['3f00', '7f20'])
|
||||
return self._tp.send_apdu(self.cla_byte + '88000010' + rand)
|
||||
return self._tp.send_apdu('a088000010' + rand)
|
||||
|
||||
def reset_card(self):
|
||||
return self._tp.reset_card()
|
||||
|
||||
def verify_chv(self, chv_no, code):
|
||||
fc = rpad(b2h(code), 16)
|
||||
return self._tp.send_apdu_checksw(self.cla_byte + '2000' + ('%02X' % chv_no) + '08' + fc)
|
||||
return self._tp.send_apdu_checksw('a02000' + ('%02x' % chv_no) + '08' + fc)
|
||||
|
||||
Reference in New Issue
Block a user