-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathgtp_dialer.py
executable file
·2026 lines (1618 loc) · 94.4 KB
/
gtp_dialer.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
'''
Example:
python3 gtp_dialer.py -d 10.10.1.1 -a internet -g 172.16.62.2 -s 10.15.8.1 -n SGW -t GTPv2
python3 gtp_dialer.py -d 10.10.1.2 -a internet -g 172.16.62.2 -s 10.15.8.1 -G 1.2.3.4 -n MME -t GTPv2 -f 10.128.1.2 -u testes@apnxpto -w paswordxpto
'''
import sys
if sys.platform != "linux" and sys.platform != "linux2":
print("Operating system not supported. Exiting.\n")
exit(1)
import fcntl
import os
import struct
import socket
import subprocess
import random
import select
import signal
import hashlib
import binascii
import time
from threading import Thread
from optparse import OptionParser
GTP_LOCAL_HOST = ''
GTP_C_LOCAL_PORT = 2123
GTP_C_REMOTE_PORT = 2123
GTP_U_LOCAL_PORT = 2152
GTP_U_REMOTE_PORT = 2152
DEFAULT_IMSI = '123456789012345'
DEFAULT_MSISDN = '1234567890'
DEFAULT_IMEI = '1234567812345678'
DEFAULT_OPERATOR = '12345'
DEFAULT_APN = 'internet'
DEFAULT_NSAPI = 5
HASH_PASS = '123456qwertyasdfghzxcvbn'
DHCP_CLIENT_NAME = 'GTP Dialer'
ie_size = { 1:1, 2:8, 3:6, 4:4, 5:4, 8:1, 9:28, 11:1, 12:3, 13:1, 14:1, 15:1, 16:4, 17:4, 18:5, 19:1, 20:1, 21:1, 22:9, 23:1, 24:1, 25:2, 26:2, 27:2, 28:2, 29:1, 127:4 }
class bcolors:
BLUE = '\u001b[34m'
YELLOW = '\u001b[33m'
GREEN = '\u001b[32m'
RED = '\u001b[31m'
ENDC = '\033[0m'
BOLD = '\033[1m'
BACKGROUNDBLACK = '\u001b[40m'
def bytes2hex(byteArray):
return ''.join(hex(i).replace("0x", "0x0")[-2:] for i in byteArray)
def hex2bytes(hexString):
return bytearray.fromhex(hexString)
def mac2str(mac):
mac_hex = bytes2hex(mac)
mac_str = ''
for i in range(0,len(mac_hex),2):
mac_str += mac_hex[i:i+2] + ':'
return mac_str[:-1]
def str2bytes(word):
str_bytes = word.encode()
return str_bytes
def bytes_to_int(b):
return int(binascii.hexlify(b),16)
def int_to_bytes(i):
return struct.pack("!I",i)
def checksum_carry_around_add(a,b):
c = bytes_to_int(a) + bytes_to_int(b)
c = int_to_bytes(c)
r = (bytes_to_int(c) & bytes_to_int(b'\x00\x00\xFF\xFF')) + (bytes_to_int(c) >> 16)
r = int_to_bytes(r)
return r
def checksum(msg):
s = b'\x00\x00'
#padding
if len(msg) % 2 !=0:
msg += b'\x00'
for i in range(0, len(msg), 2):
w = struct.pack("!BB",int(msg[i]), int(msg[i+1]))
s = checksum_carry_around_add(s,w)
r = int_to_bytes(~bytes_to_int(s) & bytes_to_int(b'\x00\x00\xFF\xFF'))
#print("checksum: " + str(r[2:]))
return r[2:]
def dhcp_option(id, size, value):
return struct.pack("!B", id) + struct.pack("!B", size) + value
def dhcp_request_packet(dhcp_type, xid, mac, ip):
op = b'\x01' # Boot Request
htype = b'\x01' # Ethernet
hlen = b'\x06' # 6 bytes (MAC addr)
hops = b'\x00' # 0 hop (hop > 1 when DHCP Relay)
#xid = b'\x00\x00\x00\x00' # Transaction ID, a random number chosen by the client, used by the client and server to associate messages and responses between a client and a server.
secs = b'\x00\x00' # Filled in by client, seconds elapsed since client began address acquisition or renewal process
flags = b'\x00\x00' # Unicast
ciaddr = str2ip("0.0.0.0") # Client IP address; only filled in if client is in BOUND, RENEW or REBINDING state and can respond to ARP requests.
yiaddr = str2ip("0.0.0.0") # 'your' (client) IP address 0.0.0.0 in requests
siaddr = str2ip("0.0.0.0") # IP address of next server to use in bootstrap; returned in DHCPOFFER, DHCPACK by server.
giaddr = str2ip("0.0.0.0") # Relay agent IP address, used in booting via a relay agent.
chaddr = mac + bytes(10) # Client hardware address (16 bytes)
sname = bytes(64) # Optional server host name, null terminated string. (64 bytes)
file = bytes(128) # Boot file name, null terminated string; "generic" name or null in DHCPDISCOVER, fully qualified directory-path name in DHCPOFFER. (128 bytes)
magic = b'\x63\x82\x53\x63' # RFC 951
opt_dhcp_type = dhcp_option(53,1, struct.pack("!B", dhcp_type))
opt_dhcp_client_identifier = dhcp_option(61,7, b'\x01' + mac)
opt_dhcp_hostname = dhcp_option(12,len(DHCP_CLIENT_NAME)+17, str2bytes(DHCP_CLIENT_NAME + mac2str(mac)))
if ip == '':
opt_ip = ''
else:
opt_ip = dhcp_option(50,4, ip)
opt_dhcp_parameter_request_list = dhcp_option(55,9, b'\x01\x21\x03\x06\x0f\x1c\x33\x3a\x3b')
opt_dhcp_end = b'\xff'
p = op + htype + hlen + hops + xid + secs + flags
p = p + ciaddr + yiaddr + siaddr + giaddr + chaddr + sname + file + magic
p = p + opt_dhcp_type
p = p + opt_dhcp_client_identifier
p = p + opt_dhcp_hostname
if opt_ip != '':
p = p + opt_ip
p = p + opt_dhcp_parameter_request_list
p = p + opt_dhcp_end
return p
def dhcp_decode(dhcp_packet):
dhcp_param = dict()
dhcp_param["op"] = dhcp_packet[0:1]
dhcp_param["htype"] = dhcp_packet[1:2]
dhcp_param["hlen"] = dhcp_packet[2:3]
dhcp_param["hops"] = dhcp_packet[3:4]
dhcp_param["xid"] = dhcp_packet[4:8]
dhcp_param["secs"] = dhcp_packet[8:10]
dhcp_param["flags"] = dhcp_packet[10:12]
dhcp_param["ciaddr"] = dhcp_packet[12:16]
dhcp_param["yiaddr"] = dhcp_packet[16:20]
dhcp_param["siaddr"] = dhcp_packet[20:24]
dhcp_param["giaddr"] = dhcp_packet[24:28]
dhcp_param["chaddr"] = dhcp_packet[28:34]
dhcp_param["sname"] = dhcp_packet[44:108]
dhcp_param["file"] = dhcp_packet[108:236]
dhcp_param["magic"] = dhcp_packet[236:240]
pointer = 240
while pointer < len(dhcp_packet):
if dhcp_packet[pointer:pointer+1] == b'\xff':
break
else:
t = struct.unpack('!B', dhcp_packet[pointer:pointer+1])[0]
l = struct.unpack('!B', dhcp_packet[pointer+1:pointer+2])[0]
dhcp_param[str(t)] = dhcp_packet[pointer+2:pointer+2+l]
pointer = pointer + 2 + l
return dhcp_param
def udp_header(scr_port, dst_port, payload_length):
udp_src_port = struct.pack("!H", scr_port)
udp_dst_port = struct.pack("!H", dst_port)
udp_length = struct.pack("!H", payload_length + 8) #add UDP 8 byte header
udp_checksum = struct.pack("!H", 0)
return udp_src_port + udp_dst_port + udp_length + udp_checksum
def ip_header_with_length(source_address, destination_address, protocol, calc_checksum, payload_length):
ip_version_and_header_length = b'\x45'
ip_dscp = b'\x00'
ip_total_length = struct.pack("!H", 20 + payload_length)
#ip_total_length = b'\x00\x00'
ip_identification = struct.pack("!H", 0)
ip_flags_and_fragment_offset = b'\x40\x00'
ip_ttl = struct.pack("!B", 64)
ip_protocol = struct.pack("!B", protocol)
ip_header_checksum = b'\x00\x00'
ip_source_addr = str2ip(source_address)
ip_destination_addr = str2ip(destination_address)
h_begin = ip_version_and_header_length + ip_dscp + ip_total_length + ip_identification + ip_flags_and_fragment_offset + ip_ttl + ip_protocol
h_end = ip_source_addr + ip_destination_addr
if calc_checksum == 1:
ip_header_checksum = checksum(h_begin + ip_header_checksum + h_end)
return h_begin + ip_header_checksum + h_end
def ip2str(ip_bytes):
return socket.inet_ntop(socket.AF_INET,ip_bytes)
def str2ip(ip_str):
return socket.inet_aton(ip_str)
def gtp_u_header(teid, length):
gtp_flags = b'\x30'
gtp_message_type = b'\xff'
gtp_length = struct.pack("!H", length)
gtp_teid = struct.pack("!I", teid)
return gtp_flags + gtp_message_type + gtp_length + gtp_teid
def open_tun(n):
TUNSETIFF = 0x400454ca
IFF_TUN = 0x0001
IFF_TAP = 0x0002
IFF_NO_PI = 0x1000 # No Packet Information - to avoid 4 extra bytes
TUNMODE = IFF_TUN | IFF_NO_PI
MODE = 0
DEBUG = 0
if sys.platform == "linux" or sys.platform == "linux2":
f = os.open("/dev/net/tun", os.O_RDWR)
ifs = fcntl.ioctl(f, TUNSETIFF, struct.pack("16sH", bytes("tun%d" % n, "utf-8"), TUNMODE))
#ifname = ifs[:16].strip("\x00")
subprocess.call("ifconfig tun%d up" % n, shell=True)
return f
def bcd(chars):
bcd_string = ""
for i in range(len(chars) // 2):
bcd_string += chars[1+2*i] + chars[2*i]
bcd_bytes = bytearray.fromhex(bcd_string)
return bcd_bytes
###### GTPv1 ######
def add_imsi(imsi):
if len(imsi) % 2 == 1:
imsi += "f"
imsi = bcd(imsi)
return b'\x02' + imsi
def add_selection_mode(sel_mode):
return b'\x0f' + bytes([(252+int(sel_mode)) % 256])
def add_random_teid(teid_type):
global teid_local_control, teid_local_data
rand_number = random.randrange(pow(2,32)-1)
if teid_type == "data":
teid_local_data = rand_number
return b'\x10' + struct.pack("!L", rand_number)
elif teid_type == "control":
teid_local_control = rand_number
return b'\x11' + struct.pack("!L", rand_number)
def add_nsapi(value):
return b'\x14' + struct.pack("!B", value % 256)
def add_eua_ipv4():
return b'\x80\x00\x02\xf1\x21'
def add_eua_ipv6():
return b'\x80\x00\x02\xf1\x57'
def add_eua_ipv4v6():
return b'\x80\x00\x02\xf1\x8d'
def add_apn(apn):
apn_bytes = bytes()
apn_list = apn.split(".")
for word in apn_list:
apn_bytes += struct.pack("!B", len(word)) + word.encode()
return b'\x83\x00' + struct.pack("!B",len(apn_bytes)) + apn_bytes
def add_gsn_address(address):
return b'\x85\x00\x04' + str2ip(address)
def add_msisdn(msisdn):
if len(msisdn) % 2 == 1:
msisdn += "f"
msisdn = bcd(msisdn)
return b'\x86' + struct.pack("!H", len(msisdn) + 1) + b'\x91' + msisdn
def return_random_bytes(size):
if size == 0: return b''
if size == 4: return struct.pack('!I', random.randrange(pow(2,32)-1))
if size == 8: return struct.pack('!Q', random.randrange(pow(2,64)-1))
if size == 16: return struct.pack('!Q', random.randrange(pow(2,64)-1)) + struct.pack('!Q', random.randrange(pow(2,64)-1))
def add_pco(pdptype, username, password, dhcp_flag, authentication_type):
len_pco = 0
pap = b''
chap = b''
dhcp = b''
if username != None and password != None:
if authentication_type == 'PAP':
len_username = struct.pack("!B", len(username))
username = username.encode()
len_password = struct.pack("!B", len(password))
password = password.encode()
len_pap_2B = struct.pack("!H", len(username)+len(password) + 6)
len_pap_1B = struct.pack("!B", len(username)+len(password) + 6)
len_pco = len(username)+len(password) + 6 + 3
pap = b'\xc0\x23' + len_pap_1B + b'\x01\x01' + len_pap_2B + len_username + username + len_password + password
chap = b''
elif authentication_type == 'CHAP':
value = return_random_bytes(16)
name = b'GTP Dialer'
length = struct.pack("!H", len(value) + len(name) + 5)
chap_challenge = b'\xc2\x23' + length[-1:] + b'\x01\x01' + length + b'\x10' + value + name
username = username.encode()
password = password.encode()
m = hashlib.md5()
m.update(b'\x01' + password + value)
hash = m.digest()
length = struct.pack("!H", len(hash) + len(username) + 5)
chap_response = b'\xc2\x23' + length[-1:] + b'\x02\x01' + length + b'\x10' + hash + username
chap = chap_challenge + chap_response
len_pco = len(chap)
pap = b''
if dhcp_flag == True:
dhcp = b'\x00\x0b\x00'
len_pco += 3
if pdptype == "ipv4":
len_pco = struct.pack("!H", 35 + len_pco)
return b'\x84' + len_pco + 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' + pap + chap + dhcp
elif pdptype == "ipv6":
len_pco = struct.pack("!H", 7 + len_pco)
return b'\x84' + len_pco + b'\x80\x00\x03\x00\x00\x01\x00' + pap + chap + dhcp
elif pdptype == "ipv4v6":
len_pco = struct.pack("!H", 41 + len_pco)
return b'\x84' + len_pco + 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' + pap + chap + dhcp
def add_qos():
# quick version. requests 70Mbits DL and 5.8Mbits UL
return b'\x87\x00\x0f\x01\x23\x43\x1f\x73\x96\xd2\xfe\x74\x83\xff\xff\x00\x80\x00'
def add_rat(rat):
return b'\x97\x00\x01' + bytes([rat])
def add_common_flags():
return b'\x94\x00\x01\x80'
def add_imei(imei):
if len(imei) % 2 == 1:
imei += "f"
imei = bcd(imei)
return b'\x9a' + struct.pack("!H", len(imei)) + imei
def add_private_extension(identifier, value, value2):
if identifier == 0:
value_bytes = b'\x7a\x57\x00'
value_bytes += value.encode()
elif identifier == 1:
m = hashlib.md5()
n = hashlib.sha1()
m.update((value + HASH_PASS).encode())
m_digest_password = m.digest()
n.update(m_digest_password + HASH_PASS.encode() + value2) #value2 == TEID Control
value_bytes = b'\x7a\x57\x01'
value_bytes += n.digest()
elif identifier == 2:
value_bytes = b'\x7a\x57\x02'
value_bytes += socket.inet_aton(value)
return b'\xff\x00' + struct.pack("!B",len(value_bytes)) + value_bytes
### GTPv1 messages ###
def cpc_request(apn, gtp_address, imsi, msisdn, pdptype, username, password, ggsn, username_pco, password_pco, dhcp, cc, operator, imei, authentication_type, rat, sel_mode):
global sequence_number
gtp_flags = b'\x32'
gtp_message_type = b'\x10'
gtp_length = b'\x00\x00' #length = 0. filled in the end
gtp_teid = b'\x00\x00\x00\x00'
gtp_sequence_number = struct.pack("!H", sequence_number)
gtp_n_pdu = b'\x00'
gtp_next_extension_header = b'\x00'
gtp_header = gtp_flags + gtp_message_type + gtp_length + gtp_teid + gtp_sequence_number + gtp_n_pdu + gtp_next_extension_header
gtp_imsi = add_imsi(imsi)
gtp_routing_area_identity = add_routing_area_identity(operator)
gtp_selection_mode = add_selection_mode(sel_mode)
gtp_teid_local_data = add_random_teid("data")
gtp_teid_local_control = add_random_teid("control")
gtp_nsapi = add_nsapi(DEFAULT_NSAPI)
gtp_cc = b'\x1a' + hex2bytes(cc)
if pdptype == "ipv4":
gtp_end_user_address = add_eua_ipv4()
elif pdptype == "ipv6":
gtp_end_user_address = add_eua_ipv6()
elif pdptype == "ipv4v6":
gtp_end_user_address = add_eua_ipv4v6()
gtp_apn = add_apn(apn)
gtp_pco = add_pco(pdptype, username_pco, password_pco, dhcp, authentication_type)
gtp_gsn_address = add_gsn_address(gtp_address)
gtp_msisdn = add_msisdn(msisdn)
gtp_qos = add_qos()
gtp_common_flags = add_common_flags()
if rat is None:
gtp_rat = add_rat(1)
else:
gtp_rat = add_rat(int(rat))
gtp_imei = add_imei(imei)
gtp_ie = gtp_imsi + gtp_routing_area_identity + gtp_selection_mode + gtp_teid_local_data + gtp_teid_local_control + gtp_nsapi + gtp_cc + gtp_end_user_address + gtp_apn + gtp_pco + gtp_gsn_address + gtp_gsn_address + gtp_msisdn + gtp_qos + gtp_common_flags + gtp_rat + gtp_imei
if username is not None and password is not None:
gtp_pe1 = add_private_extension(0, username,None)
gtp_pe2 = add_private_extension(1, password, gtp_teid_local_control[1:])
gtp_ie += gtp_pe1 + gtp_pe2
if ggsn is not None:
gtp_pe3 = add_private_extension(2, ggsn, None)
gtp_ie += gtp_pe3
cpc_packet = bytearray(gtp_header + gtp_ie)
length = len(cpc_packet) - 8
cpc_packet[3] = length % 256
cpc_packet[2] = length // 256
sequence_number +=1
return cpc_packet
def dpc_request(teid):
global sequence_number
gtp_flags = b'\x32'
gtp_message_type = b'\x14'
gtp_length = b'\x00\x08'
gtp_teid = struct.pack("!L", teid)
gtp_sequence_number = struct.pack("!H", sequence_number)
gtp_n_pdu = b'\x00'
gtp_next_extension_header = b'\x00'
gtp_teardown_nsapi = b'\x13\xff\x14' + bytes([DEFAULT_NSAPI])
gtp_header = gtp_flags + gtp_message_type + gtp_length + gtp_teid + gtp_sequence_number + gtp_n_pdu + gtp_next_extension_header
sequence_number +=1
return gtp_header + gtp_teardown_nsapi
def dpc_response(teid, request_seq_num):
gtp_flags = b'\x32'
gtp_message_type = b'\x15'
gtp_length = b'\x00\x06'
gtp_teid = struct.pack("!L", teid)
gtp_sequence_number = request_seq_num
gtp_n_pdu = b'\x00'
gtp_next_extension_header = b'\x00'
gtp_header = gtp_flags + gtp_message_type + gtp_length + gtp_teid + gtp_sequence_number + gtp_n_pdu + gtp_next_extension_header
gtp_cause = b'\x01\x80'
return gtp_header + gtp_cause
def upc_response(teid, request_seq_num, qos):
gtp_flags = b'\x32'
gtp_message_type = b'\x13'
gtp_length = b'\x00\x00'
gtp_teid = struct.pack("!L", teid)
gtp_sequence_number = request_seq_num
gtp_n_pdu = b'\x00'
gtp_next_extension_header = b'\x00'
gtp_header = gtp_flags + gtp_message_type + gtp_length + gtp_teid + gtp_sequence_number + gtp_n_pdu + gtp_next_extension_header
gtp_cause = b'\x01\x80'
upc_packet = bytearray(gtp_header + gtp_cause)
if qos != None:
gtp_qos = b'\x87' + struct.pack("!H",len(qos)) + qos
upc_packet += bytearray(gtp_qos)
length = len(upc_packet) - 8
upc_packet[3] = length % 256
upc_packet[2] = length // 256
return upc_packet
# Version not ready for extension headers. Validates TEID and cause=Requested Accepted in case of answer messages
# Uses a dictionary. Index is the IE, value are the data bytes. Length bytes (when they do exist) are discarted
def decode_gtpc(gtp_packet):
global request_sequence_number
valid = 0
if int(gtp_packet[0]) // 16 == 3 and gtp_packet[4:8] == struct.pack("!L", teid_local_control) and int(gtp_packet[1]) % 2 == 1: #Response and Cause =128,129,130
if int(gtp_packet[0]) % 16 == 0 and (gtp_packet[8:10] == b'\x01\x80' or gtp_packet[8:10] == b'\x01\x81' or gtp_packet[8:10] == b'\x01\x82'):
pointer = 8
valid = 1
elif int(gtp_packet[0:1]) % 16 < 4 and (gtp_packet[12:14] == b'\x01\x80' or gtp_packet[12:14] == b'\x01\x81' or gtp_packet[12:14] == b'\x01\x82'):
pointer = 12
valid = 1
# Proxy specific: if returned error is 240 - it means authentication is needed
elif (int(gtp_packet[0]) % 16 == 0 and gtp_packet[8:10] == b'\x01\xF0') or (int(gtp_packet[0]) % 16 < 4 and gtp_packet[12:14] == b'\x01\xF0'):
return 240
# Proxy specific: if returned error is 239 - it means authentication is wrong
elif (int(gtp_packet[0]) % 16 == 0 and gtp_packet[8:10] == b'\x01\xef') or (int(gtp_packet[0]) % 16 < 4 and gtp_packet[12:14] == b'\x01\xef'):
return 239
elif int(gtp_packet[0]) // 16 == 3 and gtp_packet[4:8] == struct.pack("!L", teid_local_control) and int(gtp_packet[1]) % 2 == 0: #Requests
if int(gtp_packet[0]) % 16 == 0:
pointer = 8
valid = 1
request_sequence_number = None
elif int(gtp_packet[0]) % 16 < 4:
pointer = 12
valid = 1
if int(gtp_packet[0]) % 16 > 1:
request_sequence_number = gtp_packet[8:10]
if valid == 1:
decode_dict = {}
while pointer < len(gtp_packet):
if gtp_packet[pointer] < 128:
decode_dict[gtp_packet[pointer]] = gtp_packet[pointer+1:pointer+1+ie_size[gtp_packet[pointer]]]
pointer += 1+ie_size[gtp_packet[pointer]]
else:
length = 256 * gtp_packet[pointer + 1] + gtp_packet[pointer + 2]
if gtp_packet[pointer] == 133:
# 133 is the first GSN (control) and 1133 is the second GSN (user plane)
if 133 in decode_dict:
decode_dict[1133] = gtp_packet[pointer+3:pointer+3+length]
else:
decode_dict[gtp_packet[pointer]] = gtp_packet[pointer+3:pointer+3+length]
else:
decode_dict[gtp_packet[pointer]] = gtp_packet[pointer+3:pointer+3+length]
pointer += 3 + length
return decode_dict
else:
return None
####### Endof GTPv1 #######
###############################################################################################################################################################
####### GTPv2 ##########
def decode_gtpc_v2(gtp_packet):
global request_sequence_number
valid = 0
if int(gtp_packet[0]) // 16 == 4 and gtp_packet[4:8] == struct.pack("!L", teid_local_control) and int(gtp_packet[1]) % 2 == 1: #Response and Cause =128,129,130
if (gtp_packet[16:17] == b'\x10' or gtp_packet[16:17] == b'\x11' or gtp_packet[16:17] == b'\x12' or gtp_packet[16:17] == b'\x13'):
pointer = 12
valid = 1
else:
return -1
elif int(gtp_packet[0]) // 16 == 4 and gtp_packet[4:8] == struct.pack("!L", teid_local_control) and int(gtp_packet[1]) % 2 == 0: #Requests
pointer = 12
valid = 1
request_sequence_number = gtp_packet[8:11]
if valid == 1:
decode_dict = {}
while pointer < len(gtp_packet):
type = gtp_packet[pointer]
instance = gtp_packet[pointer + 3]
length = 256 * gtp_packet[pointer + 1] + gtp_packet[pointer + 2]
decode_dict[(type,instance)]= gtp_packet[pointer+4:pointer+4+length]
pointer += 4 + length
return decode_dict
else:
return None
def decode_ie_v2(gtp_packet):
decode_dict = {}
pointer = 0
while pointer < len(gtp_packet):
type = gtp_packet[pointer]
instance = gtp_packet[pointer + 3]
length = 256 * gtp_packet[pointer + 1] + gtp_packet[pointer + 2]
decode_dict[(type,instance)]= gtp_packet[pointer+4:pointer+4+length]
pointer += 4 + length
return decode_dict
def add_imsi_v2( instance, imsi):
if len(imsi) % 2 == 1:
imsi += "f"
imsi = bcd(imsi)
return b'\x01' + struct.pack("!H", len(imsi)) + struct.pack("!B",instance) + imsi
def add_imei_v2( instance, imei):
if len(imei) % 2 == 1:
imei += "f"
imei = bcd(imei)
return b'\x4b' + struct.pack("!H", len(imei)) + struct.pack("!B",instance) + imei
def add_msisdn_v2(instance, msisdn):
if len(msisdn) % 2 == 1:
msisdn += "f"
msisdn = bcd(msisdn)
return b'\x4c' + struct.pack("!H", len(msisdn)) + struct.pack("!B",instance) + msisdn
def add_serving_network_v2(instance, mccmnc):
if len(mccmnc)==5:
mnc3 = 'f'
else:
mnc3 = mccmnc[5]
return b'\x53' + struct.pack("!H", 3) + struct.pack("!B",instance) + bcd(mccmnc[0] + mccmnc[1] + mccmnc[2] + mnc3 + mccmnc[3] + mccmnc[4])
def add_routing_area_identity(mccmnc):
if len(mccmnc)==5:
mnc3 = 'f'
else:
mnc3 = mccmnc[5]
return b'\x03' + bcd(mccmnc[0] + mccmnc[1] + mccmnc[2] + mnc3 + mccmnc[3] + mccmnc[4]) + b'\xff\xfe\xff'
def add_user_location_info_v2(instance, mccmnc, rat): # rat = 1 (sgsn) or 6 (mme ou sgw)
if len(mccmnc)==5:
mnc3 = 'f'
else:
mnc3 = mccmnc[5]
mcc_mnc = bcd(mccmnc[0] + mccmnc[1] + mccmnc[2] + mnc3 + mccmnc[3] + mccmnc[4]) # 3 bytes
if rat == 1:
return b'\x56' + struct.pack("!H", 8) + struct.pack("!B",instance) + b'\x02' + mcc_mnc + b'\x00\x01\x00\x01'
else:
return b'\x56' + struct.pack("!H", 13) + struct.pack("!B",instance) + b'\x18' + mcc_mnc + b'\x00\x01' + mcc_mnc + b'\x00\x00\x00\x01'
def add_rat_v2(instance, rat): # rat = 1 (sgsn) or 6 (mme ou sgw) or 3 (epdg, twan) but user can also set RAT to test erroneous scenarios
return b'\x52' + struct.pack("!H", 1) + struct.pack("!B",instance) + bytes([rat])
def add_indication_v2(instance, b1, b2, b3, b4, b5, b6):
return b'\x4d' + struct.pack("!H", 6) + struct.pack("!B",instance) + bytes([b1,b2,b3,b4,b5,b6])
def add_random_f_teid_v2(instance, int_type, ip, teid): # if teid=0 it generates a new random TEID, else it uses the received value (used in modify bearer)
global teid_local_control, teid_local_data
if teid==0:
rand_number = random.randrange(pow(2,32)-1)
else:
rand_number = teid
if int_type == "s11_c_mme":
teid_local_control = rand_number
return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+10]) + struct.pack("!L", rand_number) + socket.inet_aton(ip)
elif int_type == "s5_c_sgw":
teid_local_control = rand_number
return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+6]) + struct.pack("!L", rand_number) + socket.inet_aton(ip)
elif int_type == "s5_c_pgw":
return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+7]) + struct.pack("!L", 0) + socket.inet_aton(ip)
elif int_type == "s2b_c_pgw":
return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+32]) + struct.pack("!L", 0) + socket.inet_aton(ip)
elif int_type == "s2a_c_pgw":
return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+36]) + struct.pack("!L", 0) + socket.inet_aton(ip)
elif int_type == "s4_c_sgsn":
teid_local_control = rand_number
return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+17]) + struct.pack("!L", rand_number) + socket.inet_aton(ip)
elif int_type == "s1_u_enb":
teid_local_data = rand_number
return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+0]) + struct.pack("!L", rand_number) + socket.inet_aton(ip)
elif int_type == "s4_u_sgsn":
teid_local_data = rand_number
return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+15]) + struct.pack("!L", rand_number) + socket.inet_aton(ip)
elif int_type == "s5_u_sgw":
teid_local_data = rand_number
return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+4]) + struct.pack("!L", rand_number) + socket.inet_aton(ip)
elif int_type == "s2b_c_epdg":
teid_local_control = rand_number
return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+30]) + struct.pack("!L", rand_number) + socket.inet_aton(ip)
elif int_type == "s2b_u_epdg":
teid_local_data = rand_number
return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+31]) + struct.pack("!L", rand_number) + socket.inet_aton(ip)
elif int_type == "s2a_c_twan":
teid_local_control = rand_number
return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+35]) + struct.pack("!L", rand_number) + socket.inet_aton(ip)
elif int_type == "s2a_u_twan":
teid_local_data = rand_number
return b'\x57' + struct.pack("!H", 9) + struct.pack("!B",instance) + bytes([128+34]) + struct.pack("!L", rand_number) + socket.inet_aton(ip)
def add_apn_v2(instance,apn,operator):
apn_bytes = bytes()
if len(operator)==5:
apn = apn + '.mnc0' + operator [3:5] + '.mcc' + operator [0:3] + '.gprs'
else:
apn = apn + '.mnc' + operator [3:6] + '.mcc' + operator [0:3] + '.gprs'
apn_l = apn.split(".")
for word in apn_l:
apn_bytes += struct.pack("!B", len(word)) + word.encode()
return b'\x47' + struct.pack("!H",len(apn_bytes)) + struct.pack("!B",instance) + apn_bytes
def add_selection_mode_v2(sel_mode):
return b'\x80\x00\x01\x00' + bytes([int(sel_mode) % 256])
def add_pco_v2(pdptype, username, password, dhcp_flag, authentication_type, node):
len_pco = 0
pap = b''
chap = b''
dhcp = b''
if username != None and password != None:
if authentication_type == 'PAP':
len_username = struct.pack("!B", len(username))
username = username.encode()
len_password = struct.pack("!B", len(password))
password = password.encode()
len_pap_2B = struct.pack("!H", len(username)+len(password) + 6)
len_pap_1B = struct.pack("!B", len(username)+len(password) + 6)
len_pco = len(username)+len(password) + 6 + 3
pap = b'\xc0\x23' + len_pap_1B + b'\x01\x01' + len_pap_2B + len_username + username + len_password + password
chap = b''
elif authentication_type == 'CHAP':
value = return_random_bytes(16)
name = b'GTP Dialer'
length = struct.pack("!H", len(value) + len(name) + 5)
chap_challenge = b'\xc2\x23' + length[-1:] + b'\x01\x01' + length + b'\x10' + value + name
username = username.encode()
password = password.encode()
m = hashlib.md5()
m.update(b'\x01' + password + value)
hash = m.digest()
length = struct.pack("!H", len(hash) + len(username) + 5)
chap_response = b'\xc2\x23' + length[-1:] + b'\x02\x01' + length + b'\x10' + hash + username
chap = chap_challenge + chap_response
len_pco = len(chap)
pap = b''
if dhcp_flag == True:
dhcp = b'\x00\x0b\x00'
len_pco += 3
if node in ("SGSN", "MME", "SGW"):
ie_type = b'\x4e' # PCO
else:
ie_type = b'\xa3' # Additional PCO (APCO) for ePDG and TWAN
if pdptype == "ipv4":
len_pco = struct.pack("!H", 35 + len_pco)
return ie_type + len_pco + b'\x00\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' + pap + chap + dhcp
elif pdptype == "ipv6":
len_pco = struct.pack("!H", 7 + len_pco)
return ie_type + len_pco + b'\x00\x80\x00\x03\x00\x00\x01\x00' + pap + chap + dhcp
elif pdptype == "ipv4v6":
len_pco = struct.pack("!H", 41 + len_pco)
return ie_type + len_pco + b'\x00\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' + pap + chap + dhcp
def add_pdn_type_v2(instance,pdn_type):
return b'\x63\x00\x01\x00' + bytes([pdn_type])
def add_pdn_address_v2(instance, pdn_type, ipv4, ipv6):
if pdn_type == 1:
return b'\x4f' + struct.pack("!H",5) + struct.pack("!B",instance) + bytes([pdn_type]) + socket.inet_aton(ipv4)
elif pdn_type == 2:
return b'\x4f' + struct.pack("!H",18) + struct.pack("!B",instance) + bytes([pdn_type]) + b'\x00' + socket.inet_pton(socket.AF_INET6, ipv6)
elif pdn_type == 3:
return b'\x4f' + struct.pack("!H",22) + struct.pack("!B",instance) + bytes([pdn_type]) + b'\x00' + socket.inet_pton(socket.AF_INET6, ipv6) + socket.inet_aton(ipv4)
def add_apn_restriction_v2():
return b'\x7f\x00\x01\x00\x00'
def add_ambr_v2():
return b'\x48\x00\x08\x00\x00\x0f\x42\x40\x00\x0f\x42\x40'
def add_ebi_v2(instance,ebi):
return b'\x49\x00\x01' + struct.pack("!B",instance) + bytes([ebi])
def add_bearer_qos_v2(instance, qci):
return b'\x50\x00\x16' + struct.pack("!B",instance) + b'\x55' + struct.pack("!B",int(qci)) + b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
def add_bearer_context_v2(instance, payload_bytes):
return b'\x5d' + struct.pack("!H",len(payload_bytes)) + struct.pack("!B",instance) + payload_bytes
def add_timezone_v2():
return b'\x72\x00\x02\x00\x8f\x02'
### GTPv2 messages ###
def create_session_request(apn, gtp_address, imsi, msisdn, pdptype, ggsn, node, fixed_ipv4, fixed_ipv6, username, password, dhcp, cc, operator, rat, imei, authentication_type, qci, sel_mode):
global sequence_number
gtp_flags = b'\x48'
gtp_message_type = b'\x20'
gtp_length = b'\x00\x00'
gtp_teid = b'\x00\x00\x00\x00'
gtp_sequence_number = struct.pack("!B", sequence_number >> 16) + struct.pack("!H", sequence_number & 0xffff)
gtp_spare = b'\x00'
gtp_header = gtp_flags + gtp_message_type + gtp_length + gtp_teid + gtp_sequence_number + gtp_spare
gtp_imsi = add_imsi_v2(0,imsi)
gtp_imei = add_imei_v2(0,imei)
gtp_msisdn = add_msisdn_v2(0,msisdn)
gtp_serving_network = add_serving_network_v2(0,operator)
if node == "SGSN":
if rat is None:
gtp_user_location_info = add_user_location_info_v2(0,operator,1)
gtp_rat = add_rat_v2(0, 1)
else:
gtp_user_location_info = add_user_location_info_v2(0,operator,int(rat))
gtp_rat = add_rat_v2(0, int(rat))
elif node in ("EPDG", "TWAN"):
if rat is None:
gtp_user_location_info = b''
gtp_rat = add_rat_v2(0, 3)
else:
gtp_user_location_info = b''
gtp_rat = add_rat_v2(0, int(rat))
else:
gtp_user_location_info = add_user_location_info_v2(0,operator,6)
if rat is not None:
gtp_rat = add_rat_v2(0,int(rat))
else:
gtp_rat = add_rat_v2(0, 6)
if pdptype == "ipv4v6":
gtp_indication = add_indication_v2(0,128,0,0,0,0,0)
else:
gtp_indication = add_indication_v2(0,0,0,0,0,0,0)
gtp_indication = b''
if node == "MME":
gtp_teid_control = add_random_f_teid_v2(0,"s11_c_mme", gtp_address, 0) + add_random_f_teid_v2(1, "s5_c_pgw", ggsn, 0)
elif node == "SGSN":
gtp_teid_control = add_random_f_teid_v2(0,"s4_c_sgsn", gtp_address, 0) + add_random_f_teid_v2(1, "s5_c_pgw", ggsn, 0)
elif node == "SGW":
gtp_teid_control = add_random_f_teid_v2(0,"s5_c_sgw", gtp_address, 0)
elif node == "EPDG":
gtp_teid_control = add_random_f_teid_v2(0,"s2b_c_epdg", gtp_address, 0)
elif node == "TWAN":
gtp_teid_control = add_random_f_teid_v2(0,"s2a_c_twan", gtp_address, 0)
gtp_apn = add_apn_v2(0,apn,operator)
gtp_selection_mode = add_selection_mode_v2(sel_mode)
if pdptype == "ipv4":
gtp_pdn_type = add_pdn_type_v2(0,1)
if fixed_ipv4 == None:
gtp_pdn_address = add_pdn_address_v2(0,1,"0.0.0.0","::")
else:
gtp_pdn_address = add_pdn_address_v2(0,1,fixed_ipv4,"::")
gtp_pco = add_pco_v2("ipv4", username, password, dhcp, authentication_type, node)
elif pdptype == "ipv6":
gtp_pdn_type = add_pdn_type_v2(0,2)
if fixed_ipv6 == None:
gtp_pdn_address = add_pdn_address_v2(0,2,"0.0.0.0","::")
else:
gtp_pdn_address = add_pdn_address_v2(0,2,"0.0.0.0",fixed_ipv6)
gtp_pco = add_pco_v2("ipv6", username, password, dhcp, authentication_type, node)
elif pdptype == "ipv4v6":
gtp_pdn_type = add_pdn_type_v2(0,3)
if fixed_ipv4 == None and fixed_ipv6 == None:
gtp_pdn_address = add_pdn_address_v2(0,3,"0.0.0.0","::")
elif fixed_ipv4 != None and fixed_ipv6 == None:
gtp_pdn_address = add_pdn_address_v2(0,3,fixed_ipv4,"::")
elif fixed_ipv4 == None and fixed_ipv6 != None:
gtp_pdn_address = add_pdn_address_v2(0,3,"0.0.0.0",fixed_ipv6)
else:
gtp_pdn_address = add_pdn_address_v2(0,3,fixed_ipv4,fixed_ipv6)
gtp_pco = add_pco_v2("ipv4v6", username, password, dhcp, authentication_type, node)
gtp_apn_restriction = add_apn_restriction_v2()
gtp_ambr = add_ambr_v2()
# ie from grouped gtp_bearer_context
gtp_bearer_id = add_ebi_v2(0,DEFAULT_NSAPI)
if node == "SGSN":
gtp_teid_data = add_random_f_teid_v2(1,"s4_u_sgsn", gtp_address, 0)
elif node == "SGW":
gtp_teid_data = add_random_f_teid_v2(2,"s5_u_sgw", gtp_address, 0)
elif node == "EPDG":
gtp_teid_data = add_random_f_teid_v2(5,"s2b_u_epdg", gtp_address, 0)
elif node == "TWAN":
gtp_teid_data = add_random_f_teid_v2(6,"s2a_u_twan", gtp_address, 0)
else:
gtp_teid_data = b''
gtp_bearer_qos = add_bearer_qos_v2(0, qci)
gtp_bearer_context = add_bearer_context_v2(0,gtp_bearer_id + gtp_teid_data + gtp_bearer_qos)
gtp_timezone = add_timezone_v2()
gtp_cc = b'\x5f\x00\x02\x00' + hex2bytes(cc)
gtp_ie = gtp_imsi + gtp_imei + gtp_msisdn + gtp_serving_network + gtp_user_location_info + gtp_rat + gtp_indication + gtp_teid_control + gtp_apn + gtp_selection_mode + gtp_pdn_type + gtp_pdn_address + gtp_pco + gtp_apn_restriction + gtp_ambr + gtp_bearer_context + gtp_timezone + gtp_cc
create_session_request_packet = bytearray(gtp_header + gtp_ie)
length = len(create_session_request_packet) - 4
create_session_request_packet[3] = length % 256
create_session_request_packet[2] = length // 256
sequence_number +=1
return create_session_request_packet
def modify_bearer_request(gtp_address, node): # only for mme or sgsn mode
global sequence_number, teid_local_control, teid_local_data, teid_remote_data, teid_remote_control
gtp_flags = b'\x48'
gtp_message_type = b'\x22'
gtp_length = b'\x00\x00'
gtp_teid = struct.pack("!L", teid_remote_control)
gtp_sequence_number = struct.pack("!B", sequence_number >> 16) + struct.pack("!H", sequence_number & 0xffff)
gtp_spare = b'\x00'
gtp_header = gtp_flags + gtp_message_type + gtp_length + gtp_teid + gtp_sequence_number + gtp_spare
gtp_bearer_id = add_ebi_v2(0,DEFAULT_NSAPI)
if node == "SGSN":
gtp_teid_data = add_random_f_teid_v2(3,"s4_u_sgsn", gtp_address, teid_local_data)
elif node == "MME":
gtp_teid_data = add_random_f_teid_v2(0,"s1_u_enb", gtp_address, 0)
gtp_bearer_context = add_bearer_context_v2(0,gtp_bearer_id + gtp_teid_data)
modify_bearer_request_packet = bytearray(gtp_header + gtp_bearer_context)
length = len(modify_bearer_request_packet) - 4
modify_bearer_request_packet[3] = length % 256
modify_bearer_request_packet[2] = length // 256