c388348b3b58f758ff20b2ffa3bfcf95d9d80324
[csit.git] / GPL / traffic_scripts / lisp / lisp_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 LISP-encapsulated packet on the other interface and verifies received packet.
28 """
29
30 import sys
31 import ipaddress
32
33 from scapy.all import bind_layers, Packet
34 from scapy.fields import FlagsField, BitField, IntField
35 from scapy.layers.inet import ICMP, IP, UDP
36 from scapy.layers.inet6 import ICMPv6EchoRequest
37 from scapy.layers.inet6 import IPv6, ICMPv6ND_NS, ICMPv6MLReport2, ICMPv6ND_RA
38 from scapy.layers.l2 import Ether
39 from scapy.packet import Raw
40
41 from ..PacketVerifier import RxQueue, TxQueue
42 from ..TrafficScriptArg import TrafficScriptArg
43
44
45 class LispHeader(Packet):
46     """Scapy header for the LISP Layer."""
47
48     name = u"Lisp Header"
49     fields_desc = [
50         FlagsField(
51             u"flags", None, 8, [u"N", u"L", u"E", u"V", u"I", u"", u"", u""]
52         ),
53         BitField(u"nonce/map_version", 0, size=24),
54         IntField(u"instance_id/locator_status_bits", 0)]
55
56
57 class LispInnerIP(IP):
58     """Scapy inner LISP layer for IPv4-in-IPv4."""
59
60     name = u"Lisp Inner Layer - IPv4"
61
62
63 class LispInnerIPv6(IPv6):
64     """Scapy inner LISP layer for IPv6-in-IPv6."""
65
66     name = u"Lisp Inner Layer - IPv6"
67
68
69 def valid_ipv4(ip_address):
70     """Check IPv4 address.
71
72     :param ip_address: IPv4 address to check.
73     :type ip_address: str
74     :returns: True if IP address is correct.
75     :rtype: bool
76     :raises AttributeError, AddressValueError: If IP address is not valid.
77     """
78     try:
79         ipaddress.IPv4Address(ip_address)
80         return True
81     except (AttributeError, ipaddress.AddressValueError):
82         return False
83
84
85 def valid_ipv6(ip_address):
86     """Check IPv6 address.
87
88     :param ip_address: IPv6 address to check.
89     :type ip_address: str
90     :returns: True if IP address is correct.
91     :rtype: bool
92     :raises AttributeError, AddressValueError: If IP address is not valid.
93     """
94     try:
95         ipaddress.IPv6Address(ip_address)
96         return True
97     except (AttributeError, ipaddress.AddressValueError):
98         return False
99
100
101 def main():
102     """Send IP ICMP packet from one traffic generator interface to the other.
103
104     :raises RuntimeError: If the received packet is not correct.
105     """
106
107     args = TrafficScriptArg(
108         [
109             u"tg_src_mac", u"tg_dst_mac", u"src_ip", u"dst_ip", u"dut_if1_mac",
110             u"dut_if2_mac", u"src_rloc", u"dst_rloc"
111         ],
112         [u"ot_mode"]
113     )
114
115     tx_src_mac = args.get_arg(u"tg_src_mac")
116     tx_dst_mac = args.get_arg(u"dut_if1_mac")
117     rx_dst_mac = args.get_arg(u"tg_dst_mac")
118     rx_src_mac = args.get_arg(u"dut_if2_mac")
119     src_ip = args.get_arg(u"src_ip")
120     dst_ip = args.get_arg(u"dst_ip")
121     src_rloc = args.get_arg(u"src_rloc")
122     dst_rloc = args.get_arg(u"dst_rloc")
123     tx_if = args.get_arg(u"tx_if")
124     rx_if = args.get_arg(u"rx_if")
125     ot_mode = args.get_arg(u"ot_mode")
126
127     rxq = RxQueue(rx_if)
128     txq = TxQueue(tx_if)
129
130     pkt_raw = Ether(src=tx_src_mac, dst=tx_dst_mac)
131
132     if valid_ipv4(src_ip) and valid_ipv4(dst_ip):
133         pkt_raw /= IP(src=src_ip, dst=dst_ip)
134         pkt_raw /= ICMP()
135         ip_format = IP
136         lisp_layer = LispInnerIP
137     elif valid_ipv6(src_ip) and valid_ipv6(dst_ip):
138         pkt_raw /= IPv6(src=src_ip, dst=dst_ip)
139         pkt_raw /= ICMPv6EchoRequest()
140         ip_format = IPv6
141         lisp_layer = LispInnerIPv6
142     else:
143         raise ValueError(u"IP not in correct format")
144
145     bind_layers(UDP, LispHeader, dport=4341)
146     bind_layers(LispHeader, lisp_layer)
147
148     pkt_raw /= Raw()
149     sent_packets = list()
150     sent_packets.append(pkt_raw)
151     txq.send(pkt_raw)
152
153     while True:
154         if tx_if == rx_if:
155             ether = rxq.recv(2, ignore=sent_packets)
156         else:
157             ether = rxq.recv(2)
158
159         if ether is None:
160             raise RuntimeError(u"ICMP echo Rx timeout")
161
162         if ether.haslayer(ICMPv6ND_NS):
163             # read another packet in the queue if the current one is ICMPv6ND_NS
164             continue
165         elif ether.haslayer(ICMPv6MLReport2):
166             # read another packet in the queue if the current one is
167             # ICMPv6MLReport2
168             continue
169         elif ether.haslayer(ICMPv6ND_RA):
170             # read another packet in the queue if the current one is
171             # ICMPv6ND_RA
172             continue
173
174         # otherwise process the current packet
175         break
176
177     if rx_dst_mac == ether[Ether].dst and rx_src_mac == ether[Ether].src:
178         print(u"MAC addresses match.")
179     else:
180         raise RuntimeError(f"Matching packet unsuccessful: {ether!r}")
181
182     ip = ether.payload
183
184     if ot_mode == u"6to4":
185         if not isinstance(ip, IP):
186             raise RuntimeError(f"Not an IP packet received {ip!r}")
187     elif ot_mode == u"4to6":
188         if not isinstance(ip, IPv6):
189             raise RuntimeError(f"Not an IP packet received {ip!r}")
190     elif not isinstance(ip, ip_format):
191             raise RuntimeError(f"Not an IP packet received {ip!r}")
192
193     lisp = ether.getlayer(lisp_layer)
194     if not lisp:
195         raise RuntimeError("Lisp layer not present or parsing failed.")
196
197     # Compare data from packets
198     if src_ip == lisp.src:
199         print(u"Source IP matches source EID.")
200     else:
201         raise RuntimeError(
202             f"Matching Src IP unsuccessful: {src_ip} != {lisp.src}"
203         )
204
205     if dst_ip == lisp.dst:
206         print(u"Destination IP matches destination EID.")
207     else:
208         raise RuntimeError(
209             f"Matching Dst IP unsuccessful: {dst_ip} != {lisp.dst}"
210         )
211
212     if src_rloc == ip.src:
213         print(u"Source RLOC matches configuration.")
214     else:
215         raise RuntimeError(
216             f"Matching Src RLOC unsuccessful: {src_rloc} != {ip.src}"
217         )
218
219     if dst_rloc == ip.dst:
220         print(u"Destination RLOC matches configuration.")
221     else:
222         raise RuntimeError(
223             f"Matching dst RLOC unsuccessful: {dst_rloc} != {ip.dst}"
224         )
225
226     sys.exit(0)
227
228
229 if __name__ == u"__main__":
230     main()