forked from Hoernchen/eNB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheNB_LOCAL.py
2824 lines (2174 loc) · 121 KB
/
eNB_LOCAL.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import random
import socket
import struct
import time
import select
from optparse import OptionParser
from pycrate_asn1dir import S1AP
from pycrate_asn1rt.utils import *
from binascii import hexlify, unhexlify
from CryptoMobile.CM import *
from CryptoMobile.Milenage import Milenage
from Crypto.Hash import HMAC
from Crypto.Hash import SHA256
import sys
import fcntl
import os
import subprocess
from threading import Thread
import datetime
import eNAS, eMENU
from helpers import helper_print_pco, nas_pco, do_tun_ss
#tries to import all options for retrieving IMSI, and RES, CK and IK from USIM.
#if all fails, return_imsi and return_res_ck_ik will return None, so local values will be used.
try:
import serial
except:
pass
try:
from smartcard.System import readers
from smartcard.util import toHexString,toBytes
try:
from card.USIM import *
except:
pass
except:
pass
try:
import requests
requests.packages.urllib3.disable_warnings()
except:
pass
def write_gtp_wrap(dic, dic_t, x):
os.write(dic_t,x)
locaddr = '.'.join(f'{c}' for c in dic['ENB-GTP-ADDRESS-INT'].to_bytes(4, 'big') )
gtpua = '.'.join(f'{c}' for c in dic['SGW-GTP-ADDRESS'][-1])
lteid = int.from_bytes(dic['SGW-TEID'][-1], "big") # ok : be -> int
assert lteid.to_bytes(4, 'big') == dic['SGW-TEID'][-1]
dic_r = eMENU.print_log(dic, f"{dic['GTP-U']} {locaddr} {gtpua} {dic['PDN-ADDRESS-IPV4']} {lteid} -> {dic['SGW-TEID'][-1]}")
#{sys._getframe().f_lineno} {sys._getframe().f_code.co_filename}
# with open("gtpwr", "a") as fh:
# fh.write(str(x)+"\n")
dic = do_tun_ss(dic)
return dic_r
PLMN = '12345'
IMSI = PLMN + '1234567890'
IMEISV = '1234567890123456'
IMEI = '123456789012347'
APN = 'internet'
#Examples. Customize at your needs
NON_IP_PACKET_1 = '0102030405060708090a'
NON_IP_PACKET_2 = '0102030405060708090a0102030405060708090a'
NON_IP_PACKET_3 = '0102030405060708090a0102030405060708090a0102030405060708090a'
NON_IP_PACKET_4 = '0102030405060708090a0102030405060708090a0102030405060708090a0102030405060708090a'
# session_dict structure
#
# session_dict['STATE'] = 0
#
# enb info:
# session_dict['ENB-UE-S1AP-ID']
# session_dict['ENB-NAME'] = string with enb nasme
# session_dict['ENB-PLMN'] = plmn
# session_dict['ENB-TAC'] = tac
# session_dict['ENB-ID'] = enb_id
# session_dict['ENB-CELLID'] = enb cellid
# session_dict['ENB-GTP-ADDRESS-INT'] = ip address in integer format to use directly in s1ap
#
# security:
# session_dict['ENC-ALG'] = encryption algorithm 0 to 3
# session_dict['INT-ALG'] = integrity algorithm 1 to 3
# session_dict['ENC-KEY'] = encryption key
# session_dict['INT-KEY'] = integrity key
# session_dict['XRES'] = xres
# session_dict['KASME'] = kasme
# session_dict['NAS-KEY-EEA1']
# session_dict['NAS-KEY-EEA2']
# session_dict['NAS-KEY-EEA3']
# session_dict['NAS-KEY-EIA1']
# session_dict['NAS-KEY-EIA2']
# session_dict['NAS-KEY-EIA3']
# mme info:
# session_dict['MME-NAME'] = mme_name
# session_dict['MME-PLMN'] = servedPLMNs
# session_dict['MME-GROUP-ID'] = servedGroupIDs
# session_dict['MME-CODE'] = servedMMECs
# session_dict['MME-RELATIVE-CAPACITY'] 0 relative capacity
# session_dict['MME-UE-S1AP-ID'] = mme_ue_s1ap_id
#
# nas:
# session_dict['NAS'] = full nas_pdu (either received or to ber sent, header, mac, sqn, and nas ecnrypted or not)
# session_dict['NAS-ENC'] = nas_pdu encrypted (either received or to ber sent, and can be ecnrypted)
# session_dict['UP-COUNT'] = count (integer) . sqn is the last byte %256
# session_dict['DOWN-COUNT'] = count (integer) . sqn is the last byte %256. from the received
# session_dict['DIR'] = 0 or 1 direction 0 uplink, 1 downlink
#
# session_dict['NAS-SMS-MT'] = nas for Answering to SMS-MT
######################################################################################################################################
# GENERAL PROCEDURES: #
######################################################################################################################################
def session_dict_initialization(session_dict):
session_dict['STATE'] = 0
session_dict['ENB-UE-S1AP-ID'] = 1000
session_dict['ENB-NAME'] = 'Fabricio-eNB'
session_dict['ENB-PLMN'] = return_plmn_s1ap(session_dict['PLMN'])
session_dict['XRES'] = b'xresxres'
session_dict['KASME'] = b'kasme kasme kasme kasme '
# hex: 6b61736d652020206b61736d652020206b61736d652020206b61736d65202020
session_dict['ENB-GTP-ADDRESS-INT'] = ''
session_dict['RAB-ID'] = []
session_dict['SGW-GTP-ADDRESS'] = []
session_dict['SGW-TEID'] = []
session_dict['EPS-BEARER-IDENTITY'] = []
session_dict['EPS-BEARER-TYPE'] = [] # default 0, dedicated 1
session_dict['EPS-BEARER-STATE'] = [] # active 1, inactive 0
session_dict['EPS-BEARER-APN'] = []
session_dict['PDN-ADDRESS'] = []
session_dict['PDN-ADDRESS-IPV4'] = None
session_dict['PDN-ADDRESS-IPV6'] = None
if session_dict['ENB-TAC1'] is None:
session_dict['ENB-TAC1'] = b'\x00\x01'
if session_dict['ENB-TAC2'] is None:
session_dict['ENB-TAC2'] = b'\x00\x03'
session_dict['ENB-TAC'] = session_dict['ENB-TAC1']
session_dict['ENB-TAC-NBIOT'] = b'\x00\x02'
session_dict['ENB-ID'] = 1
session_dict['ENB-CELLID'] = 1000000
session_dict['NAS-KEY-EEA1'] = return_key(session_dict['KASME'],1,'NAS-ENC')
session_dict['NAS-KEY-EEA2'] = return_key(session_dict['KASME'],2,'NAS-ENC')
session_dict['NAS-KEY-EEA3'] = return_key(session_dict['KASME'],3,'NAS-ENC')
session_dict['NAS-KEY-EIA1'] = return_key(session_dict['KASME'],1,'NAS-INT')
session_dict['NAS-KEY-EIA2'] = return_key(session_dict['KASME'],2,'NAS-INT')
session_dict['NAS-KEY-EIA3'] = return_key(session_dict['KASME'],3,'NAS-INT')
session_dict['UP-COUNT'] = -1
session_dict['DOWN-COUNT'] = -1
session_dict['ENC-ALG'] = 0
session_dict['INT-ALG'] = 0
session_dict['ENC-KEY'] = None
session_dict['INT-KEY'] = None
session_dict['NAS-SMS-MT'] = None
if session_dict['LOCAL_KEYS'] == True:
if session_dict['IMSI'] == None:
session_dict['IMSI'] = IMSI
else:
if session_dict['IMSI'] == None:
try:
session_dict['IMSI'] = return_imsi(session_dict['SERIAL-INTERFACE'])
if session_dict['IMSI'] == None:
session_dict['LOCAL_KEYS'] = True
session_dict['IMSI'] = IMSI
except:
if session_dict['LOCAL_MILENAGE'] == False:
session_dict['LOCAL_KEYS'] = True
session_dict['IMSI'] = IMSI
if session_dict['IMEISV'] == None:
session_dict['IMEISV'] = IMEISV
session_dict['ENCODED-IMSI'] = eNAS.encode_imsi(session_dict['IMSI'])
session_dict['ENCODED-IMEI'] = eNAS.encode_imei(IMEISV)
if session_dict['ENCODED-GUTI'] == None:
session_dict['ENCODED-GUTI'] = eNAS.encode_guti(session_dict['PLMN'],32769,1,12345678)
session_dict['S-TMSI'] = None
session_dict['TMSI'] = None
session_dict['LAI'] = None
session_dict['CPSR-TYPE'] = 0
session_dict['S1-TYPE'] = "4G"
session_dict['MOBILE-IDENTITY'] = session_dict['ENCODED-IMSI']
session_dict['MOBILE-IDENTITY-TYPE'] = "IMSI"
session_dict['SESSION-SESSION-TYPE'] = "NONE"
session_dict['SESSION-TYPE'] = "4G"
session_dict['SESSION-TYPE-TUN'] = 1
session_dict['PDP-TYPE'] = 1
session_dict['ATTACH-PDN'] = None
session_dict['ATTACH-TYPE'] = 1
session_dict['TAU-TYPE'] = 0
session_dict['SMS-UPDATE-TYPE'] = False
session_dict['NBIOT-SESSION-TYPE'] = "NONE"
session_dict['CPSR-TYPE'] = 0
session_dict['UECONTEXTRELEASE-CSFB'] = False
session_dict['PROCESS-PAGING'] = True
session_dict['PCSCF-RESTORATION'] = False
session_dict['NAS-DELIVERY-INDICATION'] = 0
session_dict['NAS-KEY-SET-IDENTIFIER'] = 0
session_dict['LOG'] = []
session_dict['NON-IP-PACKET'] = 1
session_dict['NON-IP-PACKETS'] = [NON_IP_PACKET_1, NON_IP_PACKET_2, NON_IP_PACKET_3, NON_IP_PACKET_4]
session_dict['PDN-CONNECTIVITY-REQUEST-TYPE'] = 1
return session_dict
def ip2int(addr):
return struct.unpack("!I", socket.inet_aton(addr))[0]
def bytes2hex(byteArray):
return ''.join(hex(i).replace("0x", "0x0")[-2:] for i in byteArray)
def hex2bytes(hex_str):
return bytearray.fromhex(hex_str)
def bcd(chars):
bcd_string = ""
for i in range(len(chars) // 2):
bcd_string += chars[1+2*i] + chars[2*i]
bcd_bytes = bytes(bytearray.fromhex(bcd_string))
return bcd_bytes
def return_plmn_s1ap(mccmnc):
mccmnc = str(mccmnc)
print("Returning PLMN from: " + str(mccmnc))
if len(mccmnc)==5:
return bcd(mccmnc[0] + mccmnc[1] + mccmnc[2] + 'f' + mccmnc[3] + mccmnc[4])
elif len(mccmnc)==6:
return bcd(mccmnc[0] + mccmnc[1] + mccmnc[2] + mccmnc[3] + mccmnc[4] + mccmnc[5])
else:
return b''
def return_plmn(mccmnc):
mccmnc = str(mccmnc)
print("Returning PLMN from: " + str(mccmnc))
if len(mccmnc)==5:
return bcd(mccmnc[0] + mccmnc[1] + mccmnc[2] + 'f' + mccmnc[3] + mccmnc[4])
elif len(mccmnc)==6:
return bcd(mccmnc[0] + mccmnc[1] + mccmnc[2] + mccmnc[5] + mccmnc[3] + mccmnc[4])
else:
return b''
def return_apn(apn):
apn_bytes = bytes()
apn_l = apn.split(".")
for word in apn_l:
apn_bytes += struct.pack("!B", len(word)) + word.encode()
return apn_bytes
def set_stream(client, stream):
sctp_default_send_param = bytearray(client.getsockopt(132,10,32))
sctp_default_send_param[0]= stream
client.setsockopt(132, 10, sctp_default_send_param)
return client
def return_key(kasme, algo, type): # 33.401 Annex A.7
if type == 'NAS-ENC':
type = '01'
elif type == 'NAS-INT':
type = '02'
algo = '0'+str(algo)
key = kasme
message = unhexlify('15'+type+'0001'+algo+'0001')
h = HMAC.new(key, msg=message, digestmod=SHA256)
return h.digest()[-16:]
def return_kasme(plmn, autn, ck, ik):
key = unhexlify(ck + ik)
sqn_xor_ak = autn[0:12]
message = unhexlify('10') + return_plmn(plmn) + unhexlify('0003' + sqn_xor_ak + '0006')
h = HMAC.new(key, msg=message, digestmod=SHA256)
return h.digest()[-32:]
def set_key(dic):
if dic['INT-ALG'] == 0:
dic['INT-KEY'] = None
elif dic['INT-ALG'] == 1:
dic['INT-KEY'] = dic['NAS-KEY-EIA1']
elif dic['INT-ALG'] == 2:
dic['INT-KEY'] = dic['NAS-KEY-EIA2']
elif dic['INT-ALG'] == 3:
dic['INT-KEY'] = dic['NAS-KEY-EIA3']
if dic['ENC-ALG'] == 0:
dic['ENC-KEY'] = None
elif dic['ENC-ALG'] == 1:
dic['ENC-KEY'] = dic['NAS-KEY-EEA1']
elif dic['ENC-ALG'] == 2:
dic['ENC-KEY'] = dic['NAS-KEY-EEA2']
elif dic['ENC-ALG'] == 3:
dic['ENC-KEY'] = dic['NAS-KEY-EEA3']
return dic
def nas_hash(dic):
if dic['DIR'] == 0:
return nas_hash_func(dic['NAS-ENC'], dic['UP-COUNT'], dic['DIR'], dic['INT-KEY'], dic['INT-ALG'])
else:
return nas_hash_func(dic['NAS-ENC'], dic['DOWN-COUNT'], dic['DIR'], dic['INT-KEY'], dic['INT-ALG'])
def nas_hash_func(nas, count, dir, key, algo):
sqn=bytes([count%256]) #last byte
if algo == 1:
return EIA1(key, count, 0, dir, sqn+nas)
elif algo ==2:
return EIA2(key, count, 0, dir, sqn+nas)
elif algo ==3:
return EIA3(key, count, 0, dir, sqn+nas)
else:
return b'\x00\x00\x00\x00'
def nas_hash_service_request(dic):
if dic['DIR'] == 0:
return nas_hash_service_request_func(dic['NAS-ENC'], dic['UP-COUNT'], dic['DIR'], dic['INT-KEY'], dic['INT-ALG'])
else:
return nas_hash_service_request_func(dic['NAS-ENC'], dic['DOWN-COUNT'], dic['DIR'], dic['INT-KEY'], dic['INT-ALG'])
def nas_hash_service_request_func(nas, count, dir, key, algo):
if algo == 1:
return EIA1(key, count, 0, dir, nas)
elif algo ==2:
return EIA2(key, count, 0, dir, nas)
elif algo ==3:
return EIA3(key, count, 0, dir, nas)
else:
return b'\x00\x00\x00\x00'
def nas_encrypt(dic):
if dic['DIR'] == 0:
return nas_encrypt_func(dic['NAS-ENC'], dic['UP-COUNT'], dic['DIR'], dic['ENC-KEY'], dic['ENC-ALG'])
else:
return nas_encrypt_func(dic['NAS-ENC'], dic['DOWN-COUNT'], dic['DIR'], dic['ENC-KEY'], dic['ENC-ALG'])
def nas_encrypt_func(nas, count, dir, key, algo):
if algo == 1:
return EEA1(key, count, 0, dir, nas)
elif algo ==2:
return EEA2(key, count, 0, dir, nas)
elif algo ==3:
return EEA3(key, count, 0, dir, nas)
else:
return nas
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
continue
return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16))), fields[0]
#abstraction functions
def milenage_res_ck_ik(ki, op, opc, rand):
print(ki, op, opc ,rand)
rand = unhexlify(rand)
if op == None:
op = 16*b'\x00' #dummy since we will set opc directly
m = Milenage(op)
m.set_opc(opc)
else:
m = Milenage(op)
res, ck, ik, ak = m.f2345(ki, rand)
return hexlify(res), hexlify(ck), hexlify(ik)
def return_imsi(serial_interface_or_reader_index):
try:
return read_imsi_2(serial_interface_or_reader_index)
except:
try:
return read_imsi(serial_interface_or_reader_index)
except:
try:
return get_imsi(serial_interface_or_reader_index)
except:
try:
return https_imsi(serial_interface_or_reader_index)
except:
return None
def return_res_ck_ik(serial_interface_or_reader_index, rand, autn):
try:
return read_res_ck_ik_2(serial_interface_or_reader_index, rand, autn)
except:
try:
return read_res_ck_ik(serial_interface_or_reader_index, rand, autn)
except:
try:
return get_res_ck_ik(serial_interface_or_reader_index, rand, autn)
except:
try:
return https_res_ck_ik(serial_interface_or_reader_index, rand, autn)
except:
return None, None, None
def get_imsi(serial_interface):
imsi = None
ser = serial.Serial(serial_interface,38400, timeout=0.5,xonxoff=True, rtscts=True, dsrdtr=True, exclusive =True)
CLI = []
CLI.append('AT+CIMI\r\n')
a = time.time()
for i in range(len(CLI)):
ser.write(CLI[i].encode())
buffer = ''
while "OK\r\n" not in buffer and "ERROR\r\n" not in buffer:
buffer += ser.read().decode("utf-8")
if time.time()-a > 0.5:
ser.write(CLI[i].encode())
a = time.time() +1
if i==0:
for m in buffer.split('\r\n'):
if len(m) == 15:
imsi = m
ser.close()
return imsi
def get_res_ck_ik(serial_interface, rand, autn):
res = None
ck = None
ik = None
ser = serial.Serial(serial_interface,38400, timeout=0.5,xonxoff=True, rtscts=True, dsrdtr=True, exclusive =True)
CLI = []
#CLI.append('AT+CRSM=178,12032,1,4,0\r\n')
CLI.append('AT+CSIM=14,"00A40000023F00"\r\n')
CLI.append('AT+CSIM=14,"00A40000022F00"\r\n')
CLI.append('AT+CSIM=42,"00A4040010A0000000871002FFFFFFFF8903050001"\r\n')
CLI.append('AT+CSIM=78,\"008800812210' + rand.upper() + '10' + autn.upper() + '\"\r\n')
a = time.time()
for i in CLI:
ser.write(i.encode())
buffer = ''
while "OK" not in buffer and "ERROR" not in buffer:
buffer += ser.read().decode("utf-8")
if time.time()-a > 0.5:
ser.write(i.encode())
a = time.time() + 1
for i in buffer.split('"'):
if len(i)==4:
if i[0:2] == '61':
len_result = i[-2:]
LAST_CLI = 'AT+CSIM=10,"00C00000' + len_result + '\"\r\n'
ser.write(LAST_CLI.encode())
buffer = ''
while "OK\r\n" not in buffer and "ERROR\r\n" not in buffer:
buffer += ser.read().decode("utf-8")
for result in buffer.split('"'):
if len(result) > 10:
res = result[4:20]
ck = result[22:54]
ik = result[56:88]
ser.close()
return res, ck, ik
#reader functions
def bcd_str(chars):
bcd_string = ""
for i in range(len(chars) // 2):
bcd_string += chars[1+2*i] + chars[2*i]
return bcd_string
def read_imsi(reader_index):
imsi = None
r = readers()
connection = r[int(reader_index)].createConnection()
connection.connect()
data, sw1, sw2 = connection.transmit(toBytes('00A40000023F00'))
data, sw1, sw2 = connection.transmit(toBytes('00A40000027F20'))
data, sw1, sw2 = connection.transmit(toBytes('00A40000026F07'))
data, sw1, sw2 = connection.transmit(toBytes('00B0000009'))
result = toHexString(data).replace(" ","")
imsi = bcd_str(result)[-15:]
return imsi
def read_res_ck_ik(reader_index, rand, autn):
res = None
ck = None
ik = None
r = readers()
connection = r[int(reader_index)].createConnection()
connection.connect()
data, sw1, sw2 = connection.transmit(toBytes('00A40000023F00'))
data, sw1, sw2 = connection.transmit(toBytes('00A40000022F00'))
data, sw1, sw2 = connection.transmit(toBytes('00A4040010A0000000871002FFFFFFFF8903050001'))
data, sw1, sw2 = connection.transmit(toBytes('008800812210' + rand.upper() + '10' + autn.upper()))
if sw1 == 97:
data, sw1, sw2 = connection.transmit(toBytes('00C00000') + [sw2])
result = toHexString(data).replace(" ", "")
res = result[4:20]
ck = result[22:54]
ik = result[56:88]
return res, ck, ik
#reader functions - more generic using card module
def read_imsi_2(reader_index): #prepared for AUTS
a = USIM(int(reader_index))
return a.get_imsi()
def read_res_ck_ik_2(reader_index,rand,autn):
a = USIM(int(reader_index))
x = a.authenticate(RAND=toBytes(rand), AUTN=toBytes(autn))
if len(x) == 1: #AUTS goes in RES position
return toHexString(x[0]).replace(" ", ""), None, None
elif len(x) > 2:
return toHexString(x[0]).replace(" ", ""),toHexString(x[1]).replace(" ", ""),toHexString(x[2]).replace(" ", "")
else:
return None, None, None
#https functions
def https_imsi(server):
r = requests.get('https://' + server + '/?type=imsi', verify=False)
return r.json()['imsi']
def https_res_ck_ik(server, rand, autn):
r = requests.get('https://' + server + '/?type=rand-autn&rand=' + rand + '&autn=' + autn, verify=False)
return r.json()['res'], r.json()['ck'], r.json()['ik']
######################################################################################################################################
######################################################################################################################################
#------------------------------------------------------------------------------------------------------------------------------------#
######################################################################################################################################
# NON UE RELATED PROCEDURES: #
######################################################################################################################################
def S1SetupRequest(dic):
IEs = []
IEs.append({'id': 59, 'value': ('Global-ENB-ID', {'pLMNidentity': dic['ENB-PLMN'], 'eNB-ID' : ('macroENB-ID', (dic['ENB-ID'], 20))}), 'criticality': 'reject'})
IEs.append({'id': 60, 'value': ('ENBname', dic['ENB-NAME']), 'criticality': 'ignore'})
if dic['S1-TYPE'] == "4G" :
IEs.append({'id': 64, 'value': ('SupportedTAs', [{'tAC': dic['ENB-TAC1'], 'broadcastPLMNs': [dic['ENB-PLMN']]}, {'tAC': dic['ENB-TAC2'], 'broadcastPLMNs': [dic['ENB-PLMN']]}]), 'criticality': 'reject'})
elif dic['S1-TYPE'] == "NBIOT":
IEs.append({'id': 64, 'value': ('SupportedTAs', [{'tAC': dic['ENB-TAC-NBIOT'], 'broadcastPLMNs': [dic['ENB-PLMN']], 'iE-Extensions': [{'id':232, 'criticality': 'reject', 'extensionValue':('RAT-Type','nbiot')}]}]), 'criticality': 'reject'})
elif dic['S1-TYPE'] == "BOTH":
IEs.append({'id': 64, 'value': ('SupportedTAs', [{'tAC': dic['ENB-TAC'], 'broadcastPLMNs': [dic['ENB-PLMN']]}, {'tAC': dic['ENB-TAC-NBIOT'], 'broadcastPLMNs': [dic['ENB-PLMN']], 'iE-Extensions': [{'id':232, 'criticality': 'reject', 'extensionValue':('RAT-Type','nbiot')}]}]), 'criticality': 'reject'})
IEs.append({'id': 137, 'value': ('PagingDRX', 'v128'), 'criticality': 'ignore'})
if dic['S1-TYPE'] == "NBIOT" or dic['S1-TYPE'] == "BOTH":
IEs.append({'id': 234, 'value': ('NB-IoT-DefaultPagingDRX', 'v256'), 'criticality': 'ignore'})
val = ('initiatingMessage', {'procedureCode': 17, 'value': ('S1SetupRequest', {'protocolIEs': IEs}), 'criticality': 'ignore'})
dic = eMENU.print_log(dic, "S1AP: sending S1SetupRequest")
return val
def S1SetupResponseProcessing(IEs, dic):
mme_name = ''
servedPLMNs = b''
servedGroupIDs = b''
servedMMECs = b''
RelativeMMECapacity = 0
for i in IEs:
if i['id'] == 61:
mme_name = i['value'][1]
elif i['id'] == 105:
servedPLMNs = i['value'][1][0]['servedPLMNs'][0]
servedGroupIDs = i['value'][1][0]['servedGroupIDs'][0]
servedMMECs = i['value'][1][0]['servedMMECs'][0]
elif i['id'] == 87:
RelativeMMECapacity = i['value'][1]
dic['MME-NAME'] = mme_name
dic['MME-PLMN'] = servedPLMNs
dic['MME-GROUP-ID'] = servedGroupIDs
dic['MME-CODE'] = servedMMECs
dic['MME-RELATIVE-CAPACITY'] = RelativeMMECapacity
dic['STATE'] = 1
return dic
# improve when MME supports more than on network
def MMEConfigurationUpdateAcknowledge(IEs, dic):
for i in IEs:
if i['id'] == 61:
mme_name = i['value'][1]
dic['MME-NAME'] = mme_name
elif i['id'] == 105:
servedPLMNs = i['value'][1][0]['servedPLMNs']
servedGroupIDs = i['value'][1][0]['servedGroupIDs']
servedMMECs = i['value'][1][0]['servedMMECs']
dic['MME-PLMN'] = servedPLMNs
dic['MME-GROUP-ID'] = servedGroupIDs
dic['MME-CODE'] = servedMMECs
elif i['id'] == 87:
RelativeMMECapacity = i['value'][1]
dic['MME-RELATIVE-CAPACITY'] = RelativeMMECapacity
answer = ('successfulOutcome', {'procedureCode': 30, 'value': ('MMEConfigurationUpdateAcknowledge', {'protocolIEs': []}), 'criticality': 'ignore'})
dic = eMENU.print_log(dic, "S1AP: sending MMEConfigurationUpdateAcknowledge")
return answer, dic
def Reset(dic):
#assumes only one session so no need to check MME-UE-S1AP-ID and ENB-UE-S1AP-ID
IEs = []
IEs.append({'id': 2, 'value': ('Cause', ('misc', 'om-intervention')), 'criticality': 'ignore'})
IEs.append({'id': 92, 'value': ('ResetType', ('s1-Interface', 'reset-all')), 'criticality': 'ignore'})
val = ('initiatingMessage', {'procedureCode': 14, 'value': ('Reset', {'protocolIEs': IEs}), 'criticality': 'ignore'})
dic = eMENU.print_log(dic, "S1AP: sending Reset")
return val
######################################################################################################################################
######################################################################################################################################
#------------------------------------------------------------------------------------------------------------------------------------#
######################################################################################################################################
# UE RELATED PROCEDURES: #
######################################################################################################################################
###############
# NAS Msg #
###############
def _nas_pco(pdp_type,pcscf_restoration):
if pdp_type == 1:
len_pco = struct.pack("!H", 32)
if pcscf_restoration == False:
return b'\x80\x80\x21\x1c\x01\x00\x00\x1c\x81\x06\x00\x00\x00\x00\x82\x06\x00\x00\x00\x00\x83\x06\x00\x00\x00\x00\x84\x06\x00\x00\x00\x00\x00\x0c\x00\x00\x0e\x00'
else:
return b'\x80\x80\x21\x1c\x01\x00\x00\x1c\x81\x06\x00\x00\x00\x00\x82\x06\x00\x00\x00\x00\x83\x06\x00\x00\x00\x00\x84\x06\x00\x00\x00\x00\x00\x0c\x00\x00\x12\x00\x00\x0e\x00'
elif pdp_type == 2:
len_pco = struct.pack("!H", 4)
if pcscf_restoration == False:
return b'\x80\x00\x03\x00\x00\x01\x00\x00\x0e\x00'
else:
return b'\x80\x00\x03\x00\x00\x01\x00\x00\x12\x00\x00\x0e\x00'
elif pdp_type == 3:
len_pco = struct.pack("!H", 33)
if pcscf_restoration == False:
return b'\x80\x80\x21\x1c\x01\x00\x00\x1c\x81\x06\x00\x00\x00\x00\x82\x06\x00\x00\x00\x00\x83\x06\x00\x00\x00\x00\x84\x06\x00\x00\x00\x00\x00\x03\x00\x00\x0c\x00\x00\x01\x00\x00\x0e\x00'
else:
return b'\x80\x80\x21\x1c\x01\x00\x00\x1c\x81\x06\x00\x00\x00\x00\x82\x06\x00\x00\x00\x00\x83\x06\x00\x00\x00\x00\x84\x06\x00\x00\x00\x00\x00\x03\x00\x00\x0c\x00\x00\x01\x00\x00\x12\x00\x00\x0e\x00'
#-------------------------------------------------------------------#
### ESM ### :
def nas_pdn_connectivity(eps_bearer_identity, pti, pdp_type, apn, pco, esm_information_transfer_flag, request_type=1):
esm_list = []
esm_list.append((2,eps_bearer_identity)) # protocol discriminator / eps bearer identity
esm_list.append((0,'V',bytes([pti]))) # procedure trnasaction identity
esm_list.append((0,'V',bytes([208]))) # message type: pdn connectivity request
esm_list.append((0,'V',bytes([(pdp_type<<4) + request_type])))
if esm_information_transfer_flag != None:
esm_list.append((0xD,'TV',esm_information_transfer_flag))
if apn != None:
esm_list.append((0x28,'TLV',apn))
if pco != None:
esm_list.append((0x27,'TLV',pco))
return eNAS.nas_encode(esm_list)
def nas_pdn_disconnect(eps_bearer_identity, pti, linked_eps_bearer_id, pco):
esm_list = []
esm_list.append((2,eps_bearer_identity)) # protocol discriminator / eps bearer identity
esm_list.append((0,'V',bytes([pti]))) # procedure trnasaction identity
esm_list.append((0,'V',bytes([210]))) # message type: pdn disconnectrequest
esm_list.append((0,'V',bytes([linked_eps_bearer_id]))) # pdn type / request type (ipv4, initial request)
if pco != None:
esm_list.append((0x27,'TLV',pco))
return eNAS.nas_encode(esm_list)
def nas_activate_default_eps_bearer_context_accept(eps_bearer_identity, pco):
esm_list = []
pti = 0
esm_list.append((2,eps_bearer_identity)) # protocol discriminator / eps bearer identity
esm_list.append((0,'V',bytes([pti]))) # procedure trnasaction identity
esm_list.append((0,'V',bytes([194]))) # message type: activate_default_eps_bearer_context_accept
if pco != None:
esm_list.append((0x27,'TLV',pco))
return eNAS.nas_encode(esm_list)
def nas_activate_dedicated_eps_bearer_context_accept(eps_bearer_identity, pco):
esm_list = []
pti = 0
esm_list.append((2,eps_bearer_identity)) # protocol discriminator / eps bearer identity
esm_list.append((0,'V',bytes([pti]))) # procedure trnasaction identity
esm_list.append((0,'V',bytes([198]))) # message type: activate_dedicated_eps_bearer_context_accept
if pco != None:
esm_list.append((0x27,'TLV',pco))
return eNAS.nas_encode(esm_list)
def nas_modify_eps_bearer_context_accept(eps_bearer_identity, pco):
esm_list = []
pti = 0
esm_list.append((2,eps_bearer_identity)) # protocol discriminator / eps bearer identity
esm_list.append((0,'V',bytes([pti]))) # procedure trnasaction identity
esm_list.append((0,'V',bytes([202]))) # message type: activate_dedicated_eps_bearer_context_accept
if pco != None:
esm_list.append((0x27,'TLV',pco))
return eNAS.nas_encode(esm_list)
def nas_esm_information_response(eps_bearer_identity, pti, apn, pco):
esm_list = []
esm_list.append((2,eps_bearer_identity)) # protocol discriminator / eps bearer identity
esm_list.append((0,'V',bytes([pti]))) # procedure trnasaction identity
esm_list.append((0,'V',bytes([218]))) # message type: eesm information response
if apn != None:
esm_list.append((0x28,'TLV',apn))
if pco != None:
esm_list.append((0x27,'TLV',pco))
return eNAS.nas_encode(esm_list)
def nas_deactivate_eps_bearer_context_accept(eps_bearer_identity, pti, pco):
esm_list = []
esm_list.append((2,eps_bearer_identity)) # protocol discriminator / eps bearer identity
esm_list.append((0,'V',bytes([pti]))) # procedure trnasaction identity
esm_list.append((0,'V',bytes([206]))) # message type: deactivate eps bearer context accept
if pco != None:
esm_list.append((0x27,'TLV',pco))
return eNAS.nas_encode(esm_list)
def nas_esm_data_transport(eps_bearer_identity, pti, user_data_container):
esm_list = []
esm_list.append((2,eps_bearer_identity)) # protocol discriminator / eps bearer identity
esm_list.append((0,'V',bytes([pti]))) # procedure trnasaction identity
esm_list.append((0,'V',bytes([235]))) # message type: esm data transport
esm_list.append((0,'LV-E',user_data_container))
return eNAS.nas_encode(esm_list)
#-------------------------------------------------------------#
### EMM ### :
def nas_attach_request(type, esm_information_transfer_flag, eps_identity, pdp_type, attach_type, tmsi, lai, sms_update, pcscf_restoration, pdn_request_type, ksi=0):
emm_list = []
emm_list.append((7,0)) # protocol discriminator /
emm_list.append((0,'V',bytes([65]))) # message type: attach request
emm_list.append((0,'V',bytes([(ksi<<4) + attach_type]))) # eps attach type/ nas key set identifier (EPS Attach /Keyset 0)
emm_list.append((0,'LV',eps_identity)) # eps mobile identity (imsi/odd number:9) + imsi. all in bcd)
if type[0] == "4G":
emm_list.append((0,'LV',unhexlify('f0f0c04009')))
elif type[0] == "NBIOT":
emm_list.append((0,'LV',unhexlify('f0f0000008a4')))
elif type[0] == "5G":
emm_list.append((0,'LV',unhexlify('f0f0c0c0000010')))
pco = nas_pco(pdp_type,pcscf_restoration)
if attach_type == 6: #EPS Emergency Attach
emm_list.append((0,'LV-E',nas_pdn_connectivity(0,1,pdp_type,None,pco,esm_information_transfer_flag,4)))
else:
emm_list.append((0,'LV-E',nas_pdn_connectivity(0,1,pdp_type,None,pco,True, pdn_request_type)))
if type[0] == "4G":
if attach_type == 2 and lai != None:
emm_list.append((0x13, 'TV', lai))
if attach_type == 2 and tmsi == None:
emm_list.append((0x9, 'TV', 0))
if sms_update == True:
emm_list.append((0xF, 'TV', 1))
emm_list.append((0xC, 'TV', 1))
if attach_type == 2 and tmsi != None:
emm_list.append((0x10, 'TLV', tmsi[-3:-2] + bytes([(tmsi[-2]//64)*64])))
if type[1] == "PSM" or type[1] == "BOTH":
emm_list.append((0x6A, 'TLV', b'\x0f')) # 15*2=30 sec.
emm_list.append((0x5E, 'TLV', b'\x41'))
if type[1] == "EDRX" or type[1] == "BOTH":
emm_list.append((0x6E, 'TLV', b'\x75'))
elif type[0] == "NBIOT":
if attach_type == 2 and lai != None:
emm_list.append((0x13, 'TV', lai))
if attach_type == 2 and tmsi == None:
emm_list.append((0x9, 'TV', 0))
if sms_update == True:
emm_list.append((0xF, 'TV', 5))
else:
emm_list.append((0xF, 'TV', 4))
emm_list.append((0xC, 'TV', 1))
if attach_type == 2 and tmsi != None:
emm_list.append((0x10, 'TLV', tmsi[-3:-2] + bytes([(tmsi[-2]//64)*64])))
if type[1] == "PSM" or type[1] == "BOTH":
emm_list.append((0x6A, 'TLV', b'\x0f')) # 15*2=30 sec.
emm_list.append((0x5E, 'TLV', b'\x41'))
if type[1] == "EDRX" or type[1] == "BOTH":
emm_list.append((0x6E, 'TLV', b'\x75'))
elif type[0] == "5G":
if attach_type == 2 and lai != None:
emm_list.append((0x13, 'TV', lai))
if attach_type == 2 and tmsi == None:
emm_list.append((0x9, 'TV', 0))
if sms_update == True:
emm_list.append((0xF, 'TV', 1))
if attach_type == 2 and tmsi != None:
emm_list.append((0x10, 'TLV', tmsi[-3:-2] + bytes([(tmsi[-2]//64)*64])))
emm_list.append((0x6F, 'TLV', b'\xf0\x00\xf0\x00'))
return eNAS.nas_encode(emm_list)
def nas_tracking_area_update_request(ksi, eps_update_type, eps_identity, type, tmsi, lai, sms_update):
emm_list = []
emm_list.append((7,0)) # protocol discriminator /
emm_list.append((0,'V',bytes([72]))) # message type: tracking area update request
emm_list.append((0,'V',bytes([(ksi<<4) + eps_update_type]))) # ksi=6, update type: TA
emm_list.append((0,'LV',eps_identity)) # eps mobile identity (imsi/odd number:9) + imsi. all in bcd)
if type[0] == "4G":
emm_list.append((0x58,'TLV',unhexlify('f0f0c04009')))
if eps_update_type > 0 and lai != None:
emm_list.append((0x13, 'TV', lai))
if eps_update_type > 0 and tmsi == None:
emm_list.append((0x9, 'TV', 0))
if sms_update == True:
emm_list.append((0xF, 'TV', 1))
emm_list.append((0xC, 'TV', 1))
if eps_update_type > 0 and tmsi != None:
emm_list.append((0x10, 'TLV', tmsi[-3:-2] + bytes([(tmsi[-2]//64)*64])))
if type[1] == "PSM" or type[1] == "BOTH":
emm_list.append((0x6A, 'TLV', b'\x05'))
emm_list.append((0x5E, 'TLV', b'\x41'))
if type[1] == "EDRX" or type[1] == "BOTH":
emm_list.append((0x6E, 'TLV', b'\x75'))
elif type[0] == "NBIOT":
emm_list.append((0x58,'TLV',unhexlify('f0f0000008a4')))
elif type[0] == "5G":
emm_list.append((0x58,'TLV',unhexlify('f0f0c0c0000010')))
if type[0] == "NBIOT":
if eps_update_type > 0 and lai != None:
emm_list.append((0x13, 'TV', lai))
if eps_update_type > 0 and tmsi == None:
emm_list.append((0x9, 'TV', 0))
if sms_update == True:
emm_list.append((0xF, 'TV', 5))
else:
emm_list.append((0xF, 'TV', 4))
emm_list.append((0xC, 'TV', 1))
if eps_update_type > 0 and tmsi != None:
emm_list.append((0x10, 'TLV', tmsi[-3:-2] + bytes([(tmsi[-2]//64)*64])))
if type[1] == "PSM" or type[1] == "BOTH":
emm_list.append((0x6A, 'TLV', b'\x05'))
emm_list.append((0x5E, 'TLV', b'\x41'))
if type[1] == "EDRX" or type[1] == "BOTH":
emm_list.append((0x6E, 'TLV', b'\x75'))
elif type[0] == "5G":
if eps_update_type > 0 and lai != None:
emm_list.append((0x13, 'TV', lai))
if eps_update_type > 0 and tmsi == None:
emm_list.append((0x9, 'TV', 0))
if sms_update == True:
emm_list.append((0xF, 'TV', 1))
if eps_update_type > 0 and tmsi != None:
emm_list.append((0x10, 'TLV', tmsi[-3:-2] + bytes([(tmsi[-2]//64)*64])))
emm_list.append((0x6F, 'TLV', b'\xf0\x00\xf0\x00'))
return eNAS.nas_encode(emm_list)
def nas_extended_service_request(ksi, mobile_identity):
emm_list = []
emm_list.append((7,0)) # protocol discriminator /
emm_list.append((0,'V',bytes([76]))) # message type: extende service request
emm_list.append((0,'V',bytes([(ksi<<4) + 1]))) #mobile terminating cs fallback
emm_list.append((0,'LV',b'\xf4' + mobile_identity))
emm_list.append((0xB,'TV',1))
return eNAS.nas_encode(emm_list)
def nas_detach_request(ksi, detach_type, eps_identity):
emm_list = []
emm_list.append((7,0)) # protocol discriminator /
emm_list.append((0,'V',bytes([69]))) # message type: detach request
emm_list.append((0,'V',bytes([(ksi<<4) + detach_type]))) # ksi=6, update type: TA
emm_list.append((0,'LV',eps_identity)) # eps mobile identity (imsi/odd number:9) + imsi. all in bcd)
return eNAS.nas_encode(emm_list)
def nas_authentication_response(xres):
emm_list = []
emm_list.append((7,0)) # protocol discriminator /
emm_list.append((0,'V',bytes([83]))) # message type: authentication response
emm_list.append((0,'LV',xres))
return eNAS.nas_encode(emm_list)
def nas_identity_response(imsi_or_imeisv):
emm_list = []
emm_list.append((7,0)) # protocol discriminator /
emm_list.append((0,'V',bytes([86]))) # message type: identity response
emm_list.append((0,'LV',bcd(imsi_or_imeisv ))) # eps mobile identity (imsi/odd number:9) + imsi. all in bcd)
return eNAS.nas_encode(emm_list)