Ignore unexpected ICMPv6 Neighbor Discovery - Neighbor Solicitation packets
[csit.git] / resources / traffic_scripts / ipfix_sessions.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2016 Cisco and/or its affiliates.
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at:
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 """Traffic script - IPFIX listener."""
17
18 import sys
19 from ipaddress import IPv4Address, IPv6Address, AddressValueError
20
21 from scapy.layers.inet import IP, TCP, UDP
22 from scapy.layers.inet6 import IPv6
23 from scapy.layers.l2 import Ether
24
25 from resources.libraries.python.telemetry.IPFIXUtil import IPFIXHandler, \
26     IPFIXData
27 from resources.libraries.python.PacketVerifier import RxQueue, TxQueue, auto_pad
28 from resources.libraries.python.TrafficScriptArg import TrafficScriptArg
29
30
31 def valid_ipv4(ip):
32     """Check if IP address has the correct IPv4 address format.
33
34     :param ip: IP address.
35     :type ip: str
36     :return: True in case of correct IPv4 address format,
37     otherwise return false.
38     :rtype: bool
39     """
40     try:
41         IPv4Address(unicode(ip))
42         return True
43     except (AttributeError, AddressValueError):
44         return False
45
46
47 def valid_ipv6(ip):
48     """Check if IP address has the correct IPv6 address format.
49
50     :param ip: IP address.
51     :type ip: str
52     :return: True in case of correct IPv6 address format,
53     otherwise return false.
54     :rtype: bool
55     """
56     try:
57         IPv6Address(unicode(ip))
58         return True
59     except (AttributeError, AddressValueError):
60         return False
61
62
63 def verify_data(data, count, src_ip, dst_ip, protocol):
64     """Compare data in IPFIX flow report against parameters used to send test
65      packets.
66
67      :param data: Dictionary of fields in IPFIX flow report.
68      :param count: Number of packets expected.
69      :param src_ip: Expected source IP address.
70      :param dst_ip: Expected destination IP address.
71      :param protocol: Expected protocol, TCP or UDP.
72      :type data: dict
73      :type count: int
74      :type src_ip: str
75      :type dst_ip: str
76      :type protocol: scapy.layers
77      """
78
79     # verify packet count
80     if data["packetTotalCount"] != count:
81         raise RuntimeError(
82             "IPFIX reported wrong packet count. Count was {0},"
83             " but should be {1}".format(data["packetTotalCount"], count))
84     # verify IP addresses
85     keys = data.keys()
86     e = "{0} mismatch. Packets used {1}, but were classified as {2}."
87     if valid_ipv4(src_ip) and valid_ipv4(dst_ip):
88         if "IPv4_src" in keys:
89             if data["IPv4_src"] != src_ip:
90                 raise RuntimeError(
91                     e.format("Source IP", src_ip, data["IPv4_src"]))
92         if "IPv4_dst" in keys:
93             if data["IPv4_dst"] != dst_ip:
94                 raise RuntimeError(
95                     e.format("Destination IP", dst_ip, data["IPv4_dst"]))
96     else:
97         if "IPv6_src" in keys:
98             if data["IPv6_src"] != src_ip:
99                 raise RuntimeError(
100                     e.format("Source IP", src_ip, data["IPv6_src"]))
101         if "IPv6_dst" in keys:
102             if data["IPv6_dst"] != dst_ip:
103                 raise RuntimeError(
104                     e.format("Source IP", src_ip, data["IPv6_dst"]))
105     # verify protocol ID
106     if "Protocol_ID" in keys:
107         if protocol == TCP and int(data["Protocol_ID"]) != 6:
108             raise RuntimeError(
109                 "TCP Packets were classified as not TCP.")
110         if protocol == UDP and int(data["Protocol_ID"]) != 17:
111             raise RuntimeError(
112                 "UDP Packets were classified as not UDP.")
113     # return port number
114     for item in ("src_port", "tcp_src_port", "udp_src_port",
115                  "dst_port", "tcp_dst_port", "udp_dst_port"):
116         if item in keys:
117             return int(data[item])
118         else:
119             raise RuntimeError("Data contains no port information.")
120
121
122 def main():
123     """Send packets to VPP, then listen for IPFIX flow report. Verify that
124     the correct packet count was reported."""
125     args = TrafficScriptArg(
126         ['src_mac', 'dst_mac', 'src_ip', 'dst_ip', 'protocol', 'port', 'count',
127          'sessions']
128     )
129
130     dst_mac = args.get_arg('dst_mac')
131     src_mac = args.get_arg('src_mac')
132     src_ip = args.get_arg('src_ip')
133     dst_ip = args.get_arg('dst_ip')
134     tx_if = args.get_arg('tx_if')
135
136     protocol = args.get_arg('protocol')
137     count = int(args.get_arg('count'))
138     sessions = int(args.get_arg('sessions'))
139
140     txq = TxQueue(tx_if)
141     rxq = RxQueue(tx_if)
142
143     # generate simple packet based on arguments
144     ip_version = None
145     if valid_ipv4(src_ip) and valid_ipv4(dst_ip):
146         ip_version = IP
147     elif valid_ipv6(src_ip) and valid_ipv6(dst_ip):
148         ip_version = IPv6
149     else:
150         ValueError("Invalid IP version!")
151
152     if protocol.upper() == 'TCP':
153         protocol = TCP
154     elif protocol.upper() == 'UDP':
155         protocol = UDP
156     else:
157         raise ValueError("Invalid type of protocol!")
158
159     packets = []
160     for x in range(sessions):
161         pkt = (Ether(src=src_mac, dst=dst_mac) /
162                ip_version(src=src_ip, dst=dst_ip) /
163                protocol(sport=x, dport=x))
164         pkt = auto_pad(pkt)
165         packets.append(pkt)
166
167     # do not print details for sent packets
168     verbose = False
169     print("Sending more than one packet. Details will be filtered for "
170           "all packets sent.")
171
172     ignore = []
173     for x in range(sessions):
174         for _ in range(count):
175             txq.send(packets[x], verbose=verbose)
176             ignore.append(packets[x])
177
178     # allow scapy to recognize IPFIX headers and templates
179     ipfix = IPFIXHandler()
180
181     # clear receive buffer
182     while True:
183         pkt = rxq.recv(1, ignore=packets, verbose=verbose)
184         if pkt is None:
185             break
186
187     data = None
188     ports = [x for x in range(sessions)]
189
190     # get IPFIX template and data
191     while True:
192         pkt = rxq.recv(5)
193         if pkt is None:
194             raise RuntimeError("RX timeout")
195
196         if pkt.haslayer("ICMPv6ND_NS"):
197             # read another packet in the queue if the current one is ICMPv6ND_NS
198             continue
199
200         if pkt.haslayer("IPFIXHeader"):
201             if pkt.haslayer("IPFIXTemplate"):
202                 # create or update template for IPFIX data packets
203                 ipfix.update_template(pkt)
204             elif pkt.haslayer("IPFIXData"):
205                 for x in range(sessions):
206                     try:
207                         data = pkt.getlayer(IPFIXData, x+1).fields
208                     except AttributeError:
209                         raise RuntimeError("Could not find data layer "
210                                            "#{0}".format(x+1))
211                     port = verify_data(data, count, src_ip, dst_ip, protocol)
212                     if port in ports:
213                         ports.remove(port)
214                     else:
215                         raise RuntimeError("Unexpected or duplicate port {0} "
216                                            "in flow report.".format(port))
217                 print("All {0} sessions verified "
218                       "with packet count {1}.".format(sessions, count))
219                 sys.exit(0)
220             else:
221                 raise RuntimeError("Unable to parse IPFIX template "
222                                    "or data set.")
223         else:
224             raise RuntimeError("Received non-IPFIX packet or IPFIX header was"
225                                "not recognized.")
226
227
228 if __name__ == "__main__":
229     main()