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:
8 # http://www.apache.org/licenses/LICENSE-2.0
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.
16 """Traffic script - IPFIX listener."""
19 from ipaddress import IPv4Address, IPv6Address, AddressValueError
21 from scapy.layers.inet import IP, TCP, UDP
22 from scapy.layers.inet6 import IPv6
23 from scapy.layers.l2 import Ether
25 from resources.libraries.python.telemetry.IPFIXUtil import IPFIXHandler, \
27 from resources.libraries.python.PacketVerifier import RxQueue, TxQueue, auto_pad
28 from resources.libraries.python.TrafficScriptArg import TrafficScriptArg
32 """Check if IP address has the correct IPv4 address format.
34 :param ip: IP address.
36 :return: True in case of correct IPv4 address format,
37 otherwise return false.
41 IPv4Address(unicode(ip))
43 except (AttributeError, AddressValueError):
48 """Check if IP address has the correct IPv6 address format.
50 :param ip: IP address.
52 :return: True in case of correct IPv6 address format,
53 otherwise return false.
57 IPv6Address(unicode(ip))
59 except (AttributeError, AddressValueError):
63 def verify_data(data, count, src_ip, dst_ip, protocol):
64 """Compare data in IPFIX flow report against parameters used to send test
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.
76 :type protocol: scapy.layers
80 if data["packetTotalCount"] != count:
82 "IPFIX reported wrong packet count. Count was {0},"
83 " but should be {1}".format(data["packetTotalCount"], count))
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:
91 e.format("Source IP", src_ip, data["IPv4_src"]))
92 if "IPv4_dst" in keys:
93 if data["IPv4_dst"] != dst_ip:
95 e.format("Destination IP", dst_ip, data["IPv4_dst"]))
97 if "IPv6_src" in keys:
98 if data["IPv6_src"] != src_ip:
100 e.format("Source IP", src_ip, data["IPv6_src"]))
101 if "IPv6_dst" in keys:
102 if data["IPv6_dst"] != dst_ip:
104 e.format("Source IP", src_ip, data["IPv6_dst"]))
106 if "Protocol_ID" in keys:
107 if protocol == TCP and int(data["Protocol_ID"]) != 6:
109 "TCP Packets were classified as not TCP.")
110 if protocol == UDP and int(data["Protocol_ID"]) != 17:
112 "UDP Packets were classified as not UDP.")
114 for item in ("src_port", "tcp_src_port", "udp_src_port",
115 "dst_port", "tcp_dst_port", "udp_dst_port"):
117 return int(data[item])
119 raise RuntimeError("Data contains no port information.")
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',
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')
136 protocol = args.get_arg('protocol')
137 count = int(args.get_arg('count'))
138 sessions = int(args.get_arg('sessions'))
143 # generate simple packet based on arguments
145 if valid_ipv4(src_ip) and valid_ipv4(dst_ip):
147 elif valid_ipv6(src_ip) and valid_ipv6(dst_ip):
150 ValueError("Invalid IP version!")
152 if protocol.upper() == 'TCP':
154 elif protocol.upper() == 'UDP':
157 raise ValueError("Invalid type of protocol!")
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))
167 # do not print details for sent packets
169 print("Sending more than one packet. Details will be filtered for "
173 for x in range(sessions):
174 for _ in range(count):
175 txq.send(packets[x], verbose=verbose)
176 ignore.append(packets[x])
178 # allow scapy to recognize IPFIX headers and templates
179 ipfix = IPFIXHandler()
181 # clear receive buffer
183 pkt = rxq.recv(1, ignore=packets, verbose=verbose)
188 ports = [x for x in range(sessions)]
190 # get IPFIX template and data
194 raise RuntimeError("RX timeout")
196 if pkt.haslayer("ICMPv6ND_NS"):
197 # read another packet in the queue if the current one is ICMPv6ND_NS
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):
207 data = pkt.getlayer(IPFIXData, x+1).fields
208 except AttributeError:
209 raise RuntimeError("Could not find data layer "
211 port = verify_data(data, count, src_ip, dst_ip, protocol)
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))
221 raise RuntimeError("Unable to parse IPFIX template "
224 raise RuntimeError("Received non-IPFIX packet or IPFIX header was"
228 if __name__ == "__main__":