-
Notifications
You must be signed in to change notification settings - Fork 2
/
vxlan_tool.py
executable file
·1072 lines (892 loc) · 43 KB
/
vxlan_tool.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
#
# Copyright (c) 2015 Intel, Inc., Cisco Systems, Inc. and others. All rights
# reserved.
#
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License v1.0 which accompanies this distribution,
# and is available at http://www.eclipse.org/legal/epl-v10.html
__author__ = "Yi Yang, Reinaldo Penno"
__copyright__ = "Copyright(c) 2015, Intel, Inc. and Cisco Systems, Inc."
__version__ = "0.2"
__email__ = "[email protected], [email protected]"
__status__ = "beta"
import socket, sys
import pdb
import argparse
from struct import *
from ctypes import Structure, c_ubyte, c_ushort, c_uint
NSH_TYPE1_LEN = 0x6
NSH_MD_TYPE1 = 0x1
NSH_VERSION1 = int('00', 2)
NSH_NEXT_PROTO_IPV4 = int('00000001', 2)
NSH_NEXT_PROTO_OAM = int('00000100', 2)
NSH_NEXT_PROTO_ETH = int('00000011', 2)
NSH_FLAG_ZERO = int('00000000', 2)
IP_HEADER_LEN = 5
IPV4_HEADER_LEN_BYTES = 20
IPV4_VERSION = 4
IPV4_PACKET_ID = 54321
IPV4_TTL = 255
IPV4_TOS = 0
IPV4_IHL_VER = (IPV4_VERSION << 4) + IP_HEADER_LEN
UDP_HEADER_LEN_BYTES = 8
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class VXLAN(Structure):
_fields_ = [('flags', c_ubyte),
('reserved', c_uint, 16),
('next_protocol', c_uint, 8),
('vni', c_uint, 24),
('reserved2', c_uint, 8)]
def __init__(self, flags=int('00001000', 2), reserved=0, next_protocol=0,
vni=int('111111111111111111111111', 2), reserved2=0, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.flags = flags
self.reserved = reserved
self.next_protocol = next_protocol
self.vni = vni
self.reserved2 = reserved2
header_size = 8
def build(self):
return pack('!B H B I',
self.flags,
self.reserved,
self.next_protocol,
(self.vni << 8) + self.reserved2)
class ETHHEADER(Structure):
_fields_ = [('dmac0', c_ubyte),
('dmac1', c_ubyte),
('dmac2', c_ubyte),
('dmac3', c_ubyte),
('dmac4', c_ubyte),
('dmac5', c_ubyte),
('smac0', c_ubyte),
('smac1', c_ubyte),
('smac2', c_ubyte),
('smac3', c_ubyte),
('smac4', c_ubyte),
('smac5', c_ubyte),
('ethertype0', c_ubyte),
('ethertype1', c_ubyte)]
header_size = 14
def build(self):
return pack('!B B B B B B B B B B B B B B',
self.dmac0,
self.dmac1,
self.dmac2,
self.dmac3,
self.dmac4,
self.dmac5,
self.smac0,
self.smac1,
self.smac2,
self.smac3,
self.smac4,
self.smac5,
self.ethertype0,
self.ethertype1)
class BASEHEADER(Structure):
"""
Represent a NSH base header
"""
_fields_ = [('version', c_ushort, 2),
('flags', c_ushort, 8),
('length', c_ushort, 6),
('md_type', c_ubyte),
('next_protocol', c_ubyte),
('service_path', c_uint, 24),
('service_index', c_uint, 8)]
def __init__(self, service_path=1, service_index=255, version=NSH_VERSION1, flags=NSH_FLAG_ZERO,
length=NSH_TYPE1_LEN, md_type=NSH_MD_TYPE1, proto=NSH_NEXT_PROTO_ETH, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.version = version
self.flags = flags
self.length = length
self.md_type = md_type
self.next_protocol = proto
self.service_path = service_path
self.service_index = service_index
header_size = 8
def build(self):
return pack('!H B B I',
(self.version << 14) + (self.flags << 6) + self.length,
self.md_type,
self.next_protocol,
(self.service_path << 8) + self.service_index)
class CONTEXTHEADER(Structure):
_fields_ = [('network_platform', c_uint),
('network_shared', c_uint),
('service_platform', c_uint),
('service_shared', c_uint)]
header_size = 16
def __init__(self, network_platform=0x00, network_shared=0x00, service_platform=0x00, service_shared=0x00, *args,
**kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.network_platform = network_platform
self.network_shared = network_shared
self.service_platform = service_platform
self.service_shared = service_shared
def build(self):
return pack('!I I I I',
self.network_platform,
self.network_shared,
self.service_platform,
self.service_shared)
class IP4HEADER(Structure):
_fields_ = [
('ip_ihl', c_ubyte),
('ip_ver', c_ubyte),
('ip_tos', c_ubyte),
('ip_tot_len', c_ushort),
('ip_id', c_ushort),
('ip_frag_offset', c_ushort),
('ip_ttl', c_ubyte),
('ip_proto', c_ubyte),
('ip_chksum', c_ushort),
('ip_saddr', c_uint),
('ip_daddr', c_uint)]
header_size = 20
def build(self):
ip_header_pack = pack('!B B H H H B B H I I', IPV4_IHL_VER, self.ip_tos, self.ip_tot_len, self.ip_id,
self.ip_frag_offset, self.ip_ttl, self.ip_proto, self.ip_chksum, self.ip_saddr,
self.ip_daddr)
return ip_header_pack
def set_ip_checksum(self, checksum):
self.ip_chksum = checksum
class UDPHEADER(Structure):
"""
Represents a UDP header
"""
_fields_ = [
('udp_sport', c_ushort),
('udp_dport', c_ushort),
('udp_len', c_ushort),
('udp_sum', c_ushort)]
header_size = 8
def build(self):
udp_header_pack = pack('!H H H H', self.udp_sport, self.udp_dport, self.udp_len,
self.udp_sum)
return udp_header_pack
class PSEUDO_TCPHEADER(Structure):
""" Pseudoheader used in the TCP checksum."""
def __init__(self):
self.src_ip = 0
self.dest_ip = 0
self.zeroes = 0
self.protocol = 6
self.length = 0
def build(self):
""" Create a string from a pseudoheader """
p_tcp_header_pack = pack('!I I B B H', self.src_ip, self.dest_ip,
self.zeroes, self.protocol, self.length)
return p_tcp_header_pack
class PSEUDO_UDPHEADER(Structure):
""" Pseudoheader used in the UDP checksum."""
def __init__(self):
self.src_ip = 0
self.dest_ip = 0
self.zeroes = 0
self.protocol = 17
self.length = 0
def build(self):
""" Create a string from a pseudoheader """
p_udp_header_pack = pack('!I I B B H', self.src_ip, self.dest_ip,
self.zeroes, self.protocol, self.length)
return p_udp_header_pack
class TCPHEADER(Structure):
"""
Represents a TCP header
"""
_fields_ = [
('tcp_sport', c_ushort),
('tcp_dport', c_ushort),
('tcp_seq', c_uint),
('tcp_ack', c_uint),
('tcp_offset', c_ubyte),
('tcp_flags', c_ubyte),
('tcp_window', c_ushort),
('tcp_checksum', c_ushort),
('tcp_urgent', c_ushort),]
header_size = 20
def build(self):
tcp_header_pack = pack('!H H I I B B H H H', self.tcp_sport, self.tcp_dport,
self.tcp_seq, self.tcp_ack, self.tcp_offset,
self.tcp_flags, self.tcp_window, self.tcp_checksum,
self.tcp_urgent)
return tcp_header_pack
class ICMPHEADER(Structure):
"""
Represents a ICMP header
"""
_fields_ = [
('icmp_type', c_ubyte),
('icmp_code', c_ubyte),
('icmp_checksum', c_ushort),
('icmp_unused', c_ushort),
('icmp_MTU', c_ushort),
('icmp_iphead', c_uint)]
header_size = 12
def build(self):
icmp_header_pack = pack('!B B H H H I', self.icmp_type, self.icmp_code,
self.icmp_checksum, self.icmp_unused, self.icmp_MTU,
self.icmp_iphead)
return icmp_header_pack
def decode_eth(payload, offset, eth_header_values):
eth_header = payload[offset:(offset+14)]
_header_values = unpack('!B B B B B B B B B B B B B B', eth_header)
eth_header_values.dmac0 = _header_values[0]
eth_header_values.dmac1 = _header_values[1]
eth_header_values.dmac2 = _header_values[2]
eth_header_values.dmac3 = _header_values[3]
eth_header_values.dmac4 = _header_values[4]
eth_header_values.dmac5 = _header_values[5]
eth_header_values.smac0 = _header_values[6]
eth_header_values.smac1 = _header_values[7]
eth_header_values.smac2 = _header_values[8]
eth_header_values.smac3 = _header_values[9]
eth_header_values.smac4 = _header_values[10]
eth_header_values.smac5 = _header_values[11]
eth_header_values.ethertype0 = _header_values[12]
eth_header_values.ethertype1 = _header_values[13]
def decode_ip(payload, ip_header_values):
ip_header = payload[14:34]
_header_values = unpack('!B B H H H B B H I I', ip_header)
ip_header_values.ip_ihl = _header_values[0] & 0x0F
ip_header_values.ip_ver = _header_values[0] >> 4
ip_header_values.ip_tos = _header_values[1]
ip_header_values.ip_tot_len = _header_values[2]
ip_header_values.ip_id = _header_values[3]
ip_header_values.ip_frag_offset = _header_values[4]
ip_header_values.ip_ttl = _header_values[5]
ip_header_values.ip_proto = _header_values[6]
ip_header_values.ip_chksum = _header_values[7]
ip_header_values.ip_saddr = _header_values[8]
ip_header_values.ip_daddr = _header_values[9]
def decode_udp(payload, udp_header_values):
udp_header = payload[34:42]
_header_values = unpack('!H H H H', udp_header)
udp_header_values.udp_sport = _header_values[0]
udp_header_values.udp_dport = _header_values[1]
udp_header_values.udp_len = _header_values[2]
udp_header_values.udp_sum = _header_values[3]
def decode_tcp(payload, offset, tcp_header_values):
tcp_header = payload[(108+offset):(128+offset)]
_header_values = unpack('!H H I I B B H H H', tcp_header)
tcp_header_values.tcp_sport = _header_values[0]
tcp_header_values.tcp_dport = _header_values[1]
tcp_header_values.tcp_seq = _header_values[2]
tcp_header_values.tcp_ack = _header_values[3]
tcp_header_values.tcp_offset = _header_values[4]
tcp_header_values.tcp_flags = _header_values[5]
tcp_header_values.tcp_window = _header_values[6]
tcp_header_values.tcp_checksum = _header_values[7]
tcp_header_values.tcp_urgent = _header_values[8]
def decode_internal_ip(payload, offset, ip_header_values):
ip_header = payload[(88+offset):(108+offset)]
_header_values = unpack('!B B H H H B B H I I', ip_header)
ip_header_values.ip_ihl = _header_values[0] & 0x0F
ip_header_values.ip_ver = _header_values[0] >> 4
ip_header_values.ip_tos = _header_values[1]
ip_header_values.ip_tot_len = _header_values[2]
ip_header_values.ip_id = _header_values[3]
ip_header_values.ip_frag_offset = _header_values[4]
ip_header_values.ip_ttl = _header_values[5]
ip_header_values.ip_proto = _header_values[6]
ip_header_values.ip_chksum = _header_values[7]
ip_header_values.ip_saddr = _header_values[8]
ip_header_values.ip_daddr = _header_values[9]
def decode_vxlan(payload, vxlan_header_values):
"""Decode the VXLAN header for a received packets"""
vxlan_header = payload[42:50]
_header_values = unpack('!B H B I', vxlan_header)
vxlan_header_values.flags = _header_values[0]
vxlan_header_values.reserved = _header_values[1]
vxlan_header_values.next_protocol = _header_values[2]
vni_rsvd2 = _header_values[3]
vxlan_header_values.vni = vni_rsvd2 >> 8
vxlan_header_values.reserved2 = vni_rsvd2 & 0x000000FF
def decode_nsh_baseheader(payload, offset, nsh_base_header_values):
"""Decode the NSH base headers for a received packets"""
base_header = payload[offset:(offset+8)]
_header_values = unpack('!H B B I', base_header)
start_idx = _header_values[0]
nsh_base_header_values.md_type = _header_values[1]
nsh_base_header_values.next_protocol = _header_values[2]
path_idx = _header_values[3]
nsh_base_header_values.version = start_idx >> 14
nsh_base_header_values.flags = start_idx >> 6
nsh_base_header_values.length = start_idx >> 0
nsh_base_header_values.service_path = path_idx >> 8
nsh_base_header_values.service_index = path_idx & 0x000000FF
def decode_nsh_contextheader(payload, offset, nsh_context_header_values):
"""Decode the NSH context headers for a received packet"""
context_header = payload[offset:(offset+16)]
_header_values = unpack('!I I I I', context_header)
nsh_context_header_values.network_platform = _header_values[0]
nsh_context_header_values.network_shared = _header_values[1]
nsh_context_header_values.service_platform = _header_values[2]
nsh_context_header_values.service_shared = _header_values[3]
def compute_internet_checksum(data):
"""
Function for Internet checksum calculation. Works
for both IP and UDP.
"""
checksum = 0
n = len(data) % 2
# data padding
pad = bytearray('', encoding='UTF-8')
if n == 1:
pad = bytearray(b'\x00')
# for i in range(0, len(data + pad) - n, 2):
for i in range(0, len(data)-1, 2):
checksum += (ord(data[i]) << 8) + (ord(data[i + 1]))
if n == 1:
checksum += (ord(data[len(data)-1]) << 8) + (pad[0])
while checksum >> 16:
checksum = (checksum & 0xFFFF) + (checksum >> 16)
checksum = ~checksum & 0xffff
return checksum
# Implements int.from_bytes(s, byteorder='big')
def int_from_bytes(s):
return sum(ord(c) << (i * 8) for i, c in enumerate(s[::-1]))
def build_ethernet_header_swap(myethheader):
""" Build Ethernet header """
newethheader=ETHHEADER()
newethheader.smac0 = myethheader.dmac0
newethheader.smac1 = myethheader.dmac1
newethheader.smac2 = myethheader.dmac2
newethheader.smac3 = myethheader.dmac3
newethheader.smac4 = myethheader.dmac4
newethheader.smac5 = myethheader.dmac5
newethheader.dmac0 = myethheader.smac0
newethheader.dmac1 = myethheader.smac1
newethheader.dmac2 = myethheader.smac2
newethheader.dmac3 = myethheader.smac3
newethheader.dmac4 = myethheader.smac4
newethheader.dmac5 = myethheader.smac5
newethheader.ethertype0 = myethheader.ethertype0
newethheader.ethertype1 = myethheader.ethertype1
return newethheader
def build_ipv4_header(ip_tot_len, proto, src_ip, dest_ip, swap_ip):
"""
Builds a complete IP header including checksum
"""
if src_ip:
ip_saddr = socket.inet_aton(src_ip)
else:
ip_saddr = socket.inet_aton(socket.gethostbyname(socket.gethostname()))
if (swap_ip == True):
new_ip_daddr = int_from_bytes(ip_saddr)
new_ip_saddr = socket.inet_aton(dest_ip)
new_ip_saddr = int_from_bytes(new_ip_saddr)
else:
new_ip_saddr = int_from_bytes(ip_saddr)
new_ip_daddr = int_from_bytes(socket.inet_aton(dest_ip))
ip_header = IP4HEADER(IP_HEADER_LEN, IPV4_VERSION, IPV4_TOS, ip_tot_len, IPV4_PACKET_ID, 0, IPV4_TTL, proto, 0, new_ip_saddr, new_ip_daddr)
checksum = compute_internet_checksum(ip_header.build())
ip_header.set_ip_checksum(checksum)
ip_header_pack = ip_header.build()
return ip_header, ip_header_pack
def build_ipv4_header_reset(ip_tot_len, proto, src_ip, dest_ip, swap_ip):
"""
Builds a complete IP header including checksum
"""
if (swap_ip == True):
new_ip_daddr = src_ip
new_ip_saddr = dest_ip
ip_header = IP4HEADER(IP_HEADER_LEN, IPV4_VERSION, IPV4_TOS, ip_tot_len, IPV4_PACKET_ID, 0, IPV4_TTL, proto, 0, new_ip_saddr, new_ip_daddr)
checksum = compute_internet_checksum(ip_header.build())
ip_header.set_ip_checksum(checksum)
ip_header_pack = ip_header.build()
return ip_header, ip_header_pack
def build_tcp_reset(mytcpheader, ip_header):
"""
Building an TCP header requires fields from
IP header in order to perform checksum calculation
"""
# build TCP header with sum = 0
tcp_header = TCPHEADER()
tcp_header.tcp_flags = 20
tcp_header.tcp_offset = 80
source_port = mytcpheader.tcp_sport
tcp_header.tcp_sport = mytcpheader.tcp_dport
tcp_header.tcp_dport = source_port
tcp_header.tcp_window = 0
tcp_header.tcp_urgent = 0
ack = mytcpheader.tcp_seq + 1
tcp_header.tcp_seq = 0
tcp_header.tcp_ack = ack
tcp_header.tcp_checksum = 0
tcp_header_pack = tcp_header.build()
# build Pseudo Header
p_header = PSEUDO_TCPHEADER()
p_header.dest_ip = ip_header.ip_daddr
p_header.src_ip = ip_header.ip_saddr
p_header.length = 20
p_header_pack = p_header.build()
tcp_checksum = compute_internet_checksum(p_header_pack + tcp_header_pack)
tcp_header.tcp_checksum = tcp_checksum
# pack TCP header again but this time with checksum
tcp_header_pack = tcp_header.build()
return tcp_header, tcp_header_pack
def build_udp_header(src_port, dest_port, ip_header, data):
"""
Building an UDP header requires fields from
IP header in order to perform checksum calculation
"""
# build UDP header with sum = 0
udp_header = UDPHEADER(src_port, dest_port, UDP_HEADER_LEN_BYTES + len(data), 0)
udp_header_pack = udp_header.build()
# build Pseudo Header
p_header = PSEUDO_UDPHEADER()
p_header.dest_ip = ip_header.ip_daddr
p_header.src_ip = ip_header.ip_saddr
p_header.length = udp_header.udp_len
p_header_pack = p_header.build()
udp_checksum = compute_internet_checksum(p_header_pack + udp_header_pack + data)
udp_header.udp_sum = udp_checksum
# pack UDP header again but this time with checksum
udp_header_pack = udp_header.build()
return udp_header, udp_header_pack
def build_udp_packet(src_ip, dest_ip, src_port, dest_port, data, swap_ip):
"""
Data needs to encoded as Python bytes. In the case of strings
this means a bytearray of an UTF-8 encoding
"""
total_len = len(data) + IPV4_HEADER_LEN_BYTES + UDP_HEADER_LEN_BYTES
# First we build the IP header
ip_header, ip_header_pack = build_ipv4_header(total_len, socket.IPPROTO_UDP, src_ip, dest_ip, swap_ip)
# Build UDP header
udp_header, udp_header_pack = build_udp_header(src_port, dest_port, ip_header, data)
udp_packet = ip_header_pack + udp_header_pack + data
return udp_packet
def getmac(interface):
try:
mac = open('/sys/class/net/'+interface+'/address').readline()
except:
mac = None
return mac
def print_ethheader(ethheader):
print("Eth Dst MAC: %.2x:%.2x:%.2x:%.2x:%.2x:%.2x, Src MAC: %.2x:%.2x:%.2x:%.2x:%.2x:%.2x, Ethertype: 0x%.4x" % (ethheader.dmac0, ethheader.dmac1, ethheader.dmac2, ethheader.dmac3, ethheader.dmac4, ethheader.dmac5, ethheader.smac0, ethheader.smac1, ethheader.smac2, ethheader.smac3, ethheader.smac4, ethheader.smac5, (ethheader.ethertype0<<8) | ethheader.ethertype1))
def print_ipheader(ipheader):
print("IP Version: %s IP Header Length: %s, TTL: %s, Protocol: %s, Src IP: %s, Dst IP: %s" % (ipheader.ip_ver, ipheader.ip_ihl, ipheader.ip_ttl, ipheader.ip_proto, str(socket.inet_ntoa(pack('!I', ipheader.ip_saddr))), str(socket.inet_ntoa(pack('!I', ipheader.ip_daddr)))))
def print_udpheader(udpheader):
print ("UDP Src Port: %s, Dst Port: %s, Length: %s, Checksum: %s" % (udpheader.udp_sport, udpheader.udp_dport, udpheader.udp_len, udpheader.udp_sum))
def print_vxlanheader(vxlanheader):
print("VxLAN/VxLAN-gpe VNI: %s, flags: %.2x, Next: %s" % (vxlanheader.vni, vxlanheader.flags, vxlanheader.next_protocol))
def print_nsh_baseheader(nshbaseheader):
print("NSH base nsp: %s, nsi: %s" % (nshbaseheader.service_path, nshbaseheader.service_index))
def print_nsh_contextheader(nshcontextheader):
print("NSH context c1: 0x%.8x, c2: 0x%.8x, c3: 0x%.8x, c4: 0x%.8x" % (nshcontextheader.network_platform, nshcontextheader.network_shared, nshcontextheader.service_platform, nshcontextheader.service_shared))
def main():
parser = argparse.ArgumentParser(description='This is a VxLAN/VxLAN-gpe + NSH dump and forward tool, you can use it to dump and forward VxLAN/VxLAN-gpe + NSH packets, it can also act as an NSH-aware SF for SFC test when you use --forward option, in that case, it will automatically decrease nsi by one.', prog='vxlan_tool.py')
parser.add_argument('-i', '--interface',
help='Specify the interface to listen')
parser.add_argument('-d', '--do', choices=['dump', 'forward', 'send'],
help='dump/foward/send VxLAN/VxLAN-gpe + NSH or Eth + NSH packet')
parser.add_argument('-t', '--type', choices=['eth_nsh', 'vxlan_gpe_nsh'], default='vxlan_gpe_nsh',
help='Specify packet type for send: eth_nsh or vxlan_gpe_nsh')
parser.add_argument('--outer-source-mac',
help='Specify outer source MAC for packet send')
parser.add_argument('--outer-destination-mac',
help='Specify outer destination MAC for packet send')
parser.add_argument('--outer-source-ip',
help='Specify outer source IP address for packet send')
parser.add_argument('--outer-destination-ip',
help='Specify outer destination IP address for packet send')
parser.add_argument('--outer-source-udp-port', type=int,
help='Specify outer source UDP port for packet send')
parser.add_argument('--inner-source-mac',
help='Specify inner source MAC for packet send')
parser.add_argument('--inner-destination-mac',
help='Specify inner destination MAC for packet send')
parser.add_argument('--inner-source-ip',
help='Specify inner source IP address for packet send')
parser.add_argument('--inner-destination-ip',
help='Specify inner destination IP address for packet send')
parser.add_argument('--inner-source-udp-port', type=int,
help='Specify inner source UDP port for packet send')
parser.add_argument('--inner-destination-udp-port', type=int,
help='Specify inner destination UDP port for packet send')
parser.add_argument('-n', '--number', type=int,
help='Specify number of packet to send')
parser.add_argument('--no-swap-ip', dest='swap_ip', default=True, action='store_false',
help="won't swap ip if provided")
parser.add_argument('-v', '--verbose', choices=['on', 'off'],
help='dump packets when in forward mode')
parser.add_argument('--forward-inner', '-f', dest='forward_inner',
default=False, action='store_true',
help='Strip the outer encapsulation and forward the inner packet')
parser.add_argument('--block', '-b', type=int, default=0,
help='Acts as a firewall dropping packets that match this TCP dst port')
args = parser.parse_args()
macaddr = None
try:
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
if args.interface is not None:
s.bind((args.interface, 0))
if ((args.do == "forward") or (args.do == "send")):
if args.interface is None:
print("Error: you must specify the interface by -i or --interface for forward and send")
sys.exit(-1)
send_s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
send_s.bind((args.interface, 0))
if args.interface is not None:
macstring = getmac(args.interface)
if (macstring is not None):
macaddr = macstring.split(':')
if (args.do == "send"):
if (args.inner_source_mac is None):
args.inner_source_mac = macstring
if (args.inner_destination_mac is None):
print("Error: you must specify inner destination MAC for packet send")
sys.exit(-1)
if (args.inner_source_ip is None) or (args.inner_destination_ip is None):
print("Error: you must specify inner source IP and inner destination IP for packet send")
sys.exit(-1)
if (args.outer_source_mac is None):
args.outer_source_mac = args.inner_source_mac
if (args.outer_destination_mac is None):
args.outer_destination_mac = args.inner_destination_mac
if (args.outer_source_ip is None):
args.outer_source_ip = args.inner_source_ip
if (args.outer_destination_ip is None):
args.outer_destination_ip = args.inner_destination_ip
if (args.outer_source_udp_port is None):
args.outer_source_udp_port = 55651
if (args.inner_source_udp_port is None):
args.inner_source_udp_port = args.outer_source_udp_port
if (args.inner_destination_udp_port is None):
args.inner_destination_udp_port = 25
if (args.number is None):
args.number = 10
except OSError as e:
print("{}".format(e) + " '%s'" % args.interface)
sys.exit(-1)
do_print = ((args.do != "forward") or (args.verbose == "on"))
vxlan_gpe_udp_ports = [4790, 6633]
vxlan_udp_ports = [4789] + vxlan_gpe_udp_ports
#header len
eth_length = 14
ip_length = 20
udp_length = 8
vxlan_length = 8
nshbase_length = 8
nshcontext_length = 16
""" Send VxLAN/VxLAN-gpe + NSH packet """
if (args.do == "send"):
myethheader = ETHHEADER()
myipheader = IP4HEADER()
myudpheader = UDPHEADER()
myvxlanheader = VXLAN()
mynshbaseheader = BASEHEADER()
mynshcontextheader = CONTEXTHEADER()
""" Set Ethernet header """
dstmacaddr = args.outer_destination_mac.split(":")
myethheader.dmac0 = int(dstmacaddr[0], 16)
myethheader.dmac1 = int(dstmacaddr[1], 16)
myethheader.dmac2 = int(dstmacaddr[2], 16)
myethheader.dmac3 = int(dstmacaddr[3], 16)
myethheader.dmac4 = int(dstmacaddr[4], 16)
myethheader.dmac5 = int(dstmacaddr[5], 16)
myethheader.smac0 = int(macaddr[0], 16)
myethheader.smac1 = int(macaddr[1], 16)
myethheader.smac2 = int(macaddr[2], 16)
myethheader.smac3 = int(macaddr[3], 16)
myethheader.smac4 = int(macaddr[4], 16)
myethheader.smac5 = int(macaddr[5], 16)
myethheader.ethertype0 = 0x08
myethheader.ethertype1 = 0x00
""" Set VxLAN header """
myvxlanheader.flags = 0
myvxlanheader.reserved = 0
myvxlanheader.next_protocol = 0x04
myvxlanheader.vni = 0x1234
myvxlanheader.reserved2 = 0
""" Set NSH base header """
mynshbaseheader.flags = NSH_FLAG_ZERO
mynshbaseheader.length = NSH_TYPE1_LEN
mynshbaseheader.md_type = NSH_MD_TYPE1
mynshbaseheader.next_protocol = NSH_NEXT_PROTO_ETH
mynshbaseheader.service_path = 23
mynshbaseheader.service_index = 45
""" Set NSH context header """
mynshcontextheader.network_platform = int_from_bytes(socket.inet_aton(args.outer_destination_ip))
mynshcontextheader.network_shared = 0x1234
mynshcontextheader.service_platform = 0x12345678
mynshcontextheader.service_shared = 0x87654321
innerippack = build_udp_packet(args.inner_source_ip, args.inner_destination_ip, args.inner_source_udp_port, args.inner_destination_udp_port, "Hellow, World!!!".encode('utf-8'), False)
if (args.type == "vxlan_gpe_nsh"):
outerippack = build_udp_packet(args.outer_source_ip, args.outer_destination_ip, args.outer_source_udp_port, 4790, myvxlanheader.build() + mynshbaseheader.build() + mynshcontextheader.build() + myethheader.build() + innerippack, False)
elif (args.type == "eth_nsh"):
outerippack = mynshbaseheader.build() + mynshcontextheader.build() + myethheader.build() + innerippack
myethheader.ethertype0 = 0x89
myethheader.ethertype1 = 0x4f
""" Build Ethernet packet """
ethpkt = myethheader.build() + outerippack
""" Decode ethernet header """
decode_eth(ethpkt, 0, myethheader)
if (args.type == "eth_nsh"):
offset = eth_length
decode_nsh_baseheader(ethpkt, offset, mynshbaseheader)
decode_nsh_contextheader(ethpkt, offset + nshbase_length, mynshcontextheader)
elif (args.type == "vxlan_gpe_nsh"):
""" Decode IP header """
decode_ip(ethpkt, myipheader)
""" Decode UDP header """
decode_udp(ethpkt, myudpheader)
offset = eth_length + ip_length + udp_length + vxlan_length
decode_nsh_baseheader(ethpkt, offset, mynshbaseheader)
decode_nsh_contextheader(ethpkt, offset + nshbase_length, mynshcontextheader)
pktnum = 0
while (args.number > 0):
""" Send it and make sure all the data is sent out """
pkt = ethpkt
while pkt:
sent = send_s.send(pkt)
pkt = pkt[sent:]
pktnum += 1
if (do_print):
print("\n\nPacket #%d" % pktnum)
""" Print ethernet header """
if (do_print):
print_ethheader(myethheader)
if (args.type == "vxlan_gpe_nsh"):
""" Print IP header """
if (do_print):
print_ipheader(myipheader)
""" Print UDP header """
if (do_print):
print_udpheader(myudpheader)
""" Print VxLAN/VxLAN-gpe header """
if (do_print):
print_vxlanheader(myvxlanheader)
""" Print NSH base header """
if (do_print):
print_nsh_baseheader(mynshbaseheader)
""" Print NSH context header """
if (do_print):
print_nsh_contextheader(mynshcontextheader)
args.number -= 1
sys.exit(0)
# receive a packet
pktnum=0
while True:
packet = s.recvfrom(65565)
#packet string from tuple
packet = packet[0]
myethheader = ETHHEADER()
myinsertedethheader = ETHHEADER()
has_inserted_eth = False
""" Decode ethernet header """
decode_eth(packet, 0, myethheader)
if ((myethheader.ethertype0 != 0x08) or (myethheader.ethertype1 != 0x00)):
if ((myethheader.ethertype0 != 0x89) or (myethheader.ethertype1 != 0x4f)):
continue
if (macaddr is not None):
if ((myethheader.dmac4 != int(macaddr[4], 16)) or (myethheader.dmac5 != int(macaddr[5], 16))):
continue
""" Check if the received packet was ETH + NSH """
if ((myethheader.ethertype0 == 0x89) or (myethheader.ethertype1 == 0x4f)):
pktnum = pktnum + 1
print("\n\nPacket #%d" % pktnum)
""" Eth + NSH """
mynshbaseheader = BASEHEADER()
mynshcontextheader = CONTEXTHEADER()
offset = eth_length
decode_nsh_baseheader(packet, offset, mynshbaseheader)
decode_nsh_contextheader(packet, offset + nshbase_length, mynshcontextheader)
""" Print ethernet header """
print_ethheader(myethheader)
""" Print NSH base header """
print_nsh_baseheader(mynshbaseheader)
""" Print NSH context header """
print_nsh_contextheader(mynshcontextheader)
""" Check if Firewall checking is enabled, and block/drop if its the same TCP port """
if (args.block != 0):
mytcpheader = TCPHEADER()
decode_tcp(packet, 0, mytcpheader)
if (mytcpheader.tcp_dport == args.block):
print bcolors.WARNING + "TCP packet dropped on port: " + str(args.block) + bcolors.ENDC
continue
if ((args.do == "forward") and (args.interface is not None)):
""" nsi minus one for send """
mynshbaseheader.service_index = mynshbaseheader.service_index - 1
""" Build Ethernet header """
newethheader = build_ethernet_header_swap(myethheader)
""" Build Ethernet packet """
pkt = newethheader.build() + mynshbaseheader.build() + mynshcontextheader.build() + packet[eth_length+nshbase_length+nshcontext_length:]
""" Send it and make sure all the data is sent out """
while pkt:
sent = send_s.send(pkt)
pkt = pkt[sent:]
continue
pktnum = pktnum + 1
# if (do_print):
# print("\n\nPacket #%d" % pktnum)
""" Print ethernet header """
# if (do_print):
# print_ethheader(myethheader)
myipheader = IP4HEADER()
""" Decode IP header """
decode_ip(packet, myipheader)
""" Print IP header """
# if (do_print):
# print_ipheader(myipheader)
if (myipheader.ip_proto != 17):
continue
myudpheader = UDPHEADER()
""" Decode UDP header """
decode_udp(packet, myudpheader)
""" Print UDP header """
if (do_print):
print_udpheader(myudpheader)
if (myudpheader.udp_dport not in vxlan_udp_ports):
continue
myvxlanheader = VXLAN()
""" Decode VxLAN/VxLAN-gpe header """
decode_vxlan(packet, myvxlanheader)
""" Print VxLAN/VxLAN-gpe header """
if (do_print):
print_vxlanheader(myvxlanheader)
mynshbaseheader = BASEHEADER()
mynshcontextheader = CONTEXTHEADER()
""" Print NSH header """
if (myudpheader.udp_dport in vxlan_gpe_udp_ports):
offset = eth_length + ip_length + udp_length + vxlan_length
""" Decode inserted ethernet header before NSH """
decode_eth(packet, offset, myinsertedethheader)
if ((myinsertedethheader.ethertype0 == 0x89) and (myinsertedethheader.ethertype1 == 0x4f)):
has_inserted_eth = True
offset += eth_length
decode_nsh_baseheader(packet, offset, mynshbaseheader)
offset += nshbase_length
decode_nsh_contextheader(packet, offset, mynshcontextheader)
offset += nshcontext_length
""" Print NSH base header """
if (do_print):
print_nsh_baseheader(mynshbaseheader)
""" Print NSH context header """
if (do_print):
print_nsh_contextheader(mynshcontextheader)
""" Check if Firewall checking is enabled, and block/drop if its the same TCP port """
if (args.block != 0):
mytcpheader = TCPHEADER()
decode_tcp(packet, eth_length, mytcpheader)
print bcolors.OKBLUE + "FLAGS" + str(mytcpheader.tcp_flags) + bcolors.ENDC
print bcolors.OKBLUE + "OFFSET " + str(mytcpheader.tcp_offset) + bcolors.ENDC
print bcolors.OKBLUE + "SEQ " + str(mytcpheader.tcp_seq) + bcolors.ENDC
print bcolors.OKBLUE + "ACK " + str(mytcpheader.tcp_ack) + bcolors.ENDC
if (mynshcontextheader.service_platform == 0):
if (mytcpheader.tcp_dport == args.block):
print bcolors.WARNING + "TCP packet dropped on port: " + str(args.block) + bcolors.ENDC
continue
else:
print bcolors.WARNING + "TCP packet dropped: " + str(args.block) + " and RESET sent" + bcolors.ENDC
"Activate the RESET flag and exchange tcp ports"
# "We create the ICMP packet"
# print bcolors.WARNING + "TCP packet dropped: " + str(args.block) + " and ICMP sent" + bcolors.ENDC
# old_packet = packet
# myicmpheader = ICMPHEADER()
# myicmpheader.icmp_type = 3
# myicmpheader.icmp_code = 1
# myicmpheader.icmp_checksum = 0
# myicmpheader.icmp_unused = 0
# myicmpheader.icmp_MTU = 1400
# myicmpheader.icmp_iphead = 0
## ip_header_and_data = old_packet[(88+eth_length):(108+eth_length)] + packet[(108+eth_length):(116+eth_length)]
# ip_header_and_data = old_packet[(88+eth_length):]
# icmp_header_aux = myicmpheader.build()
# icmp_header = icmp_header_aux[:8] + ip_header_and_data
# icmp_checksum = compute_internet_checksum(icmp_header)
# myicmpheader.icmp_checksum = icmp_checksum
# icmp_header_aux = myicmpheader.build()
# icmp_header = icmp_header_aux[:8] + ip_header_and_data
# packet_aux = packet[:(108+eth_length)] + icmp_header
# packet = packet_aux
"We do the same but with IP"
myinternalipheader = IP4HEADER()
decode_internal_ip(packet, eth_length, myinternalipheader)
"Use the following parameters for ICMP"
# myinternalipheader.ip_tot_len = 88
# myinternalipheader.ip_tos = 192
# myinternalipheader.ip_proto = 1
# myinternalipheader.ip_id = 0
# myinternalipheader.ip_tot_len = 40
# ip_source = myinternalipheader.ip_saddr
# myinternalipheader.ip_saddr = myinternalipheader.ip_daddr
# myinternalipheader.ip_daddr = ip_source
# new_internalipheader = myinternalipheader.build()
myinternalipheader, new_internalipheader = build_ipv4_header_reset(40, myinternalipheader.ip_proto, myinternalipheader.ip_saddr, myinternalipheader.ip_daddr, True)
old_internalipheader = packet[(88+eth_length):(108+eth_length)]