f8fa595867bff46a383f54b9a77dab6e80260972
[csit.git] / GPL / traffic_scripts / lisp / lispgpe_check.py
1 #!/usr/bin/env python3
2
3 # Copyright (c) 2021 Cisco and/or its affiliates.
4 #
5 # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6 #
7 # Licensed under the Apache License 2.0 or
8 # GNU General Public License v2.0 or later;  you may not use this file
9 # except in compliance with one of these Licenses. You
10 # may obtain a copy of the Licenses at:
11 #
12 #     http://www.apache.org/licenses/LICENSE-2.0
13 #     https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
14 #
15 # Note: If this file is linked with Scapy, which is GPLv2+, your use of it
16 # must be under GPLv2+.  If at any point in the future it is no longer linked
17 # with Scapy (or other GPLv2+ licensed software), you are free to choose
18 # Apache 2.
19 #
20 # Unless required by applicable law or agreed to in writing, software
21 # distributed under the License is distributed on an "AS IS" BASIS,
22 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23 # See the License for the specific language governing permissions and
24 # limitations under the License.
25
26 """Traffic script that sends an ICMP/ICMPv6 packet out one interface, receives
27 a LISPGPE-encapsulated packet on the other interface and verifies received
28 packet.
29 """
30
31 import sys
32 import ipaddress
33
34 from scapy.all import bind_layers, Packet
35 from scapy.fields import FlagsField, BitField, XBitField, IntField
36 from scapy.layers.inet import ICMP, IP, UDP
37 from scapy.layers.inet6 import ICMPv6EchoRequest
38 from scapy.layers.inet6 import IPv6, ICMPv6ND_NS, ICMPv6MLReport2, ICMPv6ND_RA
39 from scapy.layers.l2 import Ether
40 from scapy.packet import Raw
41
42 from ..PacketVerifier import RxQueue, TxQueue
43 from ..TrafficScriptArg import TrafficScriptArg
44
45
46 class LispGPEHeader(Packet):
47     """Scapy header for the Lisp GPE Layer."""
48
49     name = "Lisp GPE Header"
50     fields_desc = [
51         FlagsField(
52             u"flags", None, 8, [u"N", u"L", u"E", u"V", u"I", u"P", u"R", u"O"]
53         ),
54         BitField(u"version", 0, size=2),
55         BitField(u"reserved", 0, size=14),
56         XBitField(u"next_protocol", 0, size=8),
57         IntField(u"instance_id/locator_status_bits", 0)
58     ]
59
60     def guess_payload_class(self, payload):
61         protocol = {
62             0x1: LispGPEInnerIP,
63             0x2: LispGPEInnerIPv6,
64             0x3: LispGPEInnerEther,
65             0x4: LispGPEInnerNSH
66         }
67         return protocol[self.next_protocol]
68
69
70 class LispGPEInnerIP(IP):
71     """Scapy inner LISP GPE layer for IPv4-in-IPv4."""
72
73     name = u"Lisp GPE Inner Layer - IPv4"
74
75
76 class LispGPEInnerIPv6(IPv6):
77     """Scapy inner LISP GPE layer for IPv6-in-IPv6."""
78
79     name = u"Lisp GPE Inner Layer - IPv6"
80
81
82 class LispGPEInnerEther(Ether):
83     """Scapy inner LISP GPE layer for Lisp-L2."""
84
85     name = u"Lisp GPE Inner Layer - Ethernet"
86
87
88 class LispGPEInnerNSH(Packet):
89     """Scapy inner LISP GPE layer for Lisp-NSH.
90
91     Parsing not implemented.
92     """
93
94
95 def valid_ipv4(ip_address):
96     """Check IPv4 address.
97
98     :param ip_address: IPv4 address to check.
99     :type ip_address: str
100     :returns: True if IP address is correct.
101     :rtype: bool
102     :raises AttributeError, AddressValueError: If IP address is not valid.
103     """
104     try:
105         ipaddress.IPv4Address(ip_address)
106         return True
107     except (AttributeError, ipaddress.AddressValueError):
108         return False
109
110
111 def valid_ipv6(ip_address):
112     """Check IPv6 address.
113
114     :param ip_address: IPv6 address to check.
115     :type ip_address: str
116     :returns: True if IP address is correct.
117     :rtype: bool
118     :raises AttributeError, AddressValueError: If IP address is not valid.
119     """
120     try:
121         ipaddress.IPv6Address(ip_address)
122         return True
123     except (AttributeError, ipaddress.AddressValueError):
124         return False
125
126
127 def main():
128     """Send IP ICMP packet from one traffic generator interface to the other.
129
130     :raises RuntimeError: If the received packet is not correct."""
131
132     args = TrafficScriptArg(
133         [
134             u"tg_src_mac", u"tg_dst_mac", u"src_ip", u"dst_ip", u"dut_if1_mac",
135             u"dut_if2_mac", u"src_rloc", u"dst_rloc"
136         ],
137         [u"ot_mode"]
138     )
139
140     tx_src_mac = args.get_arg(u"tg_src_mac")
141     tx_dst_mac = args.get_arg(u"dut_if1_mac")
142     rx_dst_mac = args.get_arg(u"tg_dst_mac")
143     rx_src_mac = args.get_arg(u"dut_if2_mac")
144     src_ip = args.get_arg(u"src_ip")
145     dst_ip = args.get_arg(u"dst_ip")
146     src_rloc = args.get_arg(u"src_rloc")
147     dst_rloc = args.get_arg(u"dst_rloc")
148     tx_if = args.get_arg(u"tx_if")
149     rx_if = args.get_arg(u"rx_if")
150     ot_mode = args.get_arg(u"ot_mode")
151
152     rxq = RxQueue(rx_if)
153     txq = TxQueue(tx_if)
154
155     pkt_raw = Ether(src=tx_src_mac, dst=tx_dst_mac)
156
157     if valid_ipv4(src_ip) and valid_ipv4(dst_ip):
158         pkt_raw /= IP(src=src_ip, dst=dst_ip)
159         pkt_raw /= ICMP()
160         ip_format = IP
161     elif valid_ipv6(src_ip) and valid_ipv6(dst_ip):
162         pkt_raw /= IPv6(src=src_ip, dst=dst_ip)
163         pkt_raw /= ICMPv6EchoRequest()
164         ip_format = IPv6
165     else:
166         raise ValueError(u"IP not in correct format")
167
168     bind_layers(UDP, LispGPEHeader, dport=4341)
169
170     pkt_raw /= Raw()
171     sent_packets = list()
172     sent_packets.append(pkt_raw)
173     txq.send(pkt_raw)
174
175     while True:
176         if tx_if == rx_if:
177             ether = rxq.recv(2, ignore=sent_packets)
178         else:
179             ether = rxq.recv(2)
180
181         if ether is None:
182             raise RuntimeError(u"ICMP echo Rx timeout")
183
184         if ether.haslayer(ICMPv6ND_NS):
185             # read another packet in the queue if the current one is ICMPv6ND_NS
186             continue
187         if ether.haslayer(ICMPv6ND_RA):
188             # read another packet in the queue if the current one is ICMPv6ND_RA
189             continue
190         elif ether.haslayer(ICMPv6MLReport2):
191             # read another packet in the queue if the current one is
192             # ICMPv6MLReport2
193             continue
194
195         # otherwise process the current packet
196         break
197
198     if rx_dst_mac == ether[Ether].dst and rx_src_mac == ether[Ether].src:
199         print(u"MAC addresses match.")
200     else:
201         raise RuntimeError(f"Matching packet unsuccessful: {ether!r}")
202
203     ip = ether.payload
204
205     if ot_mode == u"6to4":
206         if not isinstance(ip, IP):
207             raise RuntimeError(f"Not an IP packet received {ip!r}")
208     elif ot_mode == u"4to6":
209         if not isinstance(ip, IPv6):
210             raise RuntimeError(f"Not an IP packet received {ip!r}")
211     elif not isinstance(ip, ip_format):
212             raise RuntimeError(f"Not an IP packet received {ip!r}")
213
214     lisp = ether.getlayer(LispGPEHeader).underlayer
215     if not lisp:
216         raise RuntimeError(u"Lisp layer not present or parsing failed.")
217
218     # Compare data from packets
219     if src_ip == lisp.src:
220         print(u"Source IP matches source EID.")
221     else:
222         raise RuntimeError(
223             f"Matching Src IP unsuccessful: {src_ip} != {lisp.src}"
224         )
225
226     if dst_ip == lisp.dst:
227         print(u"Destination IP matches destination EID.")
228     else:
229         raise RuntimeError(
230             f"Matching Dst IP unsuccessful: {dst_ip} != {lisp.dst}"
231         )
232
233     if src_rloc == ip.src:
234         print(u"Source RLOC matches configuration.")
235     else:
236         raise RuntimeError(
237             f"Matching Src RLOC unsuccessful: {src_rloc} != {ip.src}"
238         )
239
240     if dst_rloc == ip.dst:
241         print(u"Destination RLOC matches configuration.")
242     else:
243         raise RuntimeError(
244             f"Matching dst RLOC unsuccessful: {dst_rloc} != {ip.dst}"
245         )
246
247     sys.exit(0)
248
249
250 if __name__ == u"__main__":
251     main()