blob: 8f74adcc2e923ab7e13ee2f81ae4e90f72bd2725 [file] [log] [blame]
Harald Weltec781ab82021-05-23 11:50:19 +02001#!/usr/bin/env python3
2#
3# sim-rest-client.py: client program to test the sim-rest-server.py
4#
5# this will generate authentication tuples just like a HLR / HSS
6# and will then send the related challenge to the REST interface
7# of sim-rest-server.py
8#
9# sim-rest-server.py will then contact the SIM card to perform the
10# authentication (just like a 3GPP RAN), and return the results via
11# the REST to sim-rest-client.py.
12#
13# (C) 2021 by Harald Welte <laforge@osmocom.org>
14#
15# This program is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 2 of the License, or
18# (at your option) any later version.
19#
20# This program is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with this program. If not, see <http://www.gnu.org/licenses/>.
27
28from typing import Optional, Dict
29
30import sys
31import argparse
32import secrets
33import requests
34
35from CryptoMobile.Milenage import Milenage
36from CryptoMobile.utils import xor_buf
37
38def unpack48(x:bytes) -> int:
39 """Decode a big-endian 48bit number from binary to integer."""
40 return int.from_bytes(x, byteorder='big')
41
42def pack48(x:int) -> bytes:
43 """Encode a big-endian 48bit number from integer to binary."""
44 return x.to_bytes(48 // 8, byteorder='big')
45
46def milenage_generate(opc:bytes, amf:bytes, k:bytes, sqn:bytes, rand:bytes) -> Dict[str, bytes]:
47 """Generate an MILENAGE Authentication Tuple."""
48 m = Milenage(None)
49 m.set_opc(opc)
50 mac_a = m.f1(k, rand, sqn, amf)
51 res, ck, ik, ak = m.f2345(k, rand)
52
53 # AUTN = (SQN ^ AK) || AMF || MAC
54 sqn_ak = xor_buf(sqn, ak)
55 autn = b''.join([sqn_ak, amf, mac_a])
56
57 return {'res': res, 'ck': ck, 'ik': ik, 'autn': autn}
58
59def milenage_auts(opc:bytes, k:bytes, rand:bytes, auts:bytes) -> Optional[bytes]:
60 """Validate AUTS. If successful, returns SQN_MS"""
61 amf = b'\x00\x00' # TS 33.102 Section 6.3.3
62 m = Milenage(None)
63 m.set_opc(opc)
64 ak = m.f5star(k, rand)
65
66 sqn_ak = auts[:6]
67 sqn = xor_buf(sqn_ak, ak[:6])
68
69 mac_s = m.f1star(k, rand, sqn, amf)
70 if mac_s == auts[6:14]:
71 return sqn
72 else:
73 return False
74
75
76def build_url(suffix:str) -> str:
77 """Build an URL from global server_host, server_port, BASE_PATH and suffix."""
78 BASE_PATH= "/sim-auth-api/v1"
79 return "http://%s:%u%s%s" % (server_host, server_port, BASE_PATH, suffix)
80
81
82def rest_post(suffix:str, js:Optional[dict] = None):
83 """Perform a RESTful POST."""
84 url = build_url(suffix)
85 if verbose:
86 print("POST %s (%s)" % (url, str(js)))
87 resp = requests.post(url, json=js)
88 if verbose:
89 print("-> %s" % (resp))
90 if not resp.ok:
91 print("POST failed")
92 return resp
93
94
95
96def main(argv):
97 global server_port, server_host, verbose
98
99 parser = argparse.ArgumentParser()
100 parser.add_argument("-H", "--host", help="Host to connect to", default="localhost")
101 parser.add_argument("-p", "--port", help="TCP port to connect to", default=8000)
102 parser.add_argument("-v", "--verbose", help="increase output verbosity", action='count', default=0)
103 parser.add_argument("-n", "--slot-nr", help="SIM slot number", type=int, default=0)
104 parser.add_argument("-c", "--count", help="Auth count", type=int, default=10)
105
106 parser.add_argument("-k", "--key", help="Secret key K (hex)", type=str, required=True)
107 parser.add_argument("-o", "--opc", help="Secret OPc (hex)", type=str, required=True)
108 parser.add_argument("-a", "--amf", help="AMF Field (hex)", type=str, default="0000")
109 parser.add_argument("-s", "--sqn", help="SQN Field (hex)", type=str, default="000000000000")
110
111 args = parser.parse_args()
112
113 server_host = args.host
114 server_port = args.port
115 verbose = args.verbose
116
117 #opc = bytes.fromhex('767A662ACF4587EB0C450C6A95540A04')
118 #k = bytes.fromhex('876B2D8D403EE96755BEF3E0A1857EBE')
119 opc = bytes.fromhex(args.opc)
120 k = bytes.fromhex(args.key)
121 amf = bytes.fromhex(args.amf)
122 sqn = bytes.fromhex(args.sqn)
123
124 for i in range(args.count):
125 rand = secrets.token_bytes(16)
126 t = milenage_generate(opc=opc, amf=amf, k=k, sqn=sqn, rand=rand)
127
128 req_json = {'rand': rand.hex(), 'autn': t['autn'].hex()}
129 print("-> %s" % req_json)
130 resp = rest_post('/slot/%u' % args.slot_nr, req_json)
131 resp_json = resp.json()
132 print("<- %s" % resp_json)
133 if 'synchronisation_failure' in resp_json:
134 auts = bytes.fromhex(resp_json['synchronisation_failure']['auts'])
135 sqn_ms = milenage_auts(opc, k, rand, auts)
136 if sqn_ms is not False:
137 print("SQN_MS = %s" % sqn_ms.hex())
138 sqn_ms_int = unpack48(sqn_ms)
139 # we assume an IND bit-length of 5 here
140 sqn = pack48(sqn_ms_int + (1 << 5))
141 else:
142 raise RuntimeError("AUTS auth failure during re-sync?!?")
143 elif 'successful_3g_authentication' in resp_json:
144 auth_res = resp_json['successful_3g_authentication']
145 assert bytes.fromhex(auth_res['res']) == t['res']
146 assert bytes.fromhex(auth_res['ck']) == t['ck']
147 assert bytes.fromhex(auth_res['ik']) == t['ik']
148 # we assume an IND bit-length of 5 here
149 sqn = pack48(unpack48(sqn) + (1 << 5))
150 else:
151 raise RuntimeError("Auth failure")
152
153
154if __name__ == "__main__":
155 main(sys.argv)