blob: f5b9bc6f43759652ef7f01e5370e2390b5697f5d [file] [log] [blame]
Alexander Chemeris2322c1f2018-01-26 16:45:59 +09001#!/usr/bin/env python
2
3#
4# Utility to write data from a Fairwaves SIM card DB to Osmocom HLR DB
5#
6# Copyright (C) 2017-2018 Alexander Chemeris <alexander.chemeris@gmail.com>
7#
8# This program is free software: you can redistribute it and/or modify
9# it under the terms of the GNU General Public License as published by
10# the Free Software Foundation, either version 2 of the License, or
11# (at your option) any later version.
12#
13# This program is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License
19# along with this program. If not, see <http://www.gnu.org/licenses/>.
20#
21
22from optparse import OptionParser
23import os
24import sys
25import csv
26
27#from pySim.utils import h2b
28def h2b(s):
29 return ''.join([chr((int(x,16)<<4)+int(y,16)) for x,y in zip(s[0::2], s[1::2])])
30
31def load_sim_db(filename):
32 sim_db = {}
33 with open(filename, 'r') as f:
34 reader = csv.reader(f, delimiter=' ')
35 # Skip the header
36# reader.next()
37 for l in reader:
38 sim_db[l[0]] = l
39 return sim_db
40
41def _dbi_binary_quote(s):
42 # Count usage of each char
43 cnt = {}
44 for c in s:
45 cnt[c] = cnt.get(c, 0) + 1
46
47 # Find best offset
48 e = 0
49 m = len(s)
50 for i in range(1, 256):
51 if i == 39:
52 continue
53 sum_ = cnt.get(i, 0) + cnt.get((i+1)&0xff, 0) + cnt.get((i+39)&0xff, 0)
54 if sum_ < m:
55 m = sum_
56 e = i
57 if m == 0: # No overhead ? use this !
58 break;
59
60 # Generate output
61 out = []
62 out.append( chr(e) ) # Offset
63 for c in s:
64 x = (256 + ord(c) - e) % 256
65 if x in (0, 1, 39):
66 out.append('\x01')
67 out.append(chr(x+1))
68 else:
69 out.append(chr(x))
70
71 return ''.join(out)
72
73def write_key_hlr(opts, sim_data):
74 # SQLite3 OpenBSC HLR
75 import sqlite3
76 conn = sqlite3.connect(opts.hlr_db_filename)
77
78 imsi = sim_data[1]
79 ki = sim_data[8]
80
81 c = conn.execute('SELECT id FROM Subscriber WHERE imsi = ?', (imsi,))
82 sub_id = c.fetchone()
83 if sub_id is None:
84 print("IMSI %s is not found in the HLR" % (imsi,))
85 return None
86 sub_id = sub_id[0]
87 print("IMSI %s has ID %d, writing Ki %s" % (imsi, sub_id, ki))
88
89# c = conn.execute(
90# 'INSERT INTO Subscriber ' +
91# '(imsi, name, extension, authorized, created, updated) ' +
92# 'VALUES ' +
93# '(?,?,?,1,datetime(\'now\'),datetime(\'now\'));',
94# [
95# params['imsi'],
96# params['name'],
97# '9' + params['iccid'][-5:-1]
98# ],
99# )
100# sub_id = c.lastrowid
101# c.close()
102
103 c = conn.execute(
104 'INSERT OR REPLACE INTO AuthKeys ' +
105 '(subscriber_id, algorithm_id, a3a8_ki)' +
106 'VALUES ' +
107 '(?,?,?)',
108 [ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(ki))) ],
109 )
110
111 c = conn.execute(
112 'DELETE FROM AuthLastTuples WHERE subscriber_id = ?',
113 [ sub_id ],
114 )
115
116 conn.commit()
117 conn.close()
118 return True
119
120
121def parse_options():
122
123 parser = OptionParser(usage="usage: %prog [options]",
124 description="Utility to write data from a Fairwaves SIM card DB to Osmocom HLR DB.")
125
126 parser.add_option("-s", "--sim-db", dest="sim_db_filename", type='string', metavar="FILE",
127 help="filename of a SIM DB to load keys from (space searated)",
128 default="sim_db.dat",
129 )
130 parser.add_option("-d", "--hlr", dest="hlr_db_filename", type='string', metavar="FILE",
131 help="filename of a HLR SQLite3 DB to write the keys to",
132 default="hlr.sqlite3",
133 )
134
135 (options, args) = parser.parse_args()
136
137 if args:
138 parser.error("Extraneous arguments")
139
140 return options
141
142
143if __name__ == '__main__':
144
145 # Parse options
146 opts = parse_options()
147
148 print("Loading SIM DB ...")
149 sim_db = load_sim_db(opts.sim_db_filename)
150
151 for iccid, sim in sim_db.items():
152 write_key_hlr(opts, sim)
153
154