-
Notifications
You must be signed in to change notification settings - Fork 1
/
flyingroutes.py
1726 lines (1523 loc) · 83.2 KB
/
flyingroutes.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
from argparse import ArgumentParser
from socket import gethostbyname, gethostbyaddr, socket, AF_INET, SOCK_DGRAM, SOCK_STREAM, SOCK_RAW, IPPROTO_IP, IPPROTO_ICMP, IPPROTO_UDP, SOL_IP, IP_TTL, error
from struct import pack
from threading import Thread
from queue import Queue
from os import getpid
from time import sleep, time
from platform import system
from rich.progress import Progress
FLAG = 'FLYINGROUTES'
def icmp_checksum(data):
'''
Checksum calculator for ICMP header from https://gist.github.com/pyos/10980172
Parameters:
data (str): data to derive checksum from
Returns:
checksum (int): calculated checksum
'''
x = sum(x << 8 if i % 2 else x for i, x in enumerate(data)) & 0xFFFFFFFF
x = (x >> 16) + (x & 0xFFFF)
x = (x >> 16) + (x & 0xFFFF)
checksum = ~x & 0xFFFF
return checksum
def send_icmp(progress, sender_task, timeout, n_hops, host_ip, queue, sync_queue, stop_queue):
'''
ICMP sender thread function
Parameters:
progress (Progress): rich Progress object to manage tasks
sender_task (Task): rich Task object to update
n_hops (int): number of hops to try by doing TTL increases
host_ip (str): IP address of target host
queue (Queue): queue to communicate with receiver thread
sync_queue (Queue): queue to communicate with sender thread
stop_queue (Queue): queue to communicate with receiver thread to know if target is reached
Returns:
status (bool): return status (True: success, False: failure)
'''
status = False
start = queue.get() # Wait to receive GO from receiver thread
if not start:
progress.remove_task(sender_task)
sync_queue.put(True)
return status
progress.update(sender_task, visible=True)
# Header: Code (8) - Type (0) - Checksum (using checksum function) - ID (unique so take process ID) - Sequence (1)
base_header = pack("bbHHh", 8, 0, 0, getpid() & 0xFFFF, 1)
target_reached = False
for ttl in range(1, n_hops+1):
try:
tx_socket = None
if system() == 'Darwin':
tx_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP)
else:
tx_socket = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)
tx_socket.settimeout(timeout)
except Exception as e:
print(f'Cannot create socket: {e}')
progress.remove_task(sender_task)
sync_queue.put(True)
return status
try:
# Prepare ICMP packet
data_str = f'{FLAG}{ttl}'
data_str_len = len(data_str)
data = pack(f'{data_str_len}s', data_str.encode()) # Data is flag + TTL value (needed for receiver to map response to TTL)
calc_checksum = icmp_checksum(base_header + data) # Checksum value base header and data for header packing
header = pack("bbHHh", 8, 0, calc_checksum, getpid() & 0xFFFF, 1) # Header packing with checksum
b_calc_checksum = int.from_bytes(calc_checksum.to_bytes(2, 'little'), 'big') # Keep checksum value in reverse endianness
if system() == 'Windows':
tx_socket.setsockopt(IPPROTO_IP, IP_TTL, ttl) # Set TTL value
else:
tx_socket.setsockopt(SOL_IP, IP_TTL, ttl) # Set TTL value
for n in range(packets_to_repeat): # Send several packets per TTL value
tx_socket.sendto(header + data, (host_ip, 0))
send_time = time()
queue.put((None, b_calc_checksum, ttl, send_time)) # Store checksum and TTL value in queue for the receiver thread
progress.update(sender_task, advance=1)
try:
target_reached = stop_queue.get(block=False)
except:
pass
if target_reached:
break
tx_socket.close()
except error as e:
print(f'Error while setting TTL and sending data: {e}')
tx_socket.close()
progress.remove_task(sender_task)
sync_queue.put(True)
return status
if target_reached:
break
progress.update(sender_task, completed=n_hops*packets_to_repeat)
progress.remove_task(sender_task)
sync_queue.put(True)
status = True
return status
def send_udp(progress, sender_task, timeout, n_hops, host_ip, dst_port, packets_to_repeat, queue, sync_queue, stop_queue):
'''
UDP sender thread function
Parameters:
progress (Progress): rich Progress object to manage tasks
sender_task (Task): rich Task object to update
timeout (float): socket timeout (in seconds)
n_hops (int): number of hops to try by doing TTL increases
host_ip (str): IP address of target host
dst_port (int): destination port
packets_to_repeat (int): number of packets to send for each TTL value
queue (Queue): queue to communicate with receiver thread
sync_queue (Queue): queue to communicate with sender thread
stop_queue (Queue): queue to communicate with receiver thread to know if target is reached
Returns:
status (bool): return status (True: success, False: failure)
'''
status = False
start = queue.get() # Wait to receive GO from reveiver thread
if not start:
progress.remove_task(sender_task)
return status
progress.update(sender_task, visible=True)
src_port = 1024 # Source port usage starts from 1024
target_reached = False
for ttl in range(1, n_hops+1):
src_port += 1 # Source port selection per TTL value will allow the receive function to associate sent UDP packets to receive ICMP messages
try:
tx_socket = socket(AF_INET, SOCK_DGRAM)
tx_socket.settimeout(timeout)
except Exception as e:
print(f'Cannot create socket: {e}')
progress.remove_task(sender_task)
sync_queue.put(True)
return status
bound = False
while not bound: # Set source port (try all from 1024 up to 65535)
try:
tx_socket.bind(('', src_port))
bound = True
except error as e:
#print(f'Error while binding sending socket to source port {src_port}: {e}')
#print(f'Trying next source port...')
src_port += 1
if src_port > 65535:
print(f'Cannot find available source port to bind sending socket')
tx_socket.close()
progress.remove_task(sender_task)
sync_queue.put(True)
return status
try:
if system() == 'Windows':
tx_socket.setsockopt(IPPROTO_IP, IP_TTL, ttl) # Set TTL value
else:
tx_socket.setsockopt(SOL_IP, IP_TTL, ttl) # Set TTL value
for n in range(packets_to_repeat): # Send several packets per TTL value but change the destination port (for ECMP routing)
tx_socket.sendto((FLAG+str(ttl)).encode(), (host_ip, dst_port+n))
send_time = time()
queue.put((None, src_port, ttl, send_time)) # Store source port and TTL value in queue for the receiver thread
progress.update(sender_task, advance=1)
try:
target_reached = stop_queue.get(block=False)
except:
pass
if target_reached:
tx_socket.close()
break
tx_socket.close()
except error as e:
print(f'Error while setting TTL and sending data: {e}')
tx_socket.close()
progress.remove_task(sender_task)
sync_queue.put(True)
return status
if target_reached:
break
progress.remove_task(sender_task)
sync_queue.put(True)
status = True
return status
def send_tcp(progress, sender_task, timeout, n_hops, host_ip, dst_port, packets_to_repeat, queue, sync_queue, stop_queue):
'''
TCP sender thread function
Parameters:
progress (Progress): rich Progress object to manage tasks
sender_task (Task): rich Task object to update
timeout (float): socket timeout (in seconds)
n_hops (int): number of hops to try by doing TTL increases
host_ip (str): IP address of target host
dst_port (int): destination port
packets_to_repeat (int): number of packets to send for each TTL value
queue (Queue): queue to communicate with sender thread
sync_queue (Queue): queue to communicate with sender thread
stop_queue (Queue): queue to communicate with receiver thread to know if target is reached
Returns:
status (bool): return status (True: success, False: failure)
'''
status = False
start = sync_queue.get() # Wait to receive GO from reveiver thread
if not start:
progress.remove_task(sender_task)
sync_queue.put(True)
return status
progress.update(sender_task, visible=True)
sockets = []
src_port = 1024 # Source port usage starts from 1024
target_reached = False
for ttl in range(1, n_hops+1):
src_ports = []
for n in range(packets_to_repeat): # Send several packets per TTL value but change the destination port (for ECMP routing)
src_port += 1 # Source port selection per packet to send will allow the receive function to associate sent TCP packets to receive ICMP messages
try:
tx_socket = socket(AF_INET, SOCK_STREAM) # One socket per destination port (per packet to send)
except Exception as e:
print(f'Cannot create socket: {e}')
progress.remove_task(sender_task)
sync_queue.put(True)
return status
bound = False
while not bound: # Set source port (try all from 1024 up to 65535)
try:
tx_socket.bind(('', src_port))
bound = True
except error as e:
#print(f'Error while binding sending socket to source port {src_port}: {e}')
#print(f'Trying next source port...')
src_port += 1
if src_port > 65535:
print(f'Cannot find available source port to bind sending socket')
tx_socket.close()
progress.remove_task(sender_task)
sync_queue.put(True)
return status
if system() == 'Windows':
tx_socket.setsockopt(IPPROTO_IP, IP_TTL, ttl) # Set TTL value
else:
tx_socket.setsockopt(SOL_IP, IP_TTL, ttl) # Set TTL value
tx_socket.setblocking(False) # Set socket in non-blocking mode to allow fast sending of all the packets
src_ports.append(src_port) # Store source port used in the list of source ports for the current TTL value
try:
tx_socket.connect((host_ip, dst_port+n)) # Try TCP connection
except error as e:
pass
finally:
send_time = time()
sockets.append((tx_socket, src_ports, ttl, send_time)) # Store socket, source ports and TTL value to check connection status later on
progress.update(sender_task, advance=1)
try:
target_reached = stop_queue.get(block=False)
except:
pass
if target_reached:
break
if target_reached:
break
progress.update(sender_task, completed=n_hops*packets_to_repeat)
progress.remove_task(sender_task)
sleep(timeout) # To allow TCP connections to be established (if target is reached by some sockets), still lower than TCP idle timeout
for s, src_ports, ttl, send_time in sockets: # Test connection status for each socket by trying to send data
try:
s.send((FLAG+str(ttl)).encode()) # Try sending TTL value in data
queue.put((True, src_ports, ttl, send_time)) # Store True to indicate that target was reached with source port and TTL value in queue for the receiver thread
except Exception as e:
queue.put((None, src_ports, ttl, send_time)) # Store source port and TTL value in queue for the receiver thread
s.close()
s.close()
sync_queue.put(True) # Indicate to the receiver thread that receiver can continue with mapping of sent responses to sent packets
status = True
return status
def send_all(progress, sender_task, timeout, n_hops, host_ip, dst_port, packets_to_repeat, queue, sync_queue, stop_queue):
'''
UDP, ICMP & TCP sender thread function
Parameters:
progress (Progress): rich Progress object to manage tasks
sender_task (Task): rich Task object to update
timeout (float): socket timeout (in seconds)
n_hops (int): number of hops to try by doing TTL increases
host_ip (str): IP address of target host
dst_port (int): destination port
packets_to_repeat (int): number of packets to send for each TTL value
queue (Queue): queue to communicate with receiver thread
sync_queue (Queue): queue to communicate with receiver thread
stop_queue (Queue): queue to communicate with receiver thread to know if target is reached
Returns:
status (bool): return status (True: success, False: failure)
'''
status = False
start = queue.get() # Wait to receive GO from reveiver thread
if not start:
progress.remove_task(sender_task)
sync_queue.put(True)
return status
progress.update(sender_task, visible=True)
tcp_sockets = []
# Preparation of ICMP Socket
try:
tx_socket_icmp = None
if system() == 'Darwin':
tx_socket_icmp = socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP)
else:
tx_socket_icmp = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)
tx_socket_icmp.settimeout(timeout)
except Exception as e:
print(f'Cannot create ICMP socket: {e}')
progress.remove_task(sender_task)
sync_queue.put(True)
return status
src_port = 1024 # Source port usage starts from 1024
target_reached = False
for ttl in range(1, n_hops+1):
src_port += 1 # Source port selection per TTL value will allow the receive function to associate sent UDP packets to receive ICMP messages
src_ports_tcp = []
# Preparation of UDP Socket
try:
tx_socket_udp = socket(AF_INET, SOCK_DGRAM)
tx_socket_udp.settimeout(timeout)
except Exception as e:
print(f'Cannot create UDP socket: {e}')
progress.remove_task(sender_task)
sync_queue.put(True)
return status
# Binding of UDP socket
udp_bound = False
while not udp_bound: # Set source port (try all from 1024 up to 65535)
try:
tx_socket_udp.bind(('', src_port))
udp_bound = True
except error as e:
#print(f'Error while binding sending socket to source port {src_port}: {e}')
#print(f'Trying next source port...')
src_port += 1
if src_port > 65535:
print(f'Cannot find available source port to bind UDP sending socket')
tx_socket_udp.close()
progress.remove_task(sender_task)
sync_queue.put(True)
return status
# ICMP TTL and data preparation
try:
# Header: Code (8) - Type (0) - Checksum (using checksum function) - ID (unique so take process ID) - Sequence (1)
header = pack("bbHHh", 8, 0, 0, getpid() & 0xFFFF, 1)
data = pack(str(len((FLAG+str(ttl))))+'s', (FLAG+str(ttl)).encode()) # Data is flag + TTL value (needed for receiver to map response to TTL)
calc_checksum = icmp_checksum(header + data) # Checksum value for header packing
header = pack("bbHHh", 8, 0, calc_checksum, getpid() & 0xFFFF, 1)
b_calc_checksum = int.from_bytes(calc_checksum.to_bytes(2, 'little'), 'big') # Keep checksum value in reverse endianness
if system() == 'Windows':
tx_socket_icmp.setsockopt(IPPROTO_IP, IP_TTL, ttl) # Set TTL value
else:
tx_socket_icmp.setsockopt(SOL_IP, IP_TTL, ttl) # Set TTL value
except error as e:
print(f'Error while setting TTL on ICMP socket: {e}')
tx_socket_icmp.close()
progress.remove_task(sender_task)
sync_queue.put(True)
return status
# UDP TTL preparation
try:
if system() == 'Windows':
tx_socket_udp.setsockopt(IPPROTO_IP, IP_TTL, ttl) # Set TTL value
else:
tx_socket_udp.setsockopt(SOL_IP, IP_TTL, ttl) # Set TTL value
except error as e:
print(f'Error while setting TTL on UDP socket: {e}')
tx_socket_udp.close()
progress.remove_task(sender_task)
sync_queue.put(True)
return status
# Sending the packets
for n in range(packets_to_repeat): # Send several packets per TTL value but change the destination port (for ECMP routing)
# ICMP
try:
tx_socket_icmp.sendto(header + data, (host_ip, 0))
send_time = time()
queue.put(('icmp', None, b_calc_checksum, ttl, send_time)) # Store checksum and TTL value in queue for the receiver thread
except error as e:
print(f'Error while sending ICMP data, continuing with other protocols: {e}')
tx_socket_icmp.close()
# UDP
try:
tx_socket_udp.sendto((FLAG+str(ttl)).encode(), (host_ip, dst_port+n))
send_time = time()
queue.put(('udp', None, src_port, ttl, send_time)) # Store source port and TTL value in queue for the receiver thread
except error as e:
print(f'Error while sending UDP data, continuing with other protocols: {e}')
tx_socket_udp.close()
# TCP
src_port += 1 # Source port selection per packet to send will allow the receive function to associate sent TCP packets to receive ICMP messages
try:
tx_socket_tcp = socket(AF_INET, SOCK_STREAM) # One socket per destination port (per packet to send)
except Exception as e:
print(f'Cannot create TCP socket: {e}')
tx_socket_icmp.close()
progress.remove_task(sender_task)
sync_queue.put(True)
return status
bound = False
while not bound: # Set source port (try all from 1024 up to 65535)
try:
tx_socket_tcp.bind(('', src_port))
bound = True
except error as e:
#print(f'Error while binding sending socket to source port {src_port}: {e}')
#print(f'Trying next source port...')
src_port += 1
if src_port > 65535:
print(f'Cannot find available source port to bind sending socket')
tx_socket_tcp.close()
progress.remove_task(sender_task)
sync_queue.put(True)
return status
if system() == 'Windows':
tx_socket_tcp.setsockopt(IPPROTO_IP, IP_TTL, ttl) # Set TTL value
else:
tx_socket_tcp.setsockopt(SOL_IP, IP_TTL, ttl) # Set TTL value
tx_socket_tcp.setblocking(False) # Set socket in non-blocking mode to allow fast sending of all the packets
src_ports_tcp.append(src_port) # Store source port used in the list of source ports for the current TTL value
try:
tx_socket_tcp.connect((host_ip, dst_port+n)) # Try TCP connection
except error as e:
pass
finally:
send_time = time()
tcp_sockets.append((tx_socket_tcp, src_ports_tcp, ttl, send_time)) # Store socket, source ports and TTL value to check connection status later on
progress.update(sender_task, advance=1)
try:
target_reached = stop_queue.get(block=False)
except:
pass
if target_reached:
break
if target_reached:
break
progress.remove_task(sender_task)
sleep(timeout) # To allow TCP connections to be established (if target is reached by some sockets), still lower than TCP idle timeout
for s, src_ports_tcp, ttl, send_time in tcp_sockets: # Test connection status for each socket by trying to send data
try:
s.send((FLAG+str(ttl)).encode()) # Try sending TTL value in data
queue.put(('tcp', True, src_ports_tcp, ttl, send_time)) # Store True to indicate that target was reached with source port and TTL value in queue for the receiver thread
except Exception as e:
queue.put(('tcp', None, src_ports_tcp, ttl, send_time)) # Store source port and TTL value in queue for the receiver thread
s.close()
s.close()
sync_queue.put(True) # Indicate to the receiver thread that receiver can continue with mapping of sent responses to sent packets
tx_socket_icmp.close()
tx_socket_udp.close()
status = True
return status
def print_results(host_ttl_results, host_delta_time):
'''
Printing function to standard outputfor TTL results per hop
Parameters:
host_ttl_results (list or dict): host IP addresses per TTL value (and per protocol if dict)
host_delta_time (dict): response time per host and protocol
Returns:
None
'''
if isinstance(host_ttl_results, list): # Single protocol (no protocol and list of tuples)
for (res_host, res_ttl) in host_ttl_results:
hop_space = f''
if res_ttl < 10:
hop_space = f' '
host_fqdn = ''
if ',' in res_host: # Several hosts for this TTL
res_host_list = res_host.replace(' ', '').split(',')
for host in res_host_list:
if res_host_list.index(host) == 0:
s = f'Hop {res_ttl}: {hop_space}'
else:
s = f' '
host_fqdn = ''
try:
fqdn = ''
fqdn = gethostbyaddr(host)[0]
host_fqdn = f' ({fqdn})'
except:
pass
if host in host_delta_time.keys():
if host_delta_time[host] <= 0:
s += f'{host}{host_fqdn}'
else:
s += f'{host}{host_fqdn} - {round(host_delta_time[host]*1000,2)}ms'
else:
s += f'{host}{host_fqdn}'
print(f'{s}')
host_fqdn = ''
elif res_host in host_delta_time.keys(): # One host for this TTL
host_fqdn = ''
try:
fqdn = ''
fqdn = gethostbyaddr(res_host)[0]
host_fqdn = f' ({fqdn})'
except:
pass
if host_delta_time[res_host] <= 0:
print(f'Hop {res_ttl}: {hop_space}{res_host}{host_fqdn}')
else:
print(f'Hop {res_ttl}: {hop_space}{res_host}{host_fqdn} - {round(host_delta_time[res_host]*1000,2)}ms')
else:
print(f'Hop {res_ttl}: {hop_space}{res_host}{host_fqdn}')
elif isinstance(host_ttl_results, dict): # All protocols (protocol and dict)
for res_ttl in sorted(host_ttl_results.keys()):
hop_space = f''
if res_ttl < 10:
hop_space = f' '
ttl_str = ''
for proto in host_ttl_results[res_ttl].keys():
if proto == 'all': # All protocols failed to have a response
ttl_str += f'Hop {res_ttl}: {hop_space}{host_ttl_results[res_ttl][proto]} - ICMP, UDP and TCP'
else: # We parse the response per protocol
for res_host in host_ttl_results[res_ttl][proto]: # For each protocol, we parse the responses per host
if ',' in res_host: # Several hosts for the protocol
res_host_list = res_host.replace(' ', '').split(',')
for host in res_host_list:
if not f'Hop {res_ttl}: {hop_space}' in ttl_str:
ttl_str += f'Hop {res_ttl}: {hop_space}'
elif not host in ttl_str:
ttl_str += f'\n '
host_fqdn = ''
try:
fqdn = ''
fqdn = gethostbyaddr(host)[0]
host_fqdn = f' ({fqdn})'
except:
pass
if (host in host_delta_time.keys()):
if not host in ttl_str: # Create a new host line
if host_delta_time[host][proto] <= 0:
ttl_str += f'{host}{host_fqdn} - {proto.upper()}'
else:
ttl_str += f'{host}{host_fqdn} - {proto.upper()}: {round(host_delta_time[host][proto]*1000,2)}ms'
else: # Add the protocol and response time info to the right existing host line
lines = ttl_str.split('\n')
ttl_str = ''
for line in lines:
if host in line:
if host_delta_time[host][proto] <= 0:
line += f', {proto.upper()}'
else:
line += f', {proto.upper()}: {round(host_delta_time[host][proto]*1000,2)}ms'
ttl_str += '\n'+line
ttl_str = ttl_str[1:] # Remove the first '\n' character
else:
if not host in ttl_str: # Create a new host line
ttl_str += f'{host}{host_fqdn} - {proto.upper()}'
else: # Add the protocol and response time info to the right existing host line
lines = ttl_str.split('\n')
ttl_str = ''
for line in lines:
if host in line:
ttl_str += f', {proto.upper()}'
ttl_str += '\n'+line
ttl_str = ttl_str[1:] # Remove the first '\n' character
else: # One host for the protocol
if not f'Hop {res_ttl}: {hop_space}' in ttl_str:
ttl_str += f'Hop {res_ttl}: {hop_space}'
elif not res_host in ttl_str:
ttl_str += f'\n '
host_fqdn = ''
try:
fqdn = ''
fqdn = gethostbyaddr(res_host)[0]
host_fqdn = f' ({fqdn})'
except:
pass
if (res_host in host_delta_time.keys()):
if not res_host in ttl_str: # Create a new host line
if host_delta_time[res_host][proto] <= 0:
ttl_str += f'{res_host}{host_fqdn} - {proto.upper()}'
else:
ttl_str += f'{res_host}{host_fqdn} - {proto.upper()}: {round(host_delta_time[res_host][proto]*1000,2)}ms'
else: # Add the protocol and response time info to the right existing host line
if host_delta_time[res_host][proto] <= 0:
ttl_str += f', {proto.upper()}'
else:
ttl_str += f', {proto.upper()}: {round(host_delta_time[res_host][proto]*1000,2)}ms'
else:
if not res_host in ttl_str: # Create a new host line
ttl_str += f'{res_host}{host_fqdn}, {proto.upper()}'
else: # Add the protocol and response time info to the right existing host line
ttl_str += f', {proto.upper()}'
print(f'{ttl_str}')
def map_received_icmp_to_sent_udp(host, n_hops, host_ip, recv_host_sport, reached, queue):
'''
Mapping function to associate sent UDP packets (source port and TTL value) to received ICMP packets (host IP address and inner UDP source port)
Parameters:
host (str): target hostname
n_hops (int): number of hops tried by doing TTL increases
host_ip (str): IP address of target host
recv_host_sport (list): receive information from ICMP packets (host IP address, inner UDP source port)
reached (bool): weither the target host was reached or not
queue (Queue): queue to communicate with sender thread
Returns:
host_ttl_results (list): TTL values and associated host IP addresses
'''
host_ttl_results = []
host_sport_ttl = []
host_delta_time = {}
while not queue.empty(): # Get all sent information by the sender thread from the queue
(new_host, new_sport, new_ttl, send_time) = queue.get() # new_host is None from queue
no_resp = True
for (rhost, sport, receive_time) in recv_host_sport: # Parse ICMP responses
if sport == new_sport: # Use source port information to get associated recv_host
no_resp = False
new_host = rhost
if not host_sport_ttl: # If results list is empty, let's add the first result element
host_sport_ttl.append((new_host, new_sport, new_ttl))
host_delta_time[new_host] = receive_time-send_time
else:
duplicate = False
for (rhost, sport, ttl) in host_sport_ttl: # Parse the already stored results
if (new_sport == sport): # Check if duplicate is found based on the source port (as different host could be seen due to ECMP if -r option was passed)
duplicate = True
if (new_host in rhost) and new_ttl < ttl: # If same hosts (means we went above the number of hops), compare associated TTLs and replace if TTL is lower
host_sport_ttl.append((new_host, new_sport, new_ttl))
host_sport_ttl.remove((rhost, sport, ttl))
host_delta_time[new_host] = receive_time-send_time
elif (not new_host in rhost) and new_ttl == ttl: # If different hosts and same TTL (means we got different hosts for same TTL), replace entry with one with both hosts
host_sport_ttl.append((new_host+', '+rhost, new_sport, new_ttl))
host_sport_ttl.remove((rhost, sport, ttl))
host_delta_time[new_host] = receive_time-send_time
if not duplicate: # If no duplicate, just add it to the results
host_sport_ttl.append((new_host, new_sport, new_ttl))
host_delta_time[new_host] = receive_time-send_time
if no_resp and not ('* * * * * * * *', new_sport, new_ttl) in host_sport_ttl: # No response has been seen for this source port
host_sport_ttl.append(('* * * * * * * *', new_sport, new_ttl))
# Find host TTL if reached
reached_host_ttl = n_hops
if reached:
for (rhost, sport, ttl) in host_sport_ttl:
if host_ip in rhost:
reached_host_ttl = ttl
host_sport_ttl[host_sport_ttl.index((rhost, sport, ttl))] = (host_ip, sport, ttl)
break
print(f'{host} ({host_ip}) reached in {reached_host_ttl} hops')
else:
print(f'{host} ({host_ip}) not reached in {reached_host_ttl} hops')
# Only keep results with TTL below host TTL (discard upper TTL values)
for (rhost, sport, ttl) in host_sport_ttl:
if ttl <= reached_host_ttl:
host_ttl_results.append((rhost, ttl))
# Add hops with no answers
for n in range(1, n_hops+1):
found = False
for (rhost, sport, ttl) in host_sport_ttl:
if n == ttl:
found = True
if not found and (n <= reached_host_ttl):
host_ttl_results.append(('* * * * * * * *', n))
return sorted(host_ttl_results, key=lambda a: a[1]), host_delta_time
def receive_udp(progress, receiver_task, timeout, n_hops, host, host_ip, packets_to_repeat, queue, sync_queue, stop_queue):
'''
UDP receiver (of ICMP packets) thread function
Parameters:
progress (Progress): rich Progress object to manage tasks
receiver_task (Task): rich Task object to update
timeout (float): socket timeout (in seconds)
n_hops (int): number of hops to try by doing TTL increases
host (str): target hostname
host_ip (str): IP address of target host
packets_to_repeat (int): number of packets to receive for each TTL value
queue (Queue): queue to communicate with sender thread
sync_queue (Queue): queue to communicate with sender thread
stop_queue (Queue): queue to communicate with sender thread to know if target is reached
Returns:
status (bool): return status (True: success, False: failure)
'''
status = False
system_platform = system()
try:
rx_socket = None
if system_platform == 'Darwin':
rx_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP)
else:
rx_socket = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)
rx_socket.settimeout(timeout)
except Exception as e:
print(f'Cannot create socket: {e}')
queue.put(False)
progress.remove_task(receiver_task)
return status
if system_platform == 'Windows':
rx_socket.bind(('', 0))
reached = False
recv_data_addr = []
timed_out = False
progress.update(receiver_task, visible=True)
sender_done = False
timed_out = False
queue.put(True) # Indicate to the sender thread that receiver thread is ready
while True:
timed_out = False
try:
data, addr = rx_socket.recvfrom(1024)
recv_data_addr.append((data, addr, time()))
progress.update(receiver_task, advance=1)
except error as e:
timed_out = True
#print(f'Timeout reached while some responses are still pending')
try:
sender_done = sync_queue.get(block=False)
except:
pass
if sender_done and timed_out:
break
progress.update(receiver_task, completed=n_hops*packets_to_repeat)
if not recv_data_addr:
print(f'No responses received')
progress.remove_task(receiver_task)
return status
recv_host_sport = []
for data, addr, receive_time in recv_data_addr: # Parse received ICMP packets
resp_host = addr[0]
# Decode IP and then ICMP headers
ip_header = data.hex()
ip_header_len = int(ip_header[1], 16) * 4 * 2 # IP header length is a multiple of 32-bit (4 bytes or 4 * 2 nibbles) increment
icmp_header = ip_header[ip_header_len:]
icmp_type = int(icmp_header[0:2], 16)
icmp_code = int(icmp_header[2:4], 16)
# Decode inner IP and then inner UDP headers
inner_ip_header = icmp_header[16:]
inner_ip_header_len = int(inner_ip_header[1], 16) * 4 * 2 # IP header length is a multiple of 32-bit (4 bytes or 4 * 2 nibbles) increment
inner_udp = inner_ip_header[inner_ip_header_len:]
inner_udp_len = int(inner_udp[8:12], 16) * 2
inner_udp = inner_udp[:inner_udp_len]
inner_udp_sport = int(inner_udp[0:4], 16)
if icmp_type == 11 and icmp_code == 0: # ICMP Time-to-live exceeded in transit
recv_host_sport.append((resp_host, inner_udp_sport, receive_time))
if icmp_type == 3 and icmp_code == 3 and resp_host == host_ip: # ICMP Destination unreachable Port unreachable
recv_host_sport.append((resp_host, inner_udp_sport, receive_time))
reached = True
host_ttl_results, host_delta_time = map_received_icmp_to_sent_udp(host, n_hops, host_ip, recv_host_sport, reached, queue)
progress.remove_task(receiver_task)
print_results(host_ttl_results, host_delta_time)
status = True
return status
def map_received_icmp_to_sent_tcp(host, n_hops, host_ip, recv_host_sport, queue, dst_port):
'''
Mapping function to associate sent TCP packets (source port and TTL value) to received ICMP packets (host IP address and inner TCP source port)
Parameters:
host (str): target hostname
n_hops (int): number of hops tried by doing TTL increases
host_ip (str): IP address of target host
recv_host_sport (list): receive information from ICMP packets (host IP address, inner TCP source port)
reached (bool): weither the target host was reached or not
queue (Queue): queue to communicate with sender thread
Returns:
host_ttl_results (list): TTL values and associated host IP addresses
'''
host_ttl_results = []
host_sport_ttl = []
host_delta_time = {}
reached = False
while not queue.empty(): # Get all sent information by the sender thread from the queue
(new_host, new_sports, new_ttl, send_time) = queue.get() # new_host is None from queue except when target was reached
if new_host: # Target was reached in sender thread
reached = True
new_host = host_ip
recv_host_sport.append((new_host, new_sports, new_ttl)) # Let's append this as a TCP response too
no_resp = True
for (rhost, sport, receive_time) in recv_host_sport: # Parse ICMP / TCP responses
if (sport in new_sports) or (sport == new_sports): # Use source port information to get associated recv_host
no_resp = False
new_host = rhost
if not host_sport_ttl: # If results list is empty, let's add the first result element
host_sport_ttl.append((new_host, sport, new_ttl))
host_delta_time[new_host] = receive_time-send_time
else:
duplicate = False
for (rhost, sport, ttl) in host_sport_ttl: # Parse the already stored results
if (sport in new_sports) or (sport == new_sports): # Check if duplicate is found based on the source port (as different host could be seen due to ECMP if -r option was passed)
duplicate = True
if (new_host in rhost) and new_ttl < ttl: # If same hosts (means we went above the number of hops), compare associated TTLs and replace if TTL is lower
host_sport_ttl.append((new_host, new_sports, new_ttl))
host_sport_ttl.remove((rhost, sport, ttl))
host_delta_time[new_host] = receive_time-send_time
elif (not new_host in rhost) and new_ttl == ttl: # If different hosts and same TTL (means we got different hosts for same TTL), replace entry with one with both hosts
host_sport_ttl.append((new_host+', '+rhost, new_sports, new_ttl))
host_sport_ttl.remove((rhost, sport, ttl))
host_delta_time[new_host] = receive_time-send_time
if not duplicate: # If no duplicate, just add it to the results
host_sport_ttl.append((new_host, new_sports, new_ttl))
host_delta_time[new_host] = receive_time-send_time
if no_resp and not ('* * * * * * * *', new_sports, new_ttl) in host_sport_ttl: # No response has been seen for this source port
host_sport_ttl.append(('* * * * * * * *', new_sports, new_ttl))
# Find host TTL if reached
reached_host_ttl = n_hops
if reached:
for (rhost, sport, ttl) in host_sport_ttl:
if host_ip in rhost:
reached_host_ttl = ttl
host_sport_ttl[host_sport_ttl.index((rhost, sport, ttl))] = (host_ip, sport, ttl)
# Try adding delta time for target by performing another TCP connection (as so far the response time was measure based on ICMP answers)
try:
tx_socket = socket(AF_INET, SOCK_STREAM)
start = time()
tx_socket.connect((host_ip, dst_port))
host_delta_time[host_ip] = time() - start
except:
pass
break
print(f'{host} ({host_ip}) reached in {reached_host_ttl} hops')
else:
print(f'{host} ({host_ip}) not reached in {reached_host_ttl} hops')
# Add hops with no answers
for n in range(1, n_hops+1):
found = False
for (rhost, sport, ttl) in host_sport_ttl:
if n == ttl:
found = True
if not found and (n <= reached_host_ttl):
host_ttl_results.append(('* * * * * * * *', n))
# Only keep results with TTL below host TTL (discard upper TTL values)
for (rhost, sport, ttl) in host_sport_ttl:
if ttl <= reached_host_ttl:
host_ttl_results.append((rhost, ttl))
return sorted(host_ttl_results, key=lambda a: a[1]), host_delta_time
def receive_tcp(progress, receiver_task, timeout, n_hops, host, host_ip, packets_to_repeat, dst_port, queue, sync_queue, stop_queue):
'''
TCP receiver (of ICMP packets) thread function
Parameters:
progress (Progress): rich Progress object to manage tasks
receiver_task (Task): rich Task object to update
timeout (float): socket timeout (in seconds)
n_hops (int): number of hops to try by doing TTL increases
host (str): target hostname
host_ip (str): IP address of target host
packets_to_repeat (int): number of packets to receive for each TTL value
dest_port (int): destination port
queue (Queue): queue to communicate with sender thread
sync_queue (Queue): queue to communicate with sender thread
stop_queue (Queue): queue to communicate with sender thread to know if target is reached
Returns:
status (bool): return status (True: success, False: failure)
'''
status = False
system_platform = system()
try:
rx_socket = None
if system_platform == 'Darwin':
rx_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP)
else:
rx_socket = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)
rx_socket.settimeout(timeout)
except Exception as e:
print(f'Cannot create socket: {e}')
queue.put(False)
progress.remove_task(receiver_task)
return status
if system_platform == 'Windows':
rx_socket.bind(('', 0))
reached = False
recv_data_addr = []
progress.update(receiver_task, visible=True)
sender_done = False
timed_out = False
sync_queue.put(True) # Indicate to the sender thread that receiver thread is ready
while True:
timed_out = False
try:
data, addr = rx_socket.recvfrom(1024)
recv_data_addr.append((data, addr, time()))
progress.update(receiver_task, advance=1)
except error as e:
timed_out = True
#print(f'Timeout reached while some responses are still pending')
try:
sender_done = sync_queue.get(block=False)
except:
pass
if sender_done and timed_out:
break
progress.update(receiver_task, completed=n_hops*packets_to_repeat)
if not recv_data_addr:
print(f'No responses received')
progress.remove_task(receiver_task)
return status
recv_host_sport = []
for data, addr, receive_time in recv_data_addr: # Parse received ICMP packets
resp_host = addr[0]
# Decode IP and then ICMP headers
ip_header = data.hex()
ip_header_len = int(ip_header[1], 16) * 4 * 2 # IP header length is a multiple of 32-bit (4 bytes or 4 * 2 nibbles) increment
icmp_header = ip_header[ip_header_len:]
icmp_type = int(icmp_header[0:2], 16)
icmp_code = int(icmp_header[2:4], 16)
# Decode inner IP and then inner TCP headers
inner_ip_header = icmp_header[16:]
inner_ip_header_len = int(inner_ip_header[1], 16) * 4 * 2 # IP header length is a multiple of 32-bit (4 bytes or 4 * 2 nibbles) increment
inner_tcp = inner_ip_header[inner_ip_header_len:]